AdithyaSK HF Staff commited on
Commit
ff22d1e
·
verified ·
1 Parent(s): b4100d4

Stage Harbor release files 60501-61000

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/imgs/access_request.png +3 -0
  2. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/imgs/diffusers_library.jpg +3 -0
  3. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/index.md +35 -0
  4. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/installation.md +146 -0
  5. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/modular_diffusers/auto_pipeline_blocks.md +156 -0
  6. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/modular_diffusers/components_manager.md +190 -0
  7. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/modular_diffusers/custom_blocks.md +492 -0
  8. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/modular_diffusers/guiders.md +175 -0
  9. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/modular_diffusers/loop_sequential_pipeline_blocks.md +92 -0
  10. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/modular_diffusers/modular_diffusers_states.md +75 -0
  11. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/modular_diffusers/modular_pipeline.md +358 -0
  12. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/modular_diffusers/overview.md +41 -0
  13. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/modular_diffusers/pipeline_block.md +105 -0
  14. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/modular_diffusers/quickstart.md +344 -0
  15. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/modular_diffusers/sequential_pipeline_blocks.md +113 -0
  16. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/attention_backends.md +155 -0
  17. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/cache.md +69 -0
  18. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/cache_dit.md +270 -0
  19. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/coreml.md +161 -0
  20. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/deepcache.md +62 -0
  21. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/fp16.md +306 -0
  22. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/habana.md +31 -0
  23. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/memory.md +625 -0
  24. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/mps.md +82 -0
  25. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/neuron.md +58 -0
  26. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/onnx.md +83 -0
  27. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/open_vino.md +80 -0
  28. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/para_attn.md +497 -0
  29. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/pruna.md +187 -0
  30. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/speed-memory-optims.md +203 -0
  31. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/tgate.md +182 -0
  32. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/tome.md +96 -0
  33. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/xdit.md +121 -0
  34. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/xformers.md +29 -0
  35. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/quantization/bitsandbytes.md +452 -0
  36. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/quantization/gguf.md +120 -0
  37. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/quantization/modelopt.md +141 -0
  38. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/quantization/overview.md +141 -0
  39. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/quantization/quanto.md +148 -0
  40. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/quantization/torchao.md +189 -0
  41. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/quicktour.md +232 -0
  42. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/stable_diffusion.md +132 -0
  43. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/training/adapt_a_model.md +47 -0
  44. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/training/cogvideox.md +291 -0
  45. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/training/controlnet.md +278 -0
  46. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/training/create_dataset.md +84 -0
  47. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/training/custom_diffusion.md +354 -0
  48. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/training/ddpo.md +17 -0
  49. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/training/distributed_inference.md +292 -0
  50. tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/training/dreambooth.md +551 -0
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/imgs/access_request.png ADDED

Git LFS Details

  • SHA256: 9688dabf75e180590251cd1f75d18966f9c94d5d6584bc7d0278b698c175c61f
  • Pointer size: 131 Bytes
  • Size of remote file: 105 kB
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/imgs/diffusers_library.jpg ADDED

Git LFS Details

  • SHA256: be2485d6656bec11b85f469b2bc04736a8de8270fa2f3779d9d40bfab3966950
  • Pointer size: 130 Bytes
  • Size of remote file: 14.1 kB
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/index.md ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ <p align="center">
14
+ <br>
15
+ <img src="https://raw.githubusercontent.com/huggingface/diffusers/77aadfee6a891ab9fcfb780f87c693f7a5beeb8e/docs/source/imgs/diffusers_library.jpg" width="400" style="border: none;"/>
16
+ <br>
17
+ </p>
18
+
19
+ # Diffusers
20
+
21
+ Diffusers is a library of state-of-the-art pretrained diffusion models for generating videos, images, and audio.
22
+
23
+ The library revolves around the [`DiffusionPipeline`], an API designed for:
24
+
25
+ - easy inference with only a few lines of code
26
+ - flexibility to mix-and-match pipeline components (models, schedulers)
27
+ - loading and using adapters like LoRA
28
+
29
+ Diffusers also comes with optimizations - such as offloading and quantization - to ensure even the largest models are accessible on memory-constrained devices. If memory is not an issue, Diffusers supports torch.compile to boost inference speed.
30
+
31
+ Get started right away with a Diffusers model on the [Hub](https://huggingface.co/models?library=diffusers&sort=trending) today!
32
+
33
+ ## Learn
34
+
35
+ If you're a beginner, we recommend starting with the [Hugging Face Diffusion Models Course](https://huggingface.co/learn/diffusion-course/unit0/1). You'll learn the theory behind diffusion models, and learn how to use the Diffusers library to generate images, fine-tune your own models, and more.
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/installation.md ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Installation
14
+
15
+ Diffusers is tested on Python 3.8+ and PyTorch 1.4+. Install [PyTorch](https://pytorch.org/get-started/locally/) according to your system and setup.
16
+
17
+ Create a [virtual environment](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/) for easier management of separate projects and to avoid compatibility issues between dependencies. Use [uv](https://docs.astral.sh/uv/), a Rust-based Python package and project manager, to create a virtual environment and install Diffusers.
18
+
19
+ ```bash
20
+ uv venv my-env
21
+ source my-env/bin/activate
22
+ ```
23
+
24
+ Install Diffusers with one of the following methods.
25
+
26
+ <hfoptions id="install">
27
+ <hfoption id="pip">
28
+
29
+ PyTorch only supports Python 3.8 - 3.11 on Windows.
30
+
31
+ ```bash
32
+ uv pip install diffusers["torch"] transformers
33
+ ```
34
+
35
+ </hfoption>
36
+ <hfoption id="conda">
37
+
38
+ ```bash
39
+ conda install -c conda-forge diffusers
40
+ ```
41
+
42
+ </hfoption>
43
+ <hfoption id="source">
44
+
45
+ A source install installs the `main` version instead of the latest `stable` version. The `main` version is useful for staying updated with the latest changes but it may not always be stable. If you run into a problem, open an [Issue](https://github.com/huggingface/diffusers/issues/new/choose) and we will try to resolve it as soon as possible.
46
+
47
+ Make sure [Accelerate](https://huggingface.co/docs/accelerate/index) is installed.
48
+
49
+ ```bash
50
+ uv pip install accelerate
51
+ ```
52
+
53
+ Install Diffusers from source with the command below.
54
+
55
+ ```bash
56
+ uv pip install git+https://github.com/huggingface/diffusers
57
+ ```
58
+
59
+ </hfoption>
60
+ </hfoptions>
61
+
62
+ ## Editable install
63
+
64
+ An editable install is recommended for development workflows or if you're using the `main` version of the source code. A special link is created between the cloned repository and the Python library paths. This avoids reinstalling a package after every change.
65
+
66
+ Clone the repository and install Diffusers with the following commands.
67
+
68
+ ```bash
69
+ git clone https://github.com/huggingface/diffusers.git
70
+ cd diffusers
71
+ uv pip install -e ".[torch]"
72
+ ```
73
+
74
+ > [!WARNING]
75
+ > You must keep the `diffusers` folder if you want to keep using the library with the editable install.
76
+
77
+ Update your cloned repository to the latest version of Diffusers with the command below.
78
+
79
+ ```bash
80
+ cd ~/diffusers/
81
+ git pull
82
+ ```
83
+
84
+ ## Cache
85
+
86
+ Model weights and files are downloaded from the Hub to a cache, which is usually your home directory. Change the cache location with the [HF_HOME](https://huggingface.co/docs/huggingface_hub/package_reference/environment_variables#hfhome) or [HF_HUB_CACHE](https://huggingface.co/docs/huggingface_hub/package_reference/environment_variables#hfhubcache) environment variables or configuring the `cache_dir` parameter in methods like [`~DiffusionPipeline.from_pretrained`].
87
+
88
+ <hfoptions id="cache">
89
+ <hfoption id="env variable">
90
+
91
+ ```bash
92
+ export HF_HOME="/path/to/your/cache"
93
+ export HF_HUB_CACHE="/path/to/your/hub/cache"
94
+ ```
95
+
96
+ </hfoption>
97
+ <hfoption id="from_pretrained">
98
+
99
+ ```py
100
+ from diffusers import DiffusionPipeline
101
+
102
+ pipeline = DiffusionPipeline.from_pretrained(
103
+ "black-forest-labs/FLUX.1-dev",
104
+ cache_dir="/path/to/your/cache"
105
+ )
106
+ ```
107
+
108
+ </hfoption>
109
+ </hfoptions>
110
+
111
+ Cached files allow you to use Diffusers offline. Set the [HF_HUB_OFFLINE](https://huggingface.co/docs/huggingface_hub/package_reference/environment_variables#hfhuboffline) environment variable to `1` to prevent Diffusers from connecting to the internet.
112
+
113
+ ```shell
114
+ export HF_HUB_OFFLINE=1
115
+ ```
116
+
117
+ For more details about managing and cleaning the cache, take a look at the [Understand caching](https://huggingface.co/docs/huggingface_hub/guides/manage-cache) guide.
118
+
119
+ ## Telemetry logging
120
+
121
+ Diffusers gathers telemetry information during [`~DiffusionPipeline.from_pretrained`] requests.
122
+ The data gathered includes the Diffusers and PyTorch version, the requested model or pipeline class,
123
+ and the path to a pretrained checkpoint if it is hosted on the Hub.
124
+
125
+ This usage data helps us debug issues and prioritize new features.
126
+ Telemetry is only sent when loading models and pipelines from the Hub,
127
+ and it is not collected if you're loading local files.
128
+
129
+ Opt-out and disable telemetry collection with the [HF_HUB_DISABLE_TELEMETRY](https://huggingface.co/docs/huggingface_hub/package_reference/environment_variables#hfhubdisabletelemetry) environment variable.
130
+
131
+ <hfoptions id="telemetry">
132
+ <hfoption id="Linux/macOS">
133
+
134
+ ```bash
135
+ export HF_HUB_DISABLE_TELEMETRY=1
136
+ ```
137
+
138
+ </hfoption>
139
+ <hfoption id="Windows">
140
+
141
+ ```bash
142
+ set HF_HUB_DISABLE_TELEMETRY=1
143
+ ```
144
+
145
+ </hfoption>
146
+ </hfoptions>
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/modular_diffusers/auto_pipeline_blocks.md ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # AutoPipelineBlocks
14
+
15
+ [`~modular_pipelines.AutoPipelineBlocks`] are a multi-block type containing blocks that support different workflows. It automatically selects which sub-blocks to run based on the input provided at runtime. This is typically used to package multiple workflows - text-to-image, image-to-image, inpaint - into a single pipeline for convenience.
16
+
17
+ This guide shows how to create [`~modular_pipelines.AutoPipelineBlocks`].
18
+
19
+ Create three [`~modular_pipelines.ModularPipelineBlocks`] for text-to-image, image-to-image, and inpainting. These represent the different workflows available in the pipeline.
20
+
21
+ <hfoptions id="auto">
22
+ <hfoption id="text-to-image">
23
+
24
+ ```py
25
+ import torch
26
+ from diffusers.modular_pipelines import ModularPipelineBlocks, InputParam, OutputParam
27
+
28
+ class TextToImageBlock(ModularPipelineBlocks):
29
+ model_name = "text2img"
30
+
31
+ @property
32
+ def inputs(self):
33
+ return [InputParam(name="prompt")]
34
+
35
+ @property
36
+ def intermediate_outputs(self):
37
+ return []
38
+
39
+ @property
40
+ def description(self):
41
+ return "I'm a text-to-image workflow!"
42
+
43
+ def __call__(self, components, state):
44
+ block_state = self.get_block_state(state)
45
+ print("running the text-to-image workflow")
46
+ # Add your text-to-image logic here
47
+ # For example: generate image from prompt
48
+ self.set_block_state(state, block_state)
49
+ return components, state
50
+ ```
51
+
52
+
53
+ </hfoption>
54
+ <hfoption id="image-to-image">
55
+
56
+ ```py
57
+ class ImageToImageBlock(ModularPipelineBlocks):
58
+ model_name = "img2img"
59
+
60
+ @property
61
+ def inputs(self):
62
+ return [InputParam(name="prompt"), InputParam(name="image")]
63
+
64
+ @property
65
+ def intermediate_outputs(self):
66
+ return []
67
+
68
+ @property
69
+ def description(self):
70
+ return "I'm an image-to-image workflow!"
71
+
72
+ def __call__(self, components, state):
73
+ block_state = self.get_block_state(state)
74
+ print("running the image-to-image workflow")
75
+ # Add your image-to-image logic here
76
+ # For example: transform input image based on prompt
77
+ self.set_block_state(state, block_state)
78
+ return components, state
79
+ ```
80
+
81
+
82
+ </hfoption>
83
+ <hfoption id="inpaint">
84
+
85
+ ```py
86
+ class InpaintBlock(ModularPipelineBlocks):
87
+ model_name = "inpaint"
88
+
89
+ @property
90
+ def inputs(self):
91
+ return [InputParam(name="prompt"), InputParam(name="image"), InputParam(name="mask")]
92
+
93
+ @property
94
+ def intermediate_outputs(self):
95
+ return []
96
+
97
+ @property
98
+ def description(self):
99
+ return "I'm an inpaint workflow!"
100
+
101
+ def __call__(self, components, state):
102
+ block_state = self.get_block_state(state)
103
+ print("running the inpaint workflow")
104
+ # Add your inpainting logic here
105
+ # For example: fill masked areas based on prompt
106
+ self.set_block_state(state, block_state)
107
+ return components, state
108
+ ```
109
+
110
+ </hfoption>
111
+ </hfoptions>
112
+
113
+ Create an [`~modular_pipelines.AutoPipelineBlocks`] class that includes a list of the sub-block classes and their corresponding block names.
114
+
115
+ You also need to include `block_trigger_inputs`, a list of input names that trigger the corresponding block. If a trigger input is provided at runtime, then that block is selected to run. Use `None` to specify the default block to run if no trigger inputs are detected.
116
+
117
+ Lastly, it is important to include a `description` that clearly explains which inputs trigger which workflow. This helps users understand how to run specific workflows.
118
+
119
+ ```py
120
+ from diffusers.modular_pipelines import AutoPipelineBlocks
121
+
122
+ class AutoImageBlocks(AutoPipelineBlocks):
123
+ # List of sub-block classes to choose from
124
+ block_classes = [block_inpaint_cls, block_i2i_cls, block_t2i_cls]
125
+ # Names for each block in the same order
126
+ block_names = ["inpaint", "img2img", "text2img"]
127
+ # Trigger inputs that determine which block to run
128
+ # - "mask" triggers inpaint workflow
129
+ # - "image" triggers img2img workflow (but only if mask is not provided)
130
+ # - if none of above, runs the text2img workflow (default)
131
+ block_trigger_inputs = ["mask", "image", None]
132
+ # Description is extremely important for AutoPipelineBlocks
133
+
134
+ def description(self):
135
+ return (
136
+ "Pipeline generates images given different types of conditions!\n"
137
+ + "This is an auto pipeline block that works for text2img, img2img and inpainting tasks.\n"
138
+ + " - inpaint workflow is run when `mask` is provided.\n"
139
+ + " - img2img workflow is run when `image` is provided (but only when `mask` is not provided).\n"
140
+ + " - text2img workflow is run when neither `image` nor `mask` is provided.\n"
141
+ )
142
+ ```
143
+
144
+ It is **very** important to include a `description` to avoid any confusion over how to run a block and what inputs are required. While [`~modular_pipelines.AutoPipelineBlocks`] are convenient, it's conditional logic may be difficult to figure out if it isn't properly explained.
145
+
146
+ Create an instance of `AutoImageBlocks`.
147
+
148
+ ```py
149
+ auto_blocks = AutoImageBlocks()
150
+ ```
151
+
152
+ For more complex compositions, such as nested [`~modular_pipelines.AutoPipelineBlocks`] blocks when they're used as sub-blocks in larger pipelines, use the [`~modular_pipelines.SequentialPipelineBlocks.get_execution_blocks`] method to extract the a block that is actually run based on your input.
153
+
154
+ ```py
155
+ auto_blocks.get_execution_blocks("mask")
156
+ ```
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/modular_diffusers/components_manager.md ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # ComponentsManager
14
+
15
+ The [`ComponentsManager`] is a model registry and management system for Modular Diffusers. It adds and tracks models, stores useful metadata (model size, device placement, adapters), prevents duplicate model instances, and supports offloading.
16
+
17
+ This guide will show you how to use [`ComponentsManager`] to manage components and device memory.
18
+
19
+ ## Add a component
20
+
21
+ The [`ComponentsManager`] should be created alongside a [`ModularPipeline`] in either [`~ModularPipeline.from_pretrained`] or [`~ModularPipelineBlocks.init_pipeline`].
22
+
23
+ > [!TIP]
24
+ > The `collection` parameter is optional but makes it easier to organize and manage components.
25
+
26
+ <hfoptions id="create">
27
+ <hfoption id="from_pretrained">
28
+
29
+ ```py
30
+ from diffusers import ModularPipeline, ComponentsManager
31
+
32
+ comp = ComponentsManager()
33
+ pipe = ModularPipeline.from_pretrained("YiYiXu/modular-demo-auto", components_manager=comp, collection="test1")
34
+ ```
35
+
36
+ </hfoption>
37
+ <hfoption id="init_pipeline">
38
+
39
+ ```py
40
+ from diffusers import ComponentsManager
41
+ from diffusers.modular_pipelines import SequentialPipelineBlocks
42
+ from diffusers.modular_pipelines.stable_diffusion_xl import TEXT2IMAGE_BLOCKS
43
+
44
+ t2i_blocks = SequentialPipelineBlocks.from_blocks_dict(TEXT2IMAGE_BLOCKS)
45
+
46
+ modular_repo_id = "YiYiXu/modular-loader-t2i-0704"
47
+ components = ComponentsManager()
48
+ t2i_pipeline = t2i_blocks.init_pipeline(modular_repo_id, components_manager=components)
49
+ ```
50
+
51
+ </hfoption>
52
+ </hfoptions>
53
+
54
+ Components are only loaded and registered when using [`~ModularPipeline.load_components`] or [`~ModularPipeline.load_components`]. The example below uses [`~ModularPipeline.load_components`] to create a second pipeline that reuses all the components from the first one, and assigns it to a different collection
55
+
56
+ ```py
57
+ pipe.load_components()
58
+ pipe2 = ModularPipeline.from_pretrained("YiYiXu/modular-demo-auto", components_manager=comp, collection="test2")
59
+ ```
60
+
61
+ Use the [`~ModularPipeline.null_component_names`] property to identify any components that need to be loaded, retrieve them with [`~ComponentsManager.get_components_by_names`], and then call [`~ModularPipeline.update_components`] to add the missing components.
62
+
63
+ ```py
64
+ pipe2.null_component_names
65
+ ['text_encoder', 'text_encoder_2', 'tokenizer', 'tokenizer_2', 'image_encoder', 'unet', 'vae', 'scheduler', 'controlnet']
66
+
67
+ comp_dict = comp.get_components_by_names(names=pipe2.null_component_names)
68
+ pipe2.update_components(**comp_dict)
69
+ ```
70
+
71
+ To add individual components, use the [`~ComponentsManager.add`] method. This registers a component with a unique id.
72
+
73
+ ```py
74
+ from diffusers import AutoModel
75
+
76
+ text_encoder = AutoModel.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", subfolder="text_encoder")
77
+ component_id = comp.add("text_encoder", text_encoder)
78
+ comp
79
+ ```
80
+
81
+ Use [`~ComponentsManager.remove`] to remove a component using their id.
82
+
83
+ ```py
84
+ comp.remove("text_encoder_139917733042864")
85
+ ```
86
+
87
+ ## Retrieve a component
88
+
89
+ The [`ComponentsManager`] provides several methods to retrieve registered components.
90
+
91
+ ### get_one
92
+
93
+ The [`~ComponentsManager.get_one`] method returns a single component and supports pattern matching for the `name` parameter. If multiple components match, [`~ComponentsManager.get_one`] returns an error.
94
+
95
+ | Pattern | Example | Description |
96
+ |-------------|----------------------------------|-------------------------------------------|
97
+ | exact | `comp.get_one(name="unet")` | exact name match |
98
+ | wildcard | `comp.get_one(name="unet*")` | names starting with "unet" |
99
+ | exclusion | `comp.get_one(name="!unet")` | exclude components named "unet" |
100
+ | or | `comp.get_one(name="unet&#124;vae")` | name is "unet" or "vae" |
101
+
102
+ [`~ComponentsManager.get_one`] also filters components by the `collection` argument or `load_id` argument.
103
+
104
+ ```py
105
+ comp.get_one(name="unet", collection="sdxl")
106
+ ```
107
+
108
+ ### get_components_by_names
109
+
110
+ The [`~ComponentsManager.get_components_by_names`] method accepts a list of names and returns a dictionary mapping names to components. This is especially useful with [`ModularPipeline`] since they provide lists of required component names and the returned dictionary can be passed directly to [`~ModularPipeline.update_components`].
111
+
112
+ ```py
113
+ component_dict = comp.get_components_by_names(names=["text_encoder", "unet", "vae"])
114
+ {"text_encoder": component1, "unet": component2, "vae": component3}
115
+ ```
116
+
117
+ ## Duplicate detection
118
+
119
+ It is recommended to load model components with [`ComponentSpec`] to assign components with a unique id that encodes their loading parameters. This allows [`ComponentsManager`] to automatically detect and prevent duplicate model instances even when different objects represent the same underlying checkpoint.
120
+
121
+ ```py
122
+ from diffusers import ComponentSpec, ComponentsManager
123
+ from transformers import CLIPTextModel
124
+
125
+ comp = ComponentsManager()
126
+
127
+ # Create ComponentSpec for the first text encoder
128
+ spec = ComponentSpec(name="text_encoder", repo="stabilityai/stable-diffusion-xl-base-1.0", subfolder="text_encoder", type_hint=AutoModel)
129
+ # Create ComponentSpec for a duplicate text encoder (it is same checkpoint, from the same repo/subfolder)
130
+ spec_duplicated = ComponentSpec(name="text_encoder_duplicated", repo="stabilityai/stable-diffusion-xl-base-1.0", subfolder="text_encoder", type_hint=CLIPTextModel)
131
+
132
+ # Load and add both components - the manager will detect they're the same model
133
+ comp.add("text_encoder", spec.load())
134
+ comp.add("text_encoder_duplicated", spec_duplicated.load())
135
+ ```
136
+
137
+ This returns a warning with instructions for removing the duplicate.
138
+
139
+ ```py
140
+ ComponentsManager: adding component 'text_encoder_duplicated_139917580682672', but it has duplicate load_id 'stabilityai/stable-diffusion-xl-base-1.0|text_encoder|null|null' with existing components: text_encoder_139918506246832. To remove a duplicate, call `components_manager.remove('<component_id>')`.
141
+ 'text_encoder_duplicated_139917580682672'
142
+ ```
143
+
144
+ You could also add a component without using [`ComponentSpec`] and duplicate detection still works in most cases even if you're adding the same component under a different name.
145
+
146
+ However, [`ComponentManager`] can't detect duplicates when you load the same component into different objects. In this case, you should load a model with [`ComponentSpec`].
147
+
148
+ ```py
149
+ text_encoder_2 = AutoModel.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", subfolder="text_encoder")
150
+ comp.add("text_encoder", text_encoder_2)
151
+ 'text_encoder_139917732983664'
152
+ ```
153
+
154
+ ## Collections
155
+
156
+ Collections are labels assigned to components for better organization and management. Add a component to a collection with the `collection` argument in [`~ComponentsManager.add`].
157
+
158
+ Only one component per name is allowed in each collection. Adding a second component with the same name automatically removes the first component.
159
+
160
+ ```py
161
+ from diffusers import ComponentSpec, ComponentsManager
162
+
163
+ comp = ComponentsManager()
164
+ # Create ComponentSpec for the first UNet
165
+ spec = ComponentSpec(name="unet", repo="stabilityai/stable-diffusion-xl-base-1.0", subfolder="unet", type_hint=AutoModel)
166
+ # Create ComponentSpec for a different UNet
167
+ spec2 = ComponentSpec(name="unet", repo="RunDiffusion/Juggernaut-XL-v9", subfolder="unet", type_hint=AutoModel, variant="fp16")
168
+
169
+ # Add both UNets to the same collection - the second one will replace the first
170
+ comp.add("unet", spec.load(), collection="sdxl")
171
+ comp.add("unet", spec2.load(), collection="sdxl")
172
+ ```
173
+
174
+ This makes it convenient to work with node-based systems because you can:
175
+
176
+ - Mark all models as loaded from one node with the `collection` label.
177
+ - Automatically replace models when new checkpoints are loaded under the same name.
178
+ - Batch delete all models in a collection when a node is removed.
179
+
180
+ ## Offloading
181
+
182
+ The [`~ComponentsManager.enable_auto_cpu_offload`] method is a global offloading strategy that works across all models regardless of which pipeline is using them. Once enabled, you don't need to worry about device placement if you add or remove components.
183
+
184
+ ```py
185
+ comp.enable_auto_cpu_offload(device="cuda")
186
+ ```
187
+
188
+ All models begin on the CPU and [`ComponentsManager`] moves them to the appropriate device right before they're needed, and moves other models back to the CPU when GPU memory is low.
189
+
190
+ You can set your own rules for which models to offload first.
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/modular_diffusers/custom_blocks.md ADDED
@@ -0,0 +1,492 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
14
+ # Building Custom Blocks
15
+
16
+ [ModularPipelineBlocks](./pipeline_block) are the fundamental building blocks of a [`ModularPipeline`]. You can create custom blocks by defining their inputs, outputs, and computation logic. This guide demonstrates how to create and use a custom block.
17
+
18
+ > [!TIP]
19
+ > Explore the [Modular Diffusers Custom Blocks](https://huggingface.co/collections/diffusers/modular-diffusers-custom-blocks) collection for official custom modular blocks like Nano Banana.
20
+
21
+ ## Project Structure
22
+
23
+ Your custom block project should use the following structure:
24
+
25
+ ```shell
26
+ .
27
+ ├── block.py
28
+ └── modular_config.json
29
+ ```
30
+
31
+ - `block.py` contains the custom block implementation
32
+ - `modular_config.json` contains the metadata needed to load the block
33
+
34
+ ## Example: Florence 2 Inpainting Block
35
+
36
+ In this example we will create a custom block that uses the [Florence 2](https://huggingface.co/docs/transformers/model_doc/florence2) model to process an input image and generate a mask for inpainting.
37
+
38
+ The first step is to define the components that the block will use. In this case, we will need to use the `Florence2ForConditionalGeneration` model and its corresponding processor `AutoProcessor`. When defining components, we must specify the name of the component within our pipeline, model class via `type_hint`, and provide a `pretrained_model_name_or_path` for the component if we intend to load the model weights from a specific repository on the Hub.
39
+
40
+ ```py
41
+ # Inside block.py
42
+ from diffusers.modular_pipelines import (
43
+ ModularPipelineBlocks,
44
+ ComponentSpec,
45
+ )
46
+ from transformers import AutoProcessor, Florence2ForConditionalGeneration
47
+
48
+
49
+ class Florence2ImageAnnotatorBlock(ModularPipelineBlocks):
50
+
51
+ @property
52
+ def expected_components(self):
53
+ return [
54
+ ComponentSpec(
55
+ name="image_annotator",
56
+ type_hint=Florence2ForConditionalGeneration,
57
+ pretrained_model_name_or_path="florence-community/Florence-2-base-ft",
58
+ ),
59
+ ComponentSpec(
60
+ name="image_annotator_processor",
61
+ type_hint=AutoProcessor,
62
+ pretrained_model_name_or_path="florence-community/Florence-2-base-ft",
63
+ ),
64
+ ]
65
+ ```
66
+
67
+ Next, we define the inputs and outputs of the block. The inputs include the image to be annotated, the annotation task, and the annotation prompt. The outputs include the generated mask image and annotations.
68
+
69
+ ```py
70
+ from typing import List, Union
71
+ from PIL import Image, ImageDraw
72
+ import torch
73
+ import numpy as np
74
+
75
+ from diffusers.modular_pipelines import (
76
+ PipelineState,
77
+ ModularPipelineBlocks,
78
+ InputParam,
79
+ ComponentSpec,
80
+ OutputParam,
81
+ )
82
+ from transformers import AutoProcessor, Florence2ForConditionalGeneration
83
+
84
+
85
+ class Florence2ImageAnnotatorBlock(ModularPipelineBlocks):
86
+
87
+ @property
88
+ def expected_components(self):
89
+ return [
90
+ ComponentSpec(
91
+ name="image_annotator",
92
+ type_hint=Florence2ForConditionalGeneration,
93
+ pretrained_model_name_or_path="florence-community/Florence-2-base-ft",
94
+ ),
95
+ ComponentSpec(
96
+ name="image_annotator_processor",
97
+ type_hint=AutoProcessor,
98
+ pretrained_model_name_or_path="florence-community/Florence-2-base-ft",
99
+ ),
100
+ ]
101
+
102
+ @property
103
+ def inputs(self) -> List[InputParam]:
104
+ return [
105
+ InputParam(
106
+ "image",
107
+ type_hint=Union[Image.Image, List[Image.Image]],
108
+ required=True,
109
+ description="Image(s) to annotate",
110
+ ),
111
+ InputParam(
112
+ "annotation_task",
113
+ type_hint=Union[str, List[str]],
114
+ required=True,
115
+ default="<REFERRING_EXPRESSION_SEGMENTATION>",
116
+ description="""Annotation Task to perform on the image.
117
+ Supported Tasks:
118
+
119
+ <OD>
120
+ <REFERRING_EXPRESSION_SEGMENTATION>
121
+ <CAPTION>
122
+ <DETAILED_CAPTION>
123
+ <MORE_DETAILED_CAPTION>
124
+ <DENSE_REGION_CAPTION>
125
+ <CAPTION_TO_PHRASE_GROUNDING>
126
+ <OPEN_VOCABULARY_DETECTION>
127
+
128
+ """,
129
+ ),
130
+ InputParam(
131
+ "annotation_prompt",
132
+ type_hint=Union[str, List[str]],
133
+ required=True,
134
+ description="""Annotation Prompt to provide more context to the task.
135
+ Can be used to detect or segment out specific elements in the image
136
+ """,
137
+ ),
138
+ InputParam(
139
+ "annotation_output_type",
140
+ type_hint=str,
141
+ required=True,
142
+ default="mask_image",
143
+ description="""Output type from annotation predictions. Availabe options are
144
+ mask_image:
145
+ -black and white mask image for the given image based on the task type
146
+ mask_overlay:
147
+ - mask overlayed on the original image
148
+ bounding_box:
149
+ - bounding boxes drawn on the original image
150
+ """,
151
+ ),
152
+ InputParam(
153
+ "annotation_overlay",
154
+ type_hint=bool,
155
+ required=True,
156
+ default=False,
157
+ description="",
158
+ ),
159
+ ]
160
+
161
+ @property
162
+ def intermediate_outputs(self) -> List[OutputParam]:
163
+ return [
164
+ OutputParam(
165
+ "mask_image",
166
+ type_hint=Image,
167
+ description="Inpainting Mask for input Image(s)",
168
+ ),
169
+ OutputParam(
170
+ "annotations",
171
+ type_hint=dict,
172
+ description="Annotations Predictions for input Image(s)",
173
+ ),
174
+ OutputParam(
175
+ "image",
176
+ type_hint=Image,
177
+ description="Annotated input Image(s)",
178
+ ),
179
+ ]
180
+
181
+ ```
182
+
183
+ Now we implement the `__call__` method, which contains the logic for processing the input image and generating the mask.
184
+
185
+ ```py
186
+ from typing import List, Union
187
+ from PIL import Image, ImageDraw
188
+ import torch
189
+ import numpy as np
190
+
191
+ from diffusers.modular_pipelines import (
192
+ PipelineState,
193
+ ModularPipelineBlocks,
194
+ InputParam,
195
+ ComponentSpec,
196
+ OutputParam,
197
+ )
198
+ from transformers import AutoProcessor, Florence2ForConditionalGeneration
199
+
200
+
201
+ class Florence2ImageAnnotatorBlock(ModularPipelineBlocks):
202
+
203
+ @property
204
+ def expected_components(self):
205
+ return [
206
+ ComponentSpec(
207
+ name="image_annotator",
208
+ type_hint=Florence2ForConditionalGeneration,
209
+ pretrained_model_name_or_path="florence-community/Florence-2-base-ft",
210
+ ),
211
+ ComponentSpec(
212
+ name="image_annotator_processor",
213
+ type_hint=AutoProcessor,
214
+ pretrained_model_name_or_path="florence-community/Florence-2-base-ft",
215
+ ),
216
+ ]
217
+
218
+ @property
219
+ def inputs(self) -> List[InputParam]:
220
+ return [
221
+ InputParam(
222
+ "image",
223
+ type_hint=Union[Image.Image, List[Image.Image]],
224
+ required=True,
225
+ description="Image(s) to annotate",
226
+ ),
227
+ InputParam(
228
+ "annotation_task",
229
+ type_hint=Union[str, List[str]],
230
+ required=True,
231
+ default="<REFERRING_EXPRESSION_SEGMENTATION>",
232
+ description="""Annotation Task to perform on the image.
233
+ Supported Tasks:
234
+
235
+ <OD>
236
+ <REFERRING_EXPRESSION_SEGMENTATION>
237
+ <CAPTION>
238
+ <DETAILED_CAPTION>
239
+ <MORE_DETAILED_CAPTION>
240
+ <DENSE_REGION_CAPTION>
241
+ <CAPTION_TO_PHRASE_GROUNDING>
242
+ <OPEN_VOCABULARY_DETECTION>
243
+
244
+ """,
245
+ ),
246
+ InputParam(
247
+ "annotation_prompt",
248
+ type_hint=Union[str, List[str]],
249
+ required=True,
250
+ description="""Annotation Prompt to provide more context to the task.
251
+ Can be used to detect or segment out specific elements in the image
252
+ """,
253
+ ),
254
+ InputParam(
255
+ "annotation_output_type",
256
+ type_hint=str,
257
+ required=True,
258
+ default="mask_image",
259
+ description="""Output type from annotation predictions. Availabe options are
260
+ mask_image:
261
+ -black and white mask image for the given image based on the task type
262
+ mask_overlay:
263
+ - mask overlayed on the original image
264
+ bounding_box:
265
+ - bounding boxes drawn on the original image
266
+ """,
267
+ ),
268
+ InputParam(
269
+ "annotation_overlay",
270
+ type_hint=bool,
271
+ required=True,
272
+ default=False,
273
+ description="",
274
+ ),
275
+ ]
276
+
277
+ @property
278
+ def intermediate_outputs(self) -> List[OutputParam]:
279
+ return [
280
+ OutputParam(
281
+ "mask_image",
282
+ type_hint=Image,
283
+ description="Inpainting Mask for input Image(s)",
284
+ ),
285
+ OutputParam(
286
+ "annotations",
287
+ type_hint=dict,
288
+ description="Annotations Predictions for input Image(s)",
289
+ ),
290
+ OutputParam(
291
+ "image",
292
+ type_hint=Image,
293
+ description="Annotated input Image(s)",
294
+ ),
295
+ ]
296
+
297
+ def get_annotations(self, components, images, prompts, task):
298
+ task_prompts = [task + prompt for prompt in prompts]
299
+
300
+ inputs = components.image_annotator_processor(
301
+ text=task_prompts, images=images, return_tensors="pt"
302
+ ).to(components.image_annotator.device, components.image_annotator.dtype)
303
+
304
+ generated_ids = components.image_annotator.generate(
305
+ input_ids=inputs["input_ids"],
306
+ pixel_values=inputs["pixel_values"],
307
+ max_new_tokens=1024,
308
+ early_stopping=False,
309
+ do_sample=False,
310
+ num_beams=3,
311
+ )
312
+ annotations = components.image_annotator_processor.batch_decode(
313
+ generated_ids, skip_special_tokens=False
314
+ )
315
+ outputs = []
316
+ for image, annotation in zip(images, annotations):
317
+ outputs.append(
318
+ components.image_annotator_processor.post_process_generation(
319
+ annotation, task=task, image_size=(image.width, image.height)
320
+ )
321
+ )
322
+ return outputs
323
+
324
+ def prepare_mask(self, images, annotations, overlay=False, fill="white"):
325
+ masks = []
326
+ for image, annotation in zip(images, annotations):
327
+ mask_image = image.copy() if overlay else Image.new("L", image.size, 0)
328
+ draw = ImageDraw.Draw(mask_image)
329
+
330
+ for _, _annotation in annotation.items():
331
+ if "polygons" in _annotation:
332
+ for polygon in _annotation["polygons"]:
333
+ polygon = np.array(polygon).reshape(-1, 2)
334
+ if len(polygon) < 3:
335
+ continue
336
+ polygon = polygon.reshape(-1).tolist()
337
+ draw.polygon(polygon, fill=fill)
338
+
339
+ elif "bbox" in _annotation:
340
+ bbox = _annotation["bbox"]
341
+ draw.rectangle(bbox, fill="white")
342
+
343
+ masks.append(mask_image)
344
+
345
+ return masks
346
+
347
+ def prepare_bounding_boxes(self, images, annotations):
348
+ outputs = []
349
+ for image, annotation in zip(images, annotations):
350
+ image_copy = image.copy()
351
+ draw = ImageDraw.Draw(image_copy)
352
+ for _, _annotation in annotation.items():
353
+ bbox = _annotation["bbox"]
354
+ label = _annotation["label"]
355
+
356
+ draw.rectangle(bbox, outline="red", width=3)
357
+ draw.text((bbox[0], bbox[1] - 20), label, fill="red")
358
+
359
+ outputs.append(image_copy)
360
+
361
+ return outputs
362
+
363
+ def prepare_inputs(self, images, prompts):
364
+ prompts = prompts or ""
365
+
366
+ if isinstance(images, Image.Image):
367
+ images = [images]
368
+ if isinstance(prompts, str):
369
+ prompts = [prompts]
370
+
371
+ if len(images) != len(prompts):
372
+ raise ValueError("Number of images and annotation prompts must match.")
373
+
374
+ return images, prompts
375
+
376
+ @torch.no_grad()
377
+ def __call__(self, components, state: PipelineState) -> PipelineState:
378
+ block_state = self.get_block_state(state)
379
+ images, annotation_task_prompt = self.prepare_inputs(
380
+ block_state.image, block_state.annotation_prompt
381
+ )
382
+ task = block_state.annotation_task
383
+ fill = block_state.fill
384
+
385
+ annotations = self.get_annotations(
386
+ components, images, annotation_task_prompt, task
387
+ )
388
+ block_state.annotations = annotations
389
+ if block_state.annotation_output_type == "mask_image":
390
+ block_state.mask_image = self.prepare_mask(images, annotations)
391
+ else:
392
+ block_state.mask_image = None
393
+
394
+ if block_state.annotation_output_type == "mask_overlay":
395
+ block_state.image = self.prepare_mask(images, annotations, overlay=True, fill=fill)
396
+
397
+ elif block_state.annotation_output_type == "bounding_box":
398
+ block_state.image = self.prepare_bounding_boxes(images, annotations)
399
+
400
+ self.set_block_state(state, block_state)
401
+
402
+ return components, state
403
+
404
+ ```
405
+
406
+ Once we have defined our custom block, we can save it to the Hub, using either the CLI or the [`push_to_hub`] method. This will make it easy to share and reuse our custom block with other pipelines.
407
+
408
+ <hfoptions id="share">
409
+ <hfoption id="hf CLI">
410
+
411
+ ```shell
412
+ # In the folder with the `block.py` file, run:
413
+ diffusers-cli custom_block
414
+ ```
415
+
416
+ Then upload the block to the Hub:
417
+
418
+ ```shell
419
+ hf upload <your repo id> . .
420
+ ```
421
+ </hfoption>
422
+ <hfoption id="push_to_hub">
423
+
424
+ ```py
425
+ from block import Florence2ImageAnnotatorBlock
426
+ block = Florence2ImageAnnotatorBlock()
427
+ block.push_to_hub("<your repo id>")
428
+ ```
429
+
430
+ </hfoption>
431
+ </hfoptions>
432
+
433
+ ## Using Custom Blocks
434
+
435
+ Load the custom block with [`~ModularPipelineBlocks.from_pretrained`] and set `trust_remote_code=True`.
436
+
437
+ ```py
438
+ import torch
439
+ from diffusers.modular_pipelines import ModularPipelineBlocks, SequentialPipelineBlocks
440
+ from diffusers.modular_pipelines.stable_diffusion_xl import INPAINT_BLOCKS
441
+ from diffusers.utils import load_image
442
+
443
+ # Fetch the Florence2 image annotator block that will create our mask
444
+ image_annotator_block = ModularPipelineBlocks.from_pretrained("diffusers/florence-2-custom-block", trust_remote_code=True)
445
+
446
+ my_blocks = INPAINT_BLOCKS.copy()
447
+ # insert the annotation block before the image encoding step
448
+ my_blocks.insert("image_annotator", image_annotator_block, 1)
449
+
450
+ # Create our initial set of inpainting blocks
451
+ blocks = SequentialPipelineBlocks.from_blocks_dict(my_blocks)
452
+
453
+ repo_id = "diffusers/modular-stable-diffusion-xl-base-1.0"
454
+ pipe = blocks.init_pipeline(repo_id)
455
+ pipe.load_components(torch_dtype=torch.float16, device_map="cuda", trust_remote_code=True)
456
+
457
+ image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/car.jpg?download=true")
458
+ image = image.resize((1024, 1024))
459
+
460
+ prompt = ["A red car"]
461
+ annotation_task = "<REFERRING_EXPRESSION_SEGMENTATION>"
462
+ annotation_prompt = ["the car"]
463
+
464
+ output = pipe(
465
+ prompt=prompt,
466
+ image=image,
467
+ annotation_task=annotation_task,
468
+ annotation_prompt=annotation_prompt,
469
+ annotation_output_type="mask_image",
470
+ num_inference_steps=35,
471
+ guidance_scale=7.5,
472
+ strength=0.95,
473
+ output="images"
474
+ )
475
+ output[0].save("florence-inpainting.png")
476
+ ```
477
+
478
+ ## Editing Custom Blocks
479
+
480
+ By default, custom blocks are saved in your cache directory. Use the `local_dir` argument to download and edit a custom block in a specific folder.
481
+
482
+ ```py
483
+ import torch
484
+ from diffusers.modular_pipelines import ModularPipelineBlocks, SequentialPipelineBlocks
485
+ from diffusers.modular_pipelines.stable_diffusion_xl import INPAINT_BLOCKS
486
+ from diffusers.utils import load_image
487
+
488
+ # Fetch the Florence2 image annotator block that will create our mask
489
+ image_annotator_block = ModularPipelineBlocks.from_pretrained("diffusers/florence-2-custom-block", trust_remote_code=True, local_dir="/my-local-folder")
490
+ ```
491
+
492
+ Any changes made to the block files in this folder will be reflected when you load the block again.
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/modular_diffusers/guiders.md ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Guiders
14
+
15
+ [Classifier-free guidance](https://huggingface.co/papers/2207.12598) steers model generation that better match a prompt and is commonly used to improve generation quality, control, and adherence to prompts. There are different types of guidance methods, and in Diffusers, they are known as *guiders*. Like blocks, it is easy to switch and use different guiders for different use cases without rewriting the pipeline.
16
+
17
+ This guide will show you how to switch guiders, adjust guider parameters, and load and share them to the Hub.
18
+
19
+ ## Switching guiders
20
+
21
+ [`ClassifierFreeGuidance`] is the default guider and created when a pipeline is initialized with [`~ModularPipelineBlocks.init_pipeline`]. It is created by `from_config` which means it doesn't require loading specifications from a modular repository. A guider won't be listed in `modular_model_index.json`.
22
+
23
+ Use [`~ModularPipeline.get_component_spec`] to inspect a guider.
24
+
25
+ ```py
26
+ t2i_pipeline.get_component_spec("guider")
27
+ ComponentSpec(name='guider', type_hint=<class 'diffusers.guiders.classifier_free_guidance.ClassifierFreeGuidance'>, description=None, config=FrozenDict([('guidance_scale', 7.5), ('guidance_rescale', 0.0), ('use_original_formulation', False), ('start', 0.0), ('stop', 1.0), ('_use_default_values', ['start', 'guidance_rescale', 'stop', 'use_original_formulation'])]), repo=None, subfolder=None, variant=None, revision=None, default_creation_method='from_config')
28
+ ```
29
+
30
+ Switch to a different guider by passing the new guider to [`~ModularPipeline.update_components`].
31
+
32
+ > [!TIP]
33
+ > Changing guiders will return text letting you know you're changing the guider type.
34
+ > ```bash
35
+ > ModularPipeline.update_components: adding guider with new type: PerturbedAttentionGuidance, previous type: ClassifierFreeGuidance
36
+ > ```
37
+
38
+ ```py
39
+ from diffusers import LayerSkipConfig, PerturbedAttentionGuidance
40
+
41
+ config = LayerSkipConfig(indices=[2, 9], fqn="mid_block.attentions.0.transformer_blocks", skip_attention=False, skip_attention_scores=True, skip_ff=False)
42
+ guider = PerturbedAttentionGuidance(
43
+ guidance_scale=5.0, perturbed_guidance_scale=2.5, perturbed_guidance_config=config
44
+ )
45
+ t2i_pipeline.update_components(guider=guider)
46
+ ```
47
+
48
+ Use [`~ModularPipeline.get_component_spec`] again to verify the guider type is different.
49
+
50
+ ```py
51
+ t2i_pipeline.get_component_spec("guider")
52
+ ComponentSpec(name='guider', type_hint=<class 'diffusers.guiders.perturbed_attention_guidance.PerturbedAttentionGuidance'>, description=None, config=FrozenDict([('guidance_scale', 5.0), ('perturbed_guidance_scale', 2.5), ('perturbed_guidance_start', 0.01), ('perturbed_guidance_stop', 0.2), ('perturbed_guidance_layers', None), ('perturbed_guidance_config', LayerSkipConfig(indices=[2, 9], fqn='mid_block.attentions.0.transformer_blocks', skip_attention=False, skip_attention_scores=True, skip_ff=False, dropout=1.0)), ('guidance_rescale', 0.0), ('use_original_formulation', False), ('start', 0.0), ('stop', 1.0), ('_use_default_values', ['perturbed_guidance_start', 'use_original_formulation', 'perturbed_guidance_layers', 'stop', 'start', 'guidance_rescale', 'perturbed_guidance_stop']), ('_class_name', 'PerturbedAttentionGuidance'), ('_diffusers_version', '0.35.0.dev0')]), repo=None, subfolder=None, variant=None, revision=None, default_creation_method='from_config')
53
+ ```
54
+
55
+ ## Loading custom guiders
56
+
57
+ Guiders that are already saved on the Hub with a `modular_model_index.json` file are considered a `from_pretrained` component now instead of a `from_config` component.
58
+
59
+ ```json
60
+ {
61
+ "guider": [
62
+ null,
63
+ null,
64
+ {
65
+ "repo": "YiYiXu/modular-loader-t2i-guider",
66
+ "revision": null,
67
+ "subfolder": "pag_guider",
68
+ "type_hint": [
69
+ "diffusers",
70
+ "PerturbedAttentionGuidance"
71
+ ],
72
+ "variant": null
73
+ }
74
+ ]
75
+ }
76
+ ```
77
+
78
+ The guider is only created after calling [`~ModularPipeline.load_components`] based on the loading specification in `modular_model_index.json`.
79
+
80
+ ```py
81
+ t2i_pipeline = t2i_blocks.init_pipeline("YiYiXu/modular-doc-guider")
82
+ # not created during init
83
+ assert t2i_pipeline.guider is None
84
+ t2i_pipeline.load_components()
85
+ # loaded as PAG guider
86
+ t2i_pipeline.guider
87
+ ```
88
+
89
+
90
+ ## Changing guider parameters
91
+
92
+ The guider parameters can be adjusted with either the [`~ComponentSpec.create`] method or with [`~ModularPipeline.update_components`]. The example below changes the `guidance_scale` value.
93
+
94
+ <hfoptions id="switch">
95
+ <hfoption id="create">
96
+
97
+ ```py
98
+ guider_spec = t2i_pipeline.get_component_spec("guider")
99
+ guider = guider_spec.create(guidance_scale=10)
100
+ t2i_pipeline.update_components(guider=guider)
101
+ ```
102
+
103
+ </hfoption>
104
+ <hfoption id="update_components">
105
+
106
+ ```py
107
+ guider_spec = t2i_pipeline.get_component_spec("guider")
108
+ guider_spec.config["guidance_scale"] = 10
109
+ t2i_pipeline.update_components(guider=guider_spec)
110
+ ```
111
+
112
+ </hfoption>
113
+ </hfoptions>
114
+
115
+ ## Uploading custom guiders
116
+
117
+ Call the [`~utils.PushToHubMixin.push_to_hub`] method on a custom guider to share it to the Hub.
118
+
119
+ ```py
120
+ guider.push_to_hub("YiYiXu/modular-loader-t2i-guider", subfolder="pag_guider")
121
+ ```
122
+
123
+ To make this guider available to the pipeline, either modify the `modular_model_index.json` file or use the [`~ModularPipeline.update_components`] method.
124
+
125
+ <hfoptions id="upload">
126
+ <hfoption id="modular_model_index.json">
127
+
128
+ Edit the `modular_model_index.json` file and add a loading specification for the guider by pointing to a folder containing the guider config.
129
+
130
+ ```json
131
+ {
132
+ "guider": [
133
+ "diffusers",
134
+ "PerturbedAttentionGuidance",
135
+ {
136
+ "repo": "YiYiXu/modular-loader-t2i-guider",
137
+ "revision": null,
138
+ "subfolder": "pag_guider",
139
+ "type_hint": [
140
+ "diffusers",
141
+ "PerturbedAttentionGuidance"
142
+ ],
143
+ "variant": null
144
+ }
145
+ ],
146
+ ```
147
+
148
+ </hfoption>
149
+ <hfoption id="update_components">
150
+
151
+ Change the [`~ComponentSpec.default_creation_method`] to `from_pretrained` and use [`~ModularPipeline.update_components`] to update the guider and component specifications as well as the pipeline config.
152
+
153
+ > [!TIP]
154
+ > Changing the creation method will return text letting you know you're changing the creation type to `from_pretrained`.
155
+ > ```bash
156
+ > ModularPipeline.update_components: changing the default_creation_method of guider from from_config to from_pretrained.
157
+ > ```
158
+
159
+ ```py
160
+ guider_spec = t2i_pipeline.get_component_spec("guider")
161
+ guider_spec.default_creation_method="from_pretrained"
162
+ guider_spec.repo="YiYiXu/modular-loader-t2i-guider"
163
+ guider_spec.subfolder="pag_guider"
164
+ pag_guider = guider_spec.load()
165
+ t2i_pipeline.update_components(guider=pag_guider)
166
+ ```
167
+
168
+ To make it the default guider for a pipeline, call [`~utils.PushToHubMixin.push_to_hub`]. This is an optional step and not necessary if you are only experimenting locally.
169
+
170
+ ```py
171
+ t2i_pipeline.push_to_hub("YiYiXu/modular-doc-guider")
172
+ ```
173
+
174
+ </hfoption>
175
+ </hfoptions>
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/modular_diffusers/loop_sequential_pipeline_blocks.md ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # LoopSequentialPipelineBlocks
14
+
15
+ [`~modular_pipelines.LoopSequentialPipelineBlocks`] are a multi-block type that composes other [`~modular_pipelines.ModularPipelineBlocks`] together in a loop. Data flows circularly, using `inputs` and `intermediate_outputs`, and each block is run iteratively. This is typically used to create a denoising loop which is iterative by default.
16
+
17
+ This guide shows you how to create [`~modular_pipelines.LoopSequentialPipelineBlocks`].
18
+
19
+ ## Loop wrapper
20
+
21
+ [`~modular_pipelines.LoopSequentialPipelineBlocks`], is also known as the *loop wrapper* because it defines the loop structure, iteration variables, and configuration. Within the loop wrapper, you need the following variables.
22
+
23
+ - `loop_inputs` are user provided values and equivalent to [`~modular_pipelines.ModularPipelineBlocks.inputs`].
24
+ - `loop_intermediate_outputs` are new intermediate variables created by the block and added to the [`~modular_pipelines.PipelineState`]. It is equivalent to [`~modular_pipelines.ModularPipelineBlocks.intermediate_outputs`].
25
+ - `__call__` method defines the loop structure and iteration logic.
26
+
27
+ ```py
28
+ import torch
29
+ from diffusers.modular_pipelines import LoopSequentialPipelineBlocks, ModularPipelineBlocks, InputParam, OutputParam
30
+
31
+ class LoopWrapper(LoopSequentialPipelineBlocks):
32
+ model_name = "test"
33
+ @property
34
+ def description(self):
35
+ return "I'm a loop!!"
36
+ @property
37
+ def loop_inputs(self):
38
+ return [InputParam(name="num_steps")]
39
+ @torch.no_grad()
40
+ def __call__(self, components, state):
41
+ block_state = self.get_block_state(state)
42
+ # Loop structure - can be customized to your needs
43
+ for i in range(block_state.num_steps):
44
+ # loop_step executes all registered blocks in sequence
45
+ components, block_state = self.loop_step(components, block_state, i=i)
46
+ self.set_block_state(state, block_state)
47
+ return components, state
48
+ ```
49
+
50
+ The loop wrapper can pass additional arguments, like current iteration index, to the loop blocks.
51
+
52
+ ## Loop blocks
53
+
54
+ A loop block is a [`~modular_pipelines.ModularPipelineBlocks`], but the `__call__` method behaves differently.
55
+
56
+ - It recieves the iteration variable from the loop wrapper.
57
+ - It works directly with the [`~modular_pipelines.BlockState`] instead of the [`~modular_pipelines.PipelineState`].
58
+ - It doesn't require retrieving or updating the [`~modular_pipelines.BlockState`].
59
+
60
+ Loop blocks share the same [`~modular_pipelines.BlockState`] to allow values to accumulate and change for each iteration in the loop.
61
+
62
+ ```py
63
+ class LoopBlock(ModularPipelineBlocks):
64
+ model_name = "test"
65
+ @property
66
+ def inputs(self):
67
+ return [InputParam(name="x")]
68
+ @property
69
+ def intermediate_outputs(self):
70
+ # outputs produced by this block
71
+ return [OutputParam(name="x")]
72
+ @property
73
+ def description(self):
74
+ return "I'm a block used inside the `LoopWrapper` class"
75
+ def __call__(self, components, block_state, i: int):
76
+ block_state.x += 1
77
+ return components, block_state
78
+ ```
79
+
80
+ ## LoopSequentialPipelineBlocks
81
+
82
+ Use the [`~modular_pipelines.LoopSequentialPipelineBlocks.from_blocks_dict`] method to add the loop block to the loop wrapper to create [`~modular_pipelines.LoopSequentialPipelineBlocks`].
83
+
84
+ ```py
85
+ loop = LoopWrapper.from_blocks_dict({"block1": LoopBlock})
86
+ ```
87
+
88
+ Add more loop blocks to run within each iteration with [`~modular_pipelines.LoopSequentialPipelineBlocks.from_blocks_dict`]. This allows you to modify the blocks without changing the loop logic itself.
89
+
90
+ ```py
91
+ loop = LoopWrapper.from_blocks_dict({"block1": LoopBlock(), "block2": LoopBlock})
92
+ ```
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/modular_diffusers/modular_diffusers_states.md ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # States
14
+
15
+ Blocks rely on the [`~modular_pipelines.PipelineState`] and [`~modular_pipelines.BlockState`] data structures for communicating and sharing data.
16
+
17
+ | State | Description |
18
+ |-------|-------------|
19
+ | [`~modular_pipelines.PipelineState`] | Maintains the overall data required for a pipeline's execution and allows blocks to read and update its data. |
20
+ | [`~modular_pipelines.BlockState`] | Allows each block to perform its computation with the necessary data from `inputs`|
21
+
22
+ This guide explains how states work and how they connect blocks.
23
+
24
+ ## PipelineState
25
+
26
+ The [`~modular_pipelines.PipelineState`] is a global state container for all blocks. It maintains the complete runtime state of the pipeline and provides a structured way for blocks to read from and write to shared data.
27
+
28
+ There are two dict's in [`~modular_pipelines.PipelineState`] for structuring data.
29
+
30
+ - The `values` dict is a **mutable** state containing a copy of user provided input values and intermediate output values generated by blocks. If a block modifies an `input`, it will be reflected in the `values` dict after calling `set_block_state`.
31
+
32
+ ```py
33
+ PipelineState(
34
+ values={
35
+ 'prompt': 'a cat'
36
+ 'guidance_scale': 7.0
37
+ 'num_inference_steps': 25
38
+ 'prompt_embeds': Tensor(dtype=torch.float32, shape=torch.Size([1, 1, 1, 1]))
39
+ 'negative_prompt_embeds': None
40
+ },
41
+ )
42
+ ```
43
+
44
+ ## BlockState
45
+
46
+ The [`~modular_pipelines.BlockState`] is a local view of the relevant variables an individual block needs from [`~modular_pipelines.PipelineState`] for performing it's computations.
47
+
48
+ Access these variables directly as attributes like `block_state.image`.
49
+
50
+ ```py
51
+ BlockState(
52
+ image: <PIL.Image.Image image mode=RGB size=512x512 at 0x7F3ECC494640>
53
+ )
54
+ ```
55
+
56
+ When a block's `__call__` method is executed, it retrieves the [`BlockState`] with `self.get_block_state(state)`, performs it's operations, and updates [`~modular_pipelines.PipelineState`] with `self.set_block_state(state, block_state)`.
57
+
58
+ ```py
59
+ def __call__(self, components, state):
60
+ # retrieve BlockState
61
+ block_state = self.get_block_state(state)
62
+
63
+ # computation logic on inputs
64
+
65
+ # update PipelineState
66
+ self.set_block_state(state, block_state)
67
+ return components, state
68
+ ```
69
+
70
+ ## State interaction
71
+
72
+ [`~modular_pipelines.PipelineState`] and [`~modular_pipelines.BlockState`] interaction is defined by a block's `inputs`, and `intermediate_outputs`.
73
+
74
+ - `inputs`, a block can modify an input - like `block_state.image` - and this change can be propagated globally to [`~modular_pipelines.PipelineState`] by calling `set_block_state`.
75
+ - `intermediate_outputs`, is a new variable that a block creates. It is added to the [`~modular_pipelines.PipelineState`]'s `values` dict and is available as for subsequent blocks or accessed by users as a final output from the pipeline.
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/modular_diffusers/modular_pipeline.md ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # ModularPipeline
14
+
15
+ [`ModularPipeline`] converts [`~modular_pipelines.ModularPipelineBlocks`]'s into an executable pipeline that loads models and performs the computation steps defined in the block. It is the main interface for running a pipeline and it is very similar to the [`DiffusionPipeline`] API.
16
+
17
+ The main difference is to include an expected `output` argument in the pipeline.
18
+
19
+ <hfoptions id="example">
20
+ <hfoption id="text-to-image">
21
+
22
+ ```py
23
+ import torch
24
+ from diffusers.modular_pipelines import SequentialPipelineBlocks
25
+ from diffusers.modular_pipelines.stable_diffusion_xl import TEXT2IMAGE_BLOCKS
26
+
27
+ blocks = SequentialPipelineBlocks.from_blocks_dict(TEXT2IMAGE_BLOCKS)
28
+
29
+ modular_repo_id = "YiYiXu/modular-loader-t2i-0704"
30
+ pipeline = blocks.init_pipeline(modular_repo_id)
31
+
32
+ pipeline.load_components(torch_dtype=torch.float16)
33
+ pipeline.to("cuda")
34
+
35
+ image = pipeline(prompt="Astronaut in a jungle, cold color palette, muted colors, detailed, 8k", output="images")[0]
36
+ image.save("modular_t2i_out.png")
37
+ ```
38
+
39
+ </hfoption>
40
+ <hfoption id="image-to-image">
41
+
42
+ ```py
43
+ import torch
44
+ from diffusers.modular_pipelines import SequentialPipelineBlocks
45
+ from diffusers.modular_pipelines.stable_diffusion_xl import IMAGE2IMAGE_BLOCKS
46
+
47
+ blocks = SequentialPipelineBlocks.from_blocks_dict(IMAGE2IMAGE_BLOCKS)
48
+
49
+ modular_repo_id = "YiYiXu/modular-loader-t2i-0704"
50
+ pipeline = blocks.init_pipeline(modular_repo_id)
51
+
52
+ pipeline.load_components(torch_dtype=torch.float16)
53
+ pipeline.to("cuda")
54
+
55
+ url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/sdxl-text2img.png"
56
+ init_image = load_image(url)
57
+ prompt = "a dog catching a frisbee in the jungle"
58
+ image = pipeline(prompt=prompt, image=init_image, strength=0.8, output="images")[0]
59
+ image.save("modular_i2i_out.png")
60
+ ```
61
+
62
+ </hfoption>
63
+ <hfoption id="inpainting">
64
+
65
+ ```py
66
+ import torch
67
+ from diffusers.modular_pipelines import SequentialPipelineBlocks
68
+ from diffusers.modular_pipelines.stable_diffusion_xl import INPAINT_BLOCKS
69
+ from diffusers.utils import load_image
70
+
71
+ blocks = SequentialPipelineBlocks.from_blocks_dict(INPAINT_BLOCKS)
72
+
73
+ modular_repo_id = "YiYiXu/modular-loader-t2i-0704"
74
+ pipeline = blocks.init_pipeline(modular_repo_id)
75
+
76
+ pipeline.load_components(torch_dtype=torch.float16)
77
+ pipeline.to("cuda")
78
+
79
+ img_url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/sdxl-text2img.png"
80
+ mask_url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/sdxl-inpaint-mask.png"
81
+
82
+ init_image = load_image(img_url)
83
+ mask_image = load_image(mask_url)
84
+
85
+ prompt = "A deep sea diver floating"
86
+ image = pipeline(prompt=prompt, image=init_image, mask_image=mask_image, strength=0.85, output="images")[0]
87
+ image.save("moduar_inpaint_out.png")
88
+ ```
89
+
90
+ </hfoption>
91
+ </hfoptions>
92
+
93
+ This guide will show you how to create a [`ModularPipeline`] and manage the components in it.
94
+
95
+ ## Adding blocks
96
+
97
+ Blocks are [`InsertableDict`] objects that can be inserted at specific positions, providing a flexible way to mix-and-match blocks.
98
+
99
+ Use [`~modular_pipelines.modular_pipeline_utils.InsertableDict.insert`] on either the block class or `sub_blocks` attribute to add a block.
100
+
101
+ ```py
102
+ # BLOCKS is dict of block classes, you need to add class to it
103
+ BLOCKS.insert("block_name", BlockClass, index)
104
+ # sub_blocks attribute contains instance, add a block instance to the attribute
105
+ t2i_blocks.sub_blocks.insert("block_name", block_instance, index)
106
+ ```
107
+
108
+ Use [`~modular_pipelines.modular_pipeline_utils.InsertableDict.pop`] on either the block class or `sub_blocks` attribute to remove a block.
109
+
110
+ ```py
111
+ # remove a block class from preset
112
+ BLOCKS.pop("text_encoder")
113
+ # split out a block instance on its own
114
+ text_encoder_block = t2i_blocks.sub_blocks.pop("text_encoder")
115
+ ```
116
+
117
+ Swap blocks by setting the existing block to the new block.
118
+
119
+ ```py
120
+ # Replace block class in preset
121
+ BLOCKS["prepare_latents"] = CustomPrepareLatents
122
+ # Replace in sub_blocks attribute using an block instance
123
+ t2i_blocks.sub_blocks["prepare_latents"] = CustomPrepareLatents()
124
+ ```
125
+
126
+ ## Creating a pipeline
127
+
128
+ There are two ways to create a [`ModularPipeline`]. Assemble and create a pipeline from [`ModularPipelineBlocks`] or load an existing pipeline with [`~ModularPipeline.from_pretrained`].
129
+
130
+ You should also initialize a [`ComponentsManager`] to handle device placement and memory and component management.
131
+
132
+ > [!TIP]
133
+ > Refer to the [ComponentsManager](./components_manager) doc for more details about how it can help manage components across different workflows.
134
+
135
+ <hfoptions id="create">
136
+ <hfoption id="ModularPipelineBlocks">
137
+
138
+ Use the [`~ModularPipelineBlocks.init_pipeline`] method to create a [`ModularPipeline`] from the component and configuration specifications. This method loads the *specifications* from a `modular_model_index.json` file, but it doesn't load the *models* yet.
139
+
140
+ ```py
141
+ from diffusers import ComponentsManager
142
+ from diffusers.modular_pipelines import SequentialPipelineBlocks
143
+ from diffusers.modular_pipelines.stable_diffusion_xl import TEXT2IMAGE_BLOCKS
144
+
145
+ t2i_blocks = SequentialPipelineBlocks.from_blocks_dict(TEXT2IMAGE_BLOCKS)
146
+
147
+ modular_repo_id = "YiYiXu/modular-loader-t2i-0704"
148
+ components = ComponentsManager()
149
+ t2i_pipeline = t2i_blocks.init_pipeline(modular_repo_id, components_manager=components)
150
+ ```
151
+
152
+ </hfoption>
153
+ <hfoption id="from_pretrained">
154
+
155
+ The [`~ModularPipeline.from_pretrained`] method creates a [`ModularPipeline`] from a modular repository on the Hub.
156
+
157
+ ```py
158
+ from diffusers import ModularPipeline, ComponentsManager
159
+
160
+ components = ComponentsManager()
161
+ pipeline = ModularPipeline.from_pretrained("YiYiXu/modular-loader-t2i-0704", components_manager=components)
162
+ ```
163
+
164
+ Add the `trust_remote_code` argument to load a custom [`ModularPipeline`].
165
+
166
+ ```py
167
+ from diffusers import ModularPipeline, ComponentsManager
168
+
169
+ components = ComponentsManager()
170
+ modular_repo_id = "YiYiXu/modular-diffdiff-0704"
171
+ diffdiff_pipeline = ModularPipeline.from_pretrained(modular_repo_id, trust_remote_code=True, components_manager=components)
172
+ ```
173
+
174
+ </hfoption>
175
+ </hfoptions>
176
+
177
+ ## Loading components
178
+
179
+ A [`ModularPipeline`] doesn't automatically instantiate with components. It only loads the configuration and component specifications. You can load all components with [`~ModularPipeline.load_components`] or only load specific components with [`~ModularPipeline.load_components`].
180
+
181
+ <hfoptions id="load">
182
+ <hfoption id="load_components">
183
+
184
+ ```py
185
+ import torch
186
+
187
+ t2i_pipeline.load_components(torch_dtype=torch.float16)
188
+ t2i_pipeline.to("cuda")
189
+ ```
190
+
191
+ </hfoption>
192
+ <hfoption id="load_components">
193
+
194
+ The example below only loads the UNet and VAE.
195
+
196
+ ```py
197
+ import torch
198
+
199
+ t2i_pipeline.load_components(names=["unet", "vae"], torch_dtype=torch.float16)
200
+ ```
201
+
202
+ </hfoption>
203
+ </hfoptions>
204
+
205
+ Print the pipeline to inspect the loaded pretrained components.
206
+
207
+ ```py
208
+ t2i_pipeline
209
+ ```
210
+
211
+ This should match the `modular_model_index.json` file from the modular repository a pipeline is initialized from. If a pipeline doesn't need a component, it won't be included even if it exists in the modular repository.
212
+
213
+ To modify where components are loaded from, edit the `modular_model_index.json` file in the repository and change it to your desired loading path. The example below loads a UNet from a different repository.
214
+
215
+ ```json
216
+ # original
217
+ "unet": [
218
+ null, null,
219
+ {
220
+ "repo": "stabilityai/stable-diffusion-xl-base-1.0",
221
+ "subfolder": "unet",
222
+ "variant": "fp16"
223
+ }
224
+ ]
225
+
226
+ # modified
227
+ "unet": [
228
+ null, null,
229
+ {
230
+ "repo": "RunDiffusion/Juggernaut-XL-v9",
231
+ "subfolder": "unet",
232
+ "variant": "fp16"
233
+ }
234
+ ]
235
+ ```
236
+
237
+ ### Component loading status
238
+
239
+ The pipeline properties below provide more information about which components are loaded.
240
+
241
+ Use `component_names` to return all expected components.
242
+
243
+ ```py
244
+ t2i_pipeline.component_names
245
+ ['text_encoder', 'text_encoder_2', 'tokenizer', 'tokenizer_2', 'guider', 'scheduler', 'unet', 'vae', 'image_processor']
246
+ ```
247
+
248
+ Use `null_component_names` to return components that aren't loaded yet. Load these components with [`~ModularPipeline.from_pretrained`].
249
+
250
+ ```py
251
+ t2i_pipeline.null_component_names
252
+ ['text_encoder', 'text_encoder_2', 'tokenizer', 'tokenizer_2', 'scheduler']
253
+ ```
254
+
255
+ Use `pretrained_component_names` to return components that will be loaded from pretrained models.
256
+
257
+ ```py
258
+ t2i_pipeline.pretrained_component_names
259
+ ['text_encoder', 'text_encoder_2', 'tokenizer', 'tokenizer_2', 'scheduler', 'unet', 'vae']
260
+ ```
261
+
262
+ Use `config_component_names` to return components that are created with the default config (not loaded from a modular repository). Components from a config aren't included because they are already initialized during pipeline creation. This is why they aren't listed in `null_component_names`.
263
+
264
+ ```py
265
+ t2i_pipeline.config_component_names
266
+ ['guider', 'image_processor']
267
+ ```
268
+
269
+ ## Updating components
270
+
271
+ Components may be updated depending on whether it is a *pretrained component* or a *config component*.
272
+
273
+ > [!WARNING]
274
+ > A component may change from pretrained to config when updating a component. The component type is initially defined in a block's `expected_components` field.
275
+
276
+ A pretrained component is updated with [`ComponentSpec`] whereas a config component is updated by eihter passing the object directly or with [`ComponentSpec`].
277
+
278
+ The [`ComponentSpec`] shows `default_creation_method="from_pretrained"` for a pretrained component shows `default_creation_method="from_config` for a config component.
279
+
280
+ To update a pretrained component, create a [`ComponentSpec`] with the name of the component and where to load it from. Use the [`~ComponentSpec.load`] method to load the component.
281
+
282
+ ```py
283
+ from diffusers import ComponentSpec, UNet2DConditionModel
284
+
285
+ unet_spec = ComponentSpec(name="unet",type_hint=UNet2DConditionModel, repo="stabilityai/stable-diffusion-xl-base-1.0", subfolder="unet", variant="fp16")
286
+ unet = unet_spec.load(torch_dtype=torch.float16)
287
+ ```
288
+
289
+ The [`~ModularPipeline.update_components`] method replaces the component with a new one.
290
+
291
+ ```py
292
+ t2i_pipeline.update_components(unet=unet2)
293
+ ```
294
+
295
+ When a component is updated, the loading specifications are also updated in the pipeline config.
296
+
297
+ ### Component extraction and modification
298
+
299
+ When you use [`~ComponentSpec.load`], the new component maintains its loading specifications. This makes it possible to extract the specification and recreate the component.
300
+
301
+ ```py
302
+ spec = ComponentSpec.from_component("unet", unet2)
303
+ spec
304
+ ComponentSpec(name='unet', type_hint=<class 'diffusers.models.unets.unet_2d_condition.UNet2DConditionModel'>, description=None, config=None, repo='stabilityai/stable-diffusion-xl-base-1.0', subfolder='unet', variant='fp16', revision=None, default_creation_method='from_pretrained')
305
+ unet2_recreated = spec.load(torch_dtype=torch.float16)
306
+ ```
307
+
308
+ The [`~ModularPipeline.get_component_spec`] method gets a copy of the current component specification to modify or update.
309
+
310
+ ```py
311
+ unet_spec = t2i_pipeline.get_component_spec("unet")
312
+ unet_spec
313
+ ComponentSpec(
314
+ name='unet',
315
+ type_hint=<class 'diffusers.models.unets.unet_2d_condition.UNet2DConditionModel'>,
316
+ repo='RunDiffusion/Juggernaut-XL-v9',
317
+ subfolder='unet',
318
+ variant='fp16',
319
+ default_creation_method='from_pretrained'
320
+ )
321
+
322
+ # modify to load from a different repository
323
+ unet_spec.repo = "stabilityai/stable-diffusion-xl-base-1.0"
324
+
325
+ # load component with modified spec
326
+ unet = unet_spec.load(torch_dtype=torch.float16)
327
+ ```
328
+
329
+ ## Modular repository
330
+
331
+ A repository is required if the pipeline blocks use *pretrained components*. The repository supplies loading specifications and metadata.
332
+
333
+ [`ModularPipeline`] specifically requires *modular repositories* (see [example repository](https://huggingface.co/YiYiXu/modular-diffdiff)) which are more flexible than a typical repository. It contains a `modular_model_index.json` file containing the following 3 elements.
334
+
335
+ - `library` and `class` shows which library the component was loaded from and it's class. If `null`, the component hasn't been loaded yet.
336
+ - `loading_specs_dict` contains the information required to load the component such as the repository and subfolder it is loaded from.
337
+
338
+ Unlike standard repositories, a modular repository can fetch components from different repositories based on the `loading_specs_dict`. Components don't need to exist in the same repository.
339
+
340
+ A modular repository may contain custom code for loading a [`ModularPipeline`]. This allows you to use specialized blocks that aren't native to Diffusers.
341
+
342
+ ```
343
+ modular-diffdiff-0704/
344
+ ├── block.py # Custom pipeline blocks implementation
345
+ ├── config.json # Pipeline configuration and auto_map
346
+ └── modular_model_index.json # Component loading specifications
347
+ ```
348
+
349
+ The [config.json](https://huggingface.co/YiYiXu/modular-diffdiff-0704/blob/main/config.json) file contains an `auto_map` key that points to where a custom block is defined in `block.py`.
350
+
351
+ ```json
352
+ {
353
+ "_class_name": "DiffDiffBlocks",
354
+ "auto_map": {
355
+ "ModularPipelineBlocks": "block.DiffDiffBlocks"
356
+ }
357
+ }
358
+ ```
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/modular_diffusers/overview.md ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Overview
14
+
15
+ > [!WARNING]
16
+ > Modular Diffusers is under active development and it's API may change.
17
+
18
+ Modular Diffusers is a unified pipeline system that simplifies your workflow with *pipeline blocks*.
19
+
20
+ - Blocks are reusable and you only need to create new blocks that are unique to your pipeline.
21
+ - Blocks can be mixed and matched to adapt to or create a pipeline for a specific workflow or multiple workflows.
22
+
23
+ The Modular Diffusers docs are organized as shown below.
24
+
25
+ ## Quickstart
26
+
27
+ - A [quickstart](./quickstart) demonstrating how to implement an example workflow with Modular Diffusers.
28
+
29
+ ## ModularPipelineBlocks
30
+
31
+ - [States](./modular_diffusers_states) explains how data is shared and communicated between blocks and [`ModularPipeline`].
32
+ - [ModularPipelineBlocks](./pipeline_block) is the most basic unit of a [`ModularPipeline`] and this guide shows you how to create one.
33
+ - [SequentialPipelineBlocks](./sequential_pipeline_blocks) is a type of block that chains multiple blocks so they run one after another, passing data along the chain. This guide shows you how to create [`~modular_pipelines.SequentialPipelineBlocks`] and how they connect and work together.
34
+ - [LoopSequentialPipelineBlocks](./loop_sequential_pipeline_blocks) is a type of block that runs a series of blocks in a loop. This guide shows you how to create [`~modular_pipelines.LoopSequentialPipelineBlocks`].
35
+ - [AutoPipelineBlocks](./auto_pipeline_blocks) is a type of block that automatically chooses which blocks to run based on the input. This guide shows you how to create [`~modular_pipelines.AutoPipelineBlocks`].
36
+
37
+ ## ModularPipeline
38
+
39
+ - [ModularPipeline](./modular_pipeline) shows you how to create and convert pipeline blocks into an executable [`ModularPipeline`].
40
+ - [ComponentsManager](./components_manager) shows you how to manage and reuse components across multiple pipelines.
41
+ - [Guiders](./guiders) shows you how to use different guidance methods in the pipeline.
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/modular_diffusers/pipeline_block.md ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # ModularPipelineBlocks
14
+
15
+ [`~modular_pipelines.ModularPipelineBlocks`] is the basic block for building a [`ModularPipeline`]. It defines what components, inputs/outputs, and computation a block should perform for a specific step in a pipeline. A [`~modular_pipelines.ModularPipelineBlocks`] connects with other blocks, using [state](./modular_diffusers_states), to enable the modular construction of workflows.
16
+
17
+ A [`~modular_pipelines.ModularPipelineBlocks`] on it's own can't be executed. It is a blueprint for what a step should do in a pipeline. To actually run and execute a pipeline, the [`~modular_pipelines.ModularPipelineBlocks`] needs to be converted into a [`ModularPipeline`].
18
+
19
+ This guide will show you how to create a [`~modular_pipelines.ModularPipelineBlocks`].
20
+
21
+ ## Inputs and outputs
22
+
23
+ > [!TIP]
24
+ > Refer to the [States](./modular_diffusers_states) guide if you aren't familiar with how state works in Modular Diffusers.
25
+
26
+ A [`~modular_pipelines.ModularPipelineBlocks`] requires `inputs`, and `intermediate_outputs`.
27
+
28
+ - `inputs` are values provided by a user and retrieved from the [`~modular_pipelines.PipelineState`]. This is useful because some workflows resize an image, but the original image is still required. The [`~modular_pipelines.PipelineState`] maintains the original image.
29
+
30
+ Use `InputParam` to define `inputs`.
31
+
32
+ ```py
33
+ from diffusers.modular_pipelines import InputParam
34
+
35
+ user_inputs = [
36
+ InputParam(name="image", type_hint="PIL.Image", description="raw input image to process")
37
+ ]
38
+ ```
39
+
40
+ - `intermediate_outputs` are new values created by a block and added to the [`~modular_pipelines.PipelineState`]. The `intermediate_outputs` are available as `inputs` for subsequent blocks or available as the final output from running the pipeline.
41
+
42
+ Use `OutputParam` to define `intermediate_outputs`.
43
+
44
+ ```py
45
+ from diffusers.modular_pipelines import OutputParam
46
+
47
+ user_intermediate_outputs = [
48
+ OutputParam(name="image_latents", description="latents representing the image")
49
+ ]
50
+ ```
51
+
52
+ The intermediate inputs and outputs share data to connect blocks. They are accessible at any point, allowing you to track the workflow's progress.
53
+
54
+ ## Computation logic
55
+
56
+ The computation a block performs is defined in the `__call__` method and it follows a specific structure.
57
+
58
+ 1. Retrieve the [`~modular_pipelines.BlockState`] to get a local view of the `inputs`
59
+ 2. Implement the computation logic on the `inputs`.
60
+ 3. Update [`~modular_pipelines.PipelineState`] to push changes from the local [`~modular_pipelines.BlockState`] back to the global [`~modular_pipelines.PipelineState`].
61
+ 4. Return the components and state which becomes available to the next block.
62
+
63
+ ```py
64
+ def __call__(self, components, state):
65
+ # Get a local view of the state variables this block needs
66
+ block_state = self.get_block_state(state)
67
+
68
+ # Your computation logic here
69
+ # block_state contains all your inputs
70
+ # Access them like: block_state.image, block_state.processed_image
71
+
72
+ # Update the pipeline state with your updated block_states
73
+ self.set_block_state(state, block_state)
74
+ return components, state
75
+ ```
76
+
77
+ ### Components and configs
78
+
79
+ The components and pipeline-level configs a block needs are specified in [`ComponentSpec`] and [`~modular_pipelines.ConfigSpec`].
80
+
81
+ - [`ComponentSpec`] contains the expected components used by a block. You need the `name` of the component and ideally a `type_hint` that specifies exactly what the component is.
82
+ - [`~modular_pipelines.ConfigSpec`] contains pipeline-level settings that control behavior across all blocks.
83
+
84
+ ```py
85
+ from diffusers import ComponentSpec, ConfigSpec
86
+
87
+ expected_components = [
88
+ ComponentSpec(name="unet", type_hint=UNet2DConditionModel),
89
+ ComponentSpec(name="scheduler", type_hint=EulerDiscreteScheduler)
90
+ ]
91
+
92
+ expected_config = [
93
+ ConfigSpec("force_zeros_for_empty_prompt", True)
94
+ ]
95
+ ```
96
+
97
+ When the blocks are converted into a pipeline, the components become available to the block as the first argument in `__call__`.
98
+
99
+ ```py
100
+ def __call__(self, components, state):
101
+ # Access components using dot notation
102
+ unet = components.unet
103
+ vae = components.vae
104
+ scheduler = components.scheduler
105
+ ```
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/modular_diffusers/quickstart.md ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Quickstart
14
+
15
+ Modular Diffusers is a framework for quickly building flexible and customizable pipelines. At the core of Modular Diffusers are [`ModularPipelineBlocks`] that can be combined with other blocks to adapt to new workflows. The blocks are converted into a [`ModularPipeline`], a friendly user-facing interface developers can use.
16
+
17
+ This doc will show you how to implement a [Differential Diffusion](https://differential-diffusion.github.io/) pipeline with the modular framework.
18
+
19
+ ## ModularPipelineBlocks
20
+
21
+ [`ModularPipelineBlocks`] are *definitions* that specify the components, inputs, outputs, and computation logic for a single step in a pipeline. There are four types of blocks.
22
+
23
+ - [`ModularPipelineBlocks`] is the most basic block for a single step.
24
+ - [`SequentialPipelineBlocks`] is a multi-block that composes other blocks linearly. The outputs of one block are the inputs to the next block.
25
+ - [`LoopSequentialPipelineBlocks`] is a multi-block that runs iteratively and is designed for iterative workflows.
26
+ - [`AutoPipelineBlocks`] is a collection of blocks for different workflows and it selects which block to run based on the input. It is designed to conveniently package multiple workflows into a single pipeline.
27
+
28
+ [Differential Diffusion](https://differential-diffusion.github.io/) is an image-to-image workflow. Start with the `IMAGE2IMAGE_BLOCKS` preset, a collection of `ModularPipelineBlocks` for image-to-image generation.
29
+
30
+ ```py
31
+ from diffusers.modular_pipelines.stable_diffusion_xl import IMAGE2IMAGE_BLOCKS
32
+ IMAGE2IMAGE_BLOCKS = InsertableDict([
33
+ ("text_encoder", StableDiffusionXLTextEncoderStep),
34
+ ("image_encoder", StableDiffusionXLVaeEncoderStep),
35
+ ("input", StableDiffusionXLInputStep),
36
+ ("set_timesteps", StableDiffusionXLImg2ImgSetTimestepsStep),
37
+ ("prepare_latents", StableDiffusionXLImg2ImgPrepareLatentsStep),
38
+ ("prepare_add_cond", StableDiffusionXLImg2ImgPrepareAdditionalConditioningStep),
39
+ ("denoise", StableDiffusionXLDenoiseStep),
40
+ ("decode", StableDiffusionXLDecodeStep)
41
+ ])
42
+ ```
43
+
44
+ ## Pipeline and block states
45
+
46
+ Modular Diffusers uses *state* to communicate data between blocks. There are two types of states.
47
+
48
+ - [`PipelineState`] is a global state that can be used to track all inputs and outputs across all blocks.
49
+ - [`BlockState`] is a local view of relevant variables from [`PipelineState`] for an individual block.
50
+
51
+ ## Customizing blocks
52
+
53
+ [Differential Diffusion](https://differential-diffusion.github.io/) differs from standard image-to-image in its `prepare_latents` and `denoise` blocks. All the other blocks can be reused, but you'll need to modify these two.
54
+
55
+ Create placeholder `ModularPipelineBlocks` for `prepare_latents` and `denoise` by copying and modifying the existing ones.
56
+
57
+ Print the `denoise` block to see that it is composed of [`LoopSequentialPipelineBlocks`] with three sub-blocks, `before_denoiser`, `denoiser`, and `after_denoiser`. Only the `before_denoiser` sub-block needs to be modified to prepare the latent input for the denoiser based on the change map.
58
+
59
+ ```py
60
+ denoise_blocks = IMAGE2IMAGE_BLOCKS["denoise"]()
61
+ print(denoise_blocks)
62
+ ```
63
+
64
+ Replace the `StableDiffusionXLLoopBeforeDenoiser` sub-block with the new `SDXLDiffDiffLoopBeforeDenoiser` block.
65
+
66
+ ```py
67
+ # Copy existing blocks as placeholders
68
+ class SDXLDiffDiffPrepareLatentsStep(ModularPipelineBlocks):
69
+ """Copied from StableDiffusionXLImg2ImgPrepareLatentsStep - will modify later"""
70
+ # ... same implementation as StableDiffusionXLImg2ImgPrepareLatentsStep
71
+
72
+ class SDXLDiffDiffDenoiseStep(StableDiffusionXLDenoiseLoopWrapper):
73
+ block_classes = [SDXLDiffDiffLoopBeforeDenoiser, StableDiffusionXLLoopDenoiser, StableDiffusionXLLoopAfterDenoiser]
74
+ block_names = ["before_denoiser", "denoiser", "after_denoiser"]
75
+ ```
76
+
77
+ ### prepare_latents
78
+
79
+ The `prepare_latents` block requires the following changes.
80
+
81
+ - a processor to process the change map
82
+ - a new `inputs` to accept the user-provided change map, `timestep` for precomputing all the latents and `num_inference_steps` to create the mask for updating the image regions
83
+ - update the computation in the `__call__` method for processing the change map and creating the masks, and storing it in the [`BlockState`]
84
+
85
+ ```diff
86
+ class SDXLDiffDiffPrepareLatentsStep(ModularPipelineBlocks):
87
+ @property
88
+ def expected_components(self) -> List[ComponentSpec]:
89
+ return [
90
+ ComponentSpec("vae", AutoencoderKL),
91
+ ComponentSpec("scheduler", EulerDiscreteScheduler),
92
+ + ComponentSpec("mask_processor", VaeImageProcessor, config=FrozenDict({"do_normalize": False, "do_convert_grayscale": True}))
93
+ ]
94
+ @property
95
+ def inputs(self) -> List[Tuple[str, Any]]:
96
+ return [
97
+ InputParam("generator"),
98
+ + InputParam("diffdiff_map", required=True),
99
+ - InputParam("latent_timestep", required=True, type_hint=torch.Tensor),
100
+ + InputParam("timesteps", type_hint=torch.Tensor),
101
+ + InputParam("num_inference_steps", type_hint=int),
102
+ ]
103
+
104
+ @property
105
+ def intermediate_outputs(self) -> List[OutputParam]:
106
+ return [
107
+ + OutputParam("original_latents", type_hint=torch.Tensor),
108
+ + OutputParam("diffdiff_masks", type_hint=torch.Tensor),
109
+ ]
110
+ def __call__(self, components, state: PipelineState):
111
+ # ... existing logic ...
112
+ + # Process change map and create masks
113
+ + diffdiff_map = components.mask_processor.preprocess(block_state.diffdiff_map, height=latent_height, width=latent_width)
114
+ + thresholds = torch.arange(block_state.num_inference_steps, dtype=diffdiff_map.dtype) / block_state.num_inference_steps
115
+ + block_state.diffdiff_masks = diffdiff_map > (thresholds + (block_state.denoising_start or 0))
116
+ + block_state.original_latents = block_state.latents
117
+ ```
118
+
119
+ ### denoise
120
+
121
+ The `before_denoiser` sub-block requires the following changes.
122
+
123
+ - a new `inputs` to accept a `denoising_start` parameter, `original_latents` and `diffdiff_masks` from the `prepare_latents` block
124
+ - update the computation in the `__call__` method for applying Differential Diffusion
125
+
126
+ ```diff
127
+ class SDXLDiffDiffLoopBeforeDenoiser(ModularPipelineBlocks):
128
+ @property
129
+ def description(self) -> str:
130
+ return (
131
+ "Step within the denoising loop for differential diffusion that prepare the latent input for the denoiser"
132
+ )
133
+
134
+ @property
135
+ def inputs(self) -> List[str]:
136
+ return [
137
+ InputParam("latents", required=True, type_hint=torch.Tensor),
138
+ + InputParam("denoising_start"),
139
+ + InputParam("original_latents", type_hint=torch.Tensor),
140
+ + InputParam("diffdiff_masks", type_hint=torch.Tensor),
141
+ ]
142
+
143
+ def __call__(self, components, block_state, i, t):
144
+ + # Apply differential diffusion logic
145
+ + if i == 0 and block_state.denoising_start is None:
146
+ + block_state.latents = block_state.original_latents[:1]
147
+ + else:
148
+ + block_state.mask = block_state.diffdiff_masks[i].unsqueeze(0).unsqueeze(1)
149
+ + block_state.latents = block_state.original_latents[i] * block_state.mask + block_state.latents * (1 - block_state.mask)
150
+
151
+ # ... rest of existing logic ...
152
+ ```
153
+
154
+ ## Assembling the blocks
155
+
156
+ You should have all the blocks you need at this point to create a [`ModularPipeline`].
157
+
158
+ Copy the existing `IMAGE2IMAGE_BLOCKS` preset and for the `set_timesteps` block, use the `set_timesteps` from the `TEXT2IMAGE_BLOCKS` because Differential Diffusion doesn't require a `strength` parameter.
159
+
160
+ Set the `prepare_latents` and `denoise` blocks to the `SDXLDiffDiffPrepareLatentsStep` and `SDXLDiffDiffDenoiseStep` blocks you just modified.
161
+
162
+ Call [`SequentialPipelineBlocks.from_blocks_dict`] on the blocks to create a `SequentialPipelineBlocks`.
163
+
164
+ ```py
165
+ DIFFDIFF_BLOCKS = IMAGE2IMAGE_BLOCKS.copy()
166
+ DIFFDIFF_BLOCKS["set_timesteps"] = TEXT2IMAGE_BLOCKS["set_timesteps"]
167
+ DIFFDIFF_BLOCKS["prepare_latents"] = SDXLDiffDiffPrepareLatentsStep
168
+ DIFFDIFF_BLOCKS["denoise"] = SDXLDiffDiffDenoiseStep
169
+
170
+ dd_blocks = SequentialPipelineBlocks.from_blocks_dict(DIFFDIFF_BLOCKS)
171
+ print(dd_blocks)
172
+ ```
173
+
174
+ ## ModularPipeline
175
+
176
+ Convert the [`SequentialPipelineBlocks`] into a [`ModularPipeline`] with the [`ModularPipeline.init_pipeline`] method. This initializes the expected components to load from a `modular_model_index.json` file. Explicitly load the components by calling [`ModularPipeline.load_components`].
177
+
178
+ It is a good idea to initialize the [`ComponentManager`] with the pipeline to help manage the different components. Once you call [`~ModularPipeline.load_components`], the components are registered to the [`ComponentManager`] and can be shared between workflows. The example below uses the `collection` argument to assign the components a `"diffdiff"` label for better organization.
179
+
180
+ ```py
181
+ from diffusers.modular_pipelines import ComponentsManager
182
+
183
+ components = ComponentManager()
184
+
185
+ dd_pipeline = dd_blocks.init_pipeline("YiYiXu/modular-demo-auto", components_manager=components, collection="diffdiff")
186
+ dd_pipeline.load_componenets(torch_dtype=torch.float16)
187
+ dd_pipeline.to("cuda")
188
+ ```
189
+
190
+ ## Adding workflows
191
+
192
+ Other workflows can be added to the [`ModularPipeline`] to support additional features without rewriting the entire pipeline from scratch.
193
+
194
+ This section demonstrates how to add an IP-Adapter or ControlNet.
195
+
196
+ ### IP-Adapter
197
+
198
+ Stable Diffusion XL already has a preset IP-Adapter block that you can use and doesn't require any changes to the existing Differential Diffusion pipeline.
199
+
200
+ ```py
201
+ from diffusers.modular_pipelines.stable_diffusion_xl.encoders import StableDiffusionXLAutoIPAdapterStep
202
+
203
+ ip_adapter_block = StableDiffusionXLAutoIPAdapterStep()
204
+ ```
205
+
206
+ Use the [`sub_blocks.insert`] method to insert it into the [`ModularPipeline`]. The example below inserts the `ip_adapter_block` at position `0`. Print the pipeline to see that the `ip_adapter_block` is added and it requires an `ip_adapter_image`. This also added two components to the pipeline, the `image_encoder` and `feature_extractor`.
207
+
208
+ ```py
209
+ dd_blocks.sub_blocks.insert("ip_adapter", ip_adapter_block, 0)
210
+ ```
211
+
212
+ Call [`~ModularPipeline.init_pipeline`] to initialize a [`ModularPipeline`] and use [`~ModularPipeline.load_components`] to load the model components. Load and set the IP-Adapter to run the pipeline.
213
+
214
+ ```py
215
+ dd_pipeline = dd_blocks.init_pipeline("YiYiXu/modular-demo-auto", collection="diffdiff")
216
+ dd_pipeline.load_components(torch_dtype=torch.float16)
217
+ dd_pipeline.loader.load_ip_adapter("h94/IP-Adapter", subfolder="sdxl_models", weight_name="ip-adapter_sdxl.bin")
218
+ dd_pipeline.loader.set_ip_adapter_scale(0.6)
219
+ dd_pipeline = dd_pipeline.to(device)
220
+
221
+ ip_adapter_image = load_image("https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/diffdiff_orange.jpeg")
222
+ image = load_image("https://huggingface.co/datasets/OzzyGT/testing-resources/resolve/main/differential/20240329211129_4024911930.png?download=true")
223
+ mask = load_image("https://huggingface.co/datasets/OzzyGT/testing-resources/resolve/main/differential/gradient_mask.png?download=true")
224
+
225
+ prompt = "a green pear"
226
+ negative_prompt = "blurry"
227
+ generator = torch.Generator(device=device).manual_seed(42)
228
+
229
+ image = dd_pipeline(
230
+ prompt=prompt,
231
+ negative_prompt=negative_prompt,
232
+ num_inference_steps=25,
233
+ generator=generator,
234
+ ip_adapter_image=ip_adapter_image,
235
+ diffdiff_map=mask,
236
+ image=image,
237
+ output="images"
238
+ )[0]
239
+ ```
240
+
241
+ ### ControlNet
242
+
243
+ Stable Diffusion XL already has a preset ControlNet block that can readily be used.
244
+
245
+ ```py
246
+ from diffusers.modular_pipelines.stable_diffusion_xl.modular_blocks import StableDiffusionXLAutoControlNetInputStep
247
+
248
+ control_input_block = StableDiffusionXLAutoControlNetInputStep()
249
+ ```
250
+
251
+ However, it requires modifying the `denoise` block because that's where the ControlNet injects the control information into the UNet.
252
+
253
+ Modify the `denoise` block by replacing the `StableDiffusionXLLoopDenoiser` sub-block with the `StableDiffusionXLControlNetLoopDenoiser`.
254
+
255
+ ```py
256
+ class SDXLDiffDiffControlNetDenoiseStep(StableDiffusionXLDenoiseLoopWrapper):
257
+ block_classes = [SDXLDiffDiffLoopBeforeDenoiser, StableDiffusionXLControlNetLoopDenoiser, StableDiffusionXLDenoiseLoopAfterDenoiser]
258
+ block_names = ["before_denoiser", "denoiser", "after_denoiser"]
259
+
260
+ controlnet_denoise_block = SDXLDiffDiffControlNetDenoiseStep()
261
+ ```
262
+
263
+ Insert the `controlnet_input` block and replace the `denoise` block with the new `controlnet_denoise_block`. Initialize a [`ModularPipeline`] and [`~ModularPipeline.load_components`] into it.
264
+
265
+ ```py
266
+ dd_blocks.sub_blocks.insert("controlnet_input", control_input_block, 7)
267
+ dd_blocks.sub_blocks["denoise"] = controlnet_denoise_block
268
+
269
+ dd_pipeline = dd_blocks.init_pipeline("YiYiXu/modular-demo-auto", collection="diffdiff")
270
+ dd_pipeline.load_components(torch_dtype=torch.float16)
271
+ dd_pipeline = dd_pipeline.to(device)
272
+
273
+ control_image = load_image("https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/diffdiff_tomato_canny.jpeg")
274
+ image = load_image("https://huggingface.co/datasets/OzzyGT/testing-resources/resolve/main/differential/20240329211129_4024911930.png?download=true")
275
+ mask = load_image("https://huggingface.co/datasets/OzzyGT/testing-resources/resolve/main/differential/gradient_mask.png?download=true")
276
+
277
+ prompt = "a green pear"
278
+ negative_prompt = "blurry"
279
+ generator = torch.Generator(device=device).manual_seed(42)
280
+
281
+ image = dd_pipeline(
282
+ prompt=prompt,
283
+ negative_prompt=negative_prompt,
284
+ num_inference_steps=25,
285
+ generator=generator,
286
+ control_image=control_image,
287
+ controlnet_conditioning_scale=0.5,
288
+ diffdiff_map=mask,
289
+ image=image,
290
+ output="images"
291
+ )[0]
292
+ ```
293
+
294
+ ### AutoPipelineBlocks
295
+
296
+ The Differential Diffusion, IP-Adapter, and ControlNet workflows can be bundled into a single [`ModularPipeline`] by using [`AutoPipelineBlocks`]. This allows automatically selecting which sub-blocks to run based on the inputs like `control_image` or `ip_adapter_image`. If none of these inputs are passed, then it defaults to the Differential Diffusion.
297
+
298
+ Use `block_trigger_inputs` to only run the `SDXLDiffDiffControlNetDenoiseStep` block if a `control_image` input is provided. Otherwise, the `SDXLDiffDiffDenoiseStep` is used.
299
+
300
+ ```py
301
+ class SDXLDiffDiffAutoDenoiseStep(AutoPipelineBlocks):
302
+ block_classes = [SDXLDiffDiffControlNetDenoiseStep, SDXLDiffDiffDenoiseStep]
303
+ block_names = ["controlnet_denoise", "denoise"]
304
+ block_trigger_inputs = ["controlnet_cond", None]
305
+ ```
306
+
307
+ Add the `ip_adapter` and `controlnet_input` blocks.
308
+
309
+ ```py
310
+ DIFFDIFF_AUTO_BLOCKS = IMAGE2IMAGE_BLOCKS.copy()
311
+ DIFFDIFF_AUTO_BLOCKS["prepare_latents"] = SDXLDiffDiffPrepareLatentsStep
312
+ DIFFDIFF_AUTO_BLOCKS["set_timesteps"] = TEXT2IMAGE_BLOCKS["set_timesteps"]
313
+ DIFFDIFF_AUTO_BLOCKS["denoise"] = SDXLDiffDiffAutoDenoiseStep
314
+ DIFFDIFF_AUTO_BLOCKS.insert("ip_adapter", StableDiffusionXLAutoIPAdapterStep, 0)
315
+ DIFFDIFF_AUTO_BLOCKS.insert("controlnet_input",StableDiffusionXLControlNetAutoInput, 7)
316
+ ```
317
+
318
+ Call [`SequentialPipelineBlocks.from_blocks_dict`] to create a [`SequentialPipelineBlocks`] and create a [`ModularPipeline`] and load in the model components to run.
319
+
320
+ ```py
321
+ dd_auto_blocks = SequentialPipelineBlocks.from_blocks_dict(DIFFDIFF_AUTO_BLOCKS)
322
+ dd_pipeline = dd_auto_blocks.init_pipeline("YiYiXu/modular-demo-auto", collection="diffdiff")
323
+ dd_pipeline.load_components(torch_dtype=torch.float16)
324
+ ```
325
+
326
+ ## Share
327
+
328
+ Add your [`ModularPipeline`] to the Hub with [`~ModularPipeline.save_pretrained`] and set `push_to_hub` argument to `True`.
329
+
330
+ ```py
331
+ dd_pipeline.save_pretrained("YiYiXu/test_modular_doc", push_to_hub=True)
332
+ ```
333
+
334
+ Other users can load the [`ModularPipeline`] with [`~ModularPipeline.from_pretrained`].
335
+
336
+ ```py
337
+ import torch
338
+ from diffusers.modular_pipelines import ModularPipeline, ComponentsManager
339
+
340
+ components = ComponentsManager()
341
+
342
+ diffdiff_pipeline = ModularPipeline.from_pretrained("YiYiXu/modular-diffdiff-0704", trust_remote_code=True, components_manager=components, collection="diffdiff")
343
+ diffdiff_pipeline.load_components(torch_dtype=torch.float16)
344
+ ```
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/modular_diffusers/sequential_pipeline_blocks.md ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # SequentialPipelineBlocks
14
+
15
+ [`~modular_pipelines.SequentialPipelineBlocks`] are a multi-block type that composes other [`~modular_pipelines.ModularPipelineBlocks`] together in a sequence. Data flows linearly from one block to the next using `inputs` and `intermediate_outputs`. Each block in [`~modular_pipelines.SequentialPipelineBlocks`] usually represents a step in the pipeline, and by combining them, you gradually build a pipeline.
16
+
17
+ This guide shows you how to connect two blocks into a [`~modular_pipelines.SequentialPipelineBlocks`].
18
+
19
+ Create two [`~modular_pipelines.ModularPipelineBlocks`]. The first block, `InputBlock`, outputs a `batch_size` value and the second block, `ImageEncoderBlock` uses `batch_size` as `inputs`.
20
+
21
+ <hfoptions id="sequential">
22
+ <hfoption id="InputBlock">
23
+
24
+ ```py
25
+ from diffusers.modular_pipelines import ModularPipelineBlocks, InputParam, OutputParam
26
+
27
+ class InputBlock(ModularPipelineBlocks):
28
+
29
+ @property
30
+ def inputs(self):
31
+ return [
32
+ InputParam(name="prompt", type_hint=list, description="list of text prompts"),
33
+ InputParam(name="num_images_per_prompt", type_hint=int, description="number of images per prompt"),
34
+ ]
35
+
36
+ @property
37
+ def intermediate_outputs(self):
38
+ return [
39
+ OutputParam(name="batch_size", description="calculated batch size"),
40
+ ]
41
+
42
+ @property
43
+ def description(self):
44
+ return "A block that determines batch_size based on the number of prompts and num_images_per_prompt argument."
45
+
46
+ def __call__(self, components, state):
47
+ block_state = self.get_block_state(state)
48
+ batch_size = len(block_state.prompt)
49
+ block_state.batch_size = batch_size * block_state.num_images_per_prompt
50
+ self.set_block_state(state, block_state)
51
+ return components, state
52
+ ```
53
+
54
+ </hfoption>
55
+ <hfoption id="ImageEncoderBlock">
56
+
57
+ ```py
58
+ import torch
59
+ from diffusers.modular_pipelines import ModularPipelineBlocks, InputParam, OutputParam
60
+
61
+ class ImageEncoderBlock(ModularPipelineBlocks):
62
+
63
+ @property
64
+ def inputs(self):
65
+ return [
66
+ InputParam(name="image", type_hint="PIL.Image", description="raw input image to process"),
67
+ InputParam(name="batch_size", type_hint=int),
68
+ ]
69
+
70
+ @property
71
+ def intermediate_outputs(self):
72
+ return [
73
+ OutputParam(name="image_latents", description="latents representing the image"),
74
+ ]
75
+
76
+ @property
77
+ def description(self):
78
+ return "Encode raw image into its latent presentation"
79
+
80
+ def __call__(self, components, state):
81
+ block_state = self.get_block_state(state)
82
+ # Simulate processing the image
83
+ # This will change the state of the image from a PIL image to a tensor for all blocks
84
+ block_state.image = torch.randn(1, 3, 512, 512)
85
+ block_state.batch_size = block_state.batch_size * 2
86
+ block_state.image_latents = torch.randn(1, 4, 64, 64)
87
+ self.set_block_state(state, block_state)
88
+ return components, state
89
+ ```
90
+
91
+ </hfoption>
92
+ </hfoptions>
93
+
94
+ Connect the two blocks by defining an [`InsertableDict`] to map the block names to the block instances. Blocks are executed in the order they're registered in `blocks_dict`.
95
+
96
+ Use [`~modular_pipelines.SequentialPipelineBlocks.from_blocks_dict`] to create a [`~modular_pipelines.SequentialPipelineBlocks`].
97
+
98
+ ```py
99
+ from diffusers.modular_pipelines import SequentialPipelineBlocks, InsertableDict
100
+
101
+ blocks_dict = InsertableDict()
102
+ blocks_dict["input"] = input_block
103
+ blocks_dict["image_encoder"] = image_encoder_block
104
+
105
+ blocks = SequentialPipelineBlocks.from_blocks_dict(blocks_dict)
106
+ ```
107
+
108
+ Inspect the sub-blocks in [`~modular_pipelines.SequentialPipelineBlocks`] by calling `blocks`, and for more details about the inputs and outputs, access the `docs` attribute.
109
+
110
+ ```py
111
+ print(blocks)
112
+ print(blocks.doc)
113
+ ```
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/attention_backends.md ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Attention backends
13
+
14
+ > [!NOTE]
15
+ > The attention dispatcher is an experimental feature. Please open an issue if you have any feedback or encounter any problems.
16
+
17
+ Diffusers provides several optimized attention algorithms that are more memory and computationally efficient through it's *attention dispatcher*. The dispatcher acts as a router for managing and switching between different attention implementations and provides a unified interface for interacting with them.
18
+
19
+ Refer to the table below for an overview of the available attention families and to the [Available backends](#available-backends) section for a more complete list.
20
+
21
+ | attention family | main feature |
22
+ |---|---|
23
+ | FlashAttention | minimizes memory reads/writes through tiling and recomputation |
24
+ | AI Tensor Engine for ROCm | FlashAttention implementation optimized for AMD ROCm accelerators |
25
+ | SageAttention | quantizes attention to int8 |
26
+ | PyTorch native | built-in PyTorch implementation using [scaled_dot_product_attention](./fp16#scaled-dot-product-attention) |
27
+ | xFormers | memory-efficient attention with support for various attention kernels |
28
+
29
+ This guide will show you how to set and use the different attention backends.
30
+
31
+ ## set_attention_backend
32
+
33
+ The [`~ModelMixin.set_attention_backend`] method iterates through all the modules in the model and sets the appropriate attention backend to use. The attention backend setting persists until [`~ModelMixin.reset_attention_backend`] is called.
34
+
35
+ The example below demonstrates how to enable the `_flash_3_hub` implementation for FlashAttention-3 from the [kernel](https://github.com/huggingface/kernels) library, which allows you to instantly use optimized compute kernels from the Hub without requiring any setup.
36
+
37
+ > [!NOTE]
38
+ > FlashAttention-3 is not supported for non-Hopper architectures, in which case, use FlashAttention with `set_attention_backend("flash")`.
39
+
40
+ ```py
41
+ import torch
42
+ from diffusers import QwenImagePipeline
43
+
44
+ pipeline = QwenImagePipeline.from_pretrained(
45
+ "Qwen/Qwen-Image", torch_dtype=torch.bfloat16, device_map="cuda"
46
+ )
47
+ pipeline.transformer.set_attention_backend("_flash_3_hub")
48
+
49
+ prompt = """
50
+ cinematic film still of a cat sipping a margarita in a pool in Palm Springs, California
51
+ highly detailed, high budget hollywood movie, cinemascope, moody, epic, gorgeous, film grain
52
+ """
53
+ pipeline(prompt).images[0]
54
+ ```
55
+
56
+ To restore the default attention backend, call [`~ModelMixin.reset_attention_backend`].
57
+
58
+ ```py
59
+ pipeline.transformer.reset_attention_backend()
60
+ ```
61
+
62
+ ## attention_backend context manager
63
+
64
+ The [attention_backend](https://github.com/huggingface/diffusers/blob/5e181eddfe7e44c1444a2511b0d8e21d177850a0/src/diffusers/models/attention_dispatch.py#L225) context manager temporarily sets an attention backend for a model within the context. Outside the context, the default attention (PyTorch's native scaled dot product attention) is used. This is useful if you want to use different backends for different parts of a pipeline or if you want to test the different backends.
65
+
66
+ ```py
67
+ import torch
68
+ from diffusers import QwenImagePipeline
69
+
70
+ pipeline = QwenImagePipeline.from_pretrained(
71
+ "Qwen/Qwen-Image", torch_dtype=torch.bfloat16, device_map="cuda"
72
+ )
73
+ prompt = """
74
+ cinematic film still of a cat sipping a margarita in a pool in Palm Springs, California
75
+ highly detailed, high budget hollywood movie, cinemascope, moody, epic, gorgeous, film grain
76
+ """
77
+
78
+ with attention_backend("_flash_3_hub"):
79
+ image = pipeline(prompt).images[0]
80
+ ```
81
+
82
+ > [!TIP]
83
+ > Most attention backends support `torch.compile` without graph breaks and can be used to further speed up inference.
84
+
85
+ ## Checks
86
+
87
+ The attention dispatcher includes debugging checks that catch common errors before they cause problems.
88
+
89
+ 1. Device checks verify that query, key, and value tensors live on the same device.
90
+ 2. Data type checks confirm tensors have matching dtypes and use either bfloat16 or float16.
91
+ 3. Shape checks validate tensor dimensions and prevent mixing attention masks with causal flags.
92
+
93
+ Enable these checks by setting the `DIFFUSERS_ATTN_CHECKS` environment variable. Checks add overhead to every attention operation, so they're disabled by default.
94
+
95
+ ```bash
96
+ export DIFFUSERS_ATTN_CHECKS=yes
97
+ ```
98
+
99
+ The checks are run now before every attention operation.
100
+
101
+ ```py
102
+ import torch
103
+
104
+ query = torch.randn(1, 10, 8, 64, dtype=torch.bfloat16, device="cuda")
105
+ key = torch.randn(1, 10, 8, 64, dtype=torch.bfloat16, device="cuda")
106
+ value = torch.randn(1, 10, 8, 64, dtype=torch.bfloat16, device="cuda")
107
+
108
+ try:
109
+ with attention_backend("flash"):
110
+ output = dispatch_attention_fn(query, key, value)
111
+ print("✓ Flash Attention works with checks enabled")
112
+ except Exception as e:
113
+ print(f"✗ Flash Attention failed: {e}")
114
+ ```
115
+
116
+ You can also configure the registry directly.
117
+
118
+ ```py
119
+ from diffusers.models.attention_dispatch import _AttentionBackendRegistry
120
+
121
+ _AttentionBackendRegistry._checks_enabled = True
122
+ ```
123
+
124
+ ## Available backends
125
+
126
+ Refer to the table below for a complete list of available attention backends and their variants.
127
+
128
+ <details>
129
+ <summary>Expand</summary>
130
+
131
+ | Backend Name | Family | Description |
132
+ |--------------|--------|-------------|
133
+ | `native` | [PyTorch native](https://docs.pytorch.org/docs/stable/generated/torch.nn.attention.SDPBackend.html#torch.nn.attention.SDPBackend) | Default backend using PyTorch's scaled_dot_product_attention |
134
+ | `flex` | [FlexAttention](https://docs.pytorch.org/docs/stable/nn.attention.flex_attention.html#module-torch.nn.attention.flex_attention) | PyTorch FlexAttention implementation |
135
+ | `_native_cudnn` | [PyTorch native](https://docs.pytorch.org/docs/stable/generated/torch.nn.attention.SDPBackend.html#torch.nn.attention.SDPBackend) | CuDNN-optimized attention |
136
+ | `_native_efficient` | [PyTorch native](https://docs.pytorch.org/docs/stable/generated/torch.nn.attention.SDPBackend.html#torch.nn.attention.SDPBackend) | Memory-efficient attention |
137
+ | `_native_flash` | [PyTorch native](https://docs.pytorch.org/docs/stable/generated/torch.nn.attention.SDPBackend.html#torch.nn.attention.SDPBackend) | PyTorch's FlashAttention |
138
+ | `_native_math` | [PyTorch native](https://docs.pytorch.org/docs/stable/generated/torch.nn.attention.SDPBackend.html#torch.nn.attention.SDPBackend) | Math-based attention (fallback) |
139
+ | `_native_npu` | [PyTorch native](https://docs.pytorch.org/docs/stable/generated/torch.nn.attention.SDPBackend.html#torch.nn.attention.SDPBackend) | NPU-optimized attention |
140
+ | `_native_xla` | [PyTorch native](https://docs.pytorch.org/docs/stable/generated/torch.nn.attention.SDPBackend.html#torch.nn.attention.SDPBackend) | XLA-optimized attention |
141
+ | `flash` | [FlashAttention](https://github.com/Dao-AILab/flash-attention) | FlashAttention-2 |
142
+ | `flash_varlen` | [FlashAttention](https://github.com/Dao-AILab/flash-attention) | Variable length FlashAttention |
143
+ | `aiter` | [AI Tensor Engine for ROCm](https://github.com/ROCm/aiter) | FlashAttention for AMD ROCm |
144
+ | `_flash_3` | [FlashAttention](https://github.com/Dao-AILab/flash-attention) | FlashAttention-3 |
145
+ | `_flash_varlen_3` | [FlashAttention](https://github.com/Dao-AILab/flash-attention) | Variable length FlashAttention-3 |
146
+ | `_flash_3_hub` | [FlashAttention](https://github.com/Dao-AILab/flash-attention) | FlashAttention-3 from kernels |
147
+ | `sage` | [SageAttention](https://github.com/thu-ml/SageAttention) | Quantized attention (INT8 QK) |
148
+ | `sage_varlen` | [SageAttention](https://github.com/thu-ml/SageAttention) | Variable length SageAttention |
149
+ | `_sage_qk_int8_pv_fp8_cuda` | [SageAttention](https://github.com/thu-ml/SageAttention) | INT8 QK + FP8 PV (CUDA) |
150
+ | `_sage_qk_int8_pv_fp8_cuda_sm90` | [SageAttention](https://github.com/thu-ml/SageAttention) | INT8 QK + FP8 PV (SM90) |
151
+ | `_sage_qk_int8_pv_fp16_cuda` | [SageAttention](https://github.com/thu-ml/SageAttention) | INT8 QK + FP16 PV (CUDA) |
152
+ | `_sage_qk_int8_pv_fp16_triton` | [SageAttention](https://github.com/thu-ml/SageAttention) | INT8 QK + FP16 PV (Triton) |
153
+ | `xformers` | [xFormers](https://github.com/facebookresearch/xformers) | Memory-efficient attention |
154
+
155
+ </details>
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/cache.md ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Caching
13
+
14
+ Caching accelerates inference by storing and reusing intermediate outputs of different layers, such as attention and feedforward layers, instead of performing the entire computation at each inference step. It significantly improves generation speed at the expense of more memory and doesn't require additional training.
15
+
16
+ This guide shows you how to use the caching methods supported in Diffusers.
17
+
18
+ ## Pyramid Attention Broadcast
19
+
20
+ [Pyramid Attention Broadcast (PAB)](https://huggingface.co/papers/2408.12588) is based on the observation that attention outputs aren't that different between successive timesteps of the generation process. The attention differences are smallest in the cross attention layers and are generally cached over a longer timestep range. This is followed by temporal attention and spatial attention layers.
21
+
22
+ > [!TIP]
23
+ > Not all video models have three types of attention (cross, temporal, and spatial)!
24
+
25
+ PAB can be combined with other techniques like sequence parallelism and classifier-free guidance parallelism (data parallelism) for near real-time video generation.
26
+
27
+ Set up and pass a [`PyramidAttentionBroadcastConfig`] to a pipeline's transformer to enable it. The `spatial_attention_block_skip_range` controls how often to skip attention calculations in the spatial attention blocks and the `spatial_attention_timestep_skip_range` is the range of timesteps to skip. Take care to choose an appropriate range because a smaller interval can lead to slower inference speeds and a larger interval can result in lower generation quality.
28
+
29
+ ```python
30
+ import torch
31
+ from diffusers import CogVideoXPipeline, PyramidAttentionBroadcastConfig
32
+
33
+ pipeline = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-5b", torch_dtype=torch.bfloat16)
34
+ pipeline.to("cuda")
35
+
36
+ config = PyramidAttentionBroadcastConfig(
37
+ spatial_attention_block_skip_range=2,
38
+ spatial_attention_timestep_skip_range=(100, 800),
39
+ current_timestep_callback=lambda: pipe.current_timestep,
40
+ )
41
+ pipeline.transformer.enable_cache(config)
42
+ ```
43
+
44
+ ## FasterCache
45
+
46
+ [FasterCache](https://huggingface.co/papers/2410.19355) caches and reuses attention features similar to [PAB](#pyramid-attention-broadcast) since output differences are small for each successive timestep.
47
+
48
+ This method may also choose to skip the unconditional branch prediction, when using classifier-free guidance for sampling (common in most base models), and estimate it from the conditional branch prediction if there is significant redundancy in the predicted latent outputs between successive timesteps.
49
+
50
+ Set up and pass a [`FasterCacheConfig`] to a pipeline's transformer to enable it.
51
+
52
+ ```python
53
+ import torch
54
+ from diffusers import CogVideoXPipeline, FasterCacheConfig
55
+
56
+ pipe line= CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-5b", torch_dtype=torch.bfloat16)
57
+ pipeline.to("cuda")
58
+
59
+ config = FasterCacheConfig(
60
+ spatial_attention_block_skip_range=2,
61
+ spatial_attention_timestep_skip_range=(-1, 681),
62
+ current_timestep_callback=lambda: pipe.current_timestep,
63
+ attention_weight_callback=lambda _: 0.3,
64
+ unconditional_batch_skip_range=5,
65
+ unconditional_batch_timestep_skip_range=(-1, 781),
66
+ tensor_format="BFCHW",
67
+ )
68
+ pipeline.transformer.enable_cache(config)
69
+ ```
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/cache_dit.md ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## CacheDiT
2
+
3
+ CacheDiT is a unified, flexible, and training-free cache acceleration framework designed to support nearly all Diffusers' DiT-based pipelines. It provides a unified cache API that supports automatic block adapter, DBCache, and more.
4
+
5
+ To learn more, refer to the [CacheDiT](https://github.com/vipshop/cache-dit) repository.
6
+
7
+ Install a stable release of CacheDiT from PyPI or you can install the latest version from GitHub.
8
+
9
+ <hfoptions id="install">
10
+ <hfoption id="PyPI">
11
+
12
+ ```bash
13
+ pip3 install -U cache-dit
14
+ ```
15
+
16
+ </hfoption>
17
+ <hfoption id="source">
18
+
19
+ ```bash
20
+ pip3 install git+https://github.com/vipshop/cache-dit.git
21
+ ```
22
+
23
+ </hfoption>
24
+ </hfoptions>
25
+
26
+ Run the command below to view supported DiT pipelines.
27
+
28
+ ```python
29
+ >>> import cache_dit
30
+ >>> cache_dit.supported_pipelines()
31
+ (30, ['Flux*', 'Mochi*', 'CogVideoX*', 'Wan*', 'HunyuanVideo*', 'QwenImage*', 'LTX*', 'Allegro*',
32
+ 'CogView3Plus*', 'CogView4*', 'Cosmos*', 'EasyAnimate*', 'SkyReelsV2*', 'StableDiffusion3*',
33
+ 'ConsisID*', 'DiT*', 'Amused*', 'Bria*', 'Lumina*', 'OmniGen*', 'PixArt*', 'Sana*', 'StableAudio*',
34
+ 'VisualCloze*', 'AuraFlow*', 'Chroma*', 'ShapE*', 'HiDream*', 'HunyuanDiT*', 'HunyuanDiTPAG*'])
35
+ ```
36
+
37
+ For a complete benchmark, please refer to [Benchmarks](https://github.com/vipshop/cache-dit/blob/main/bench/).
38
+
39
+
40
+ ## Unified Cache API
41
+
42
+ CacheDiT works by matching specific input/output patterns as shown below.
43
+
44
+ ![](https://github.com/vipshop/cache-dit/raw/main/assets/patterns-v1.png)
45
+
46
+ Call the `enable_cache()` function on a pipeline to enable cache acceleration. This function is the entry point to many of CacheDiT's features.
47
+
48
+ ```python
49
+ import cache_dit
50
+ from diffusers import DiffusionPipeline
51
+
52
+ # Can be any diffusion pipeline
53
+ pipe = DiffusionPipeline.from_pretrained("Qwen/Qwen-Image")
54
+
55
+ # One-line code with default cache options.
56
+ cache_dit.enable_cache(pipe)
57
+
58
+ # Just call the pipe as normal.
59
+ output = pipe(...)
60
+
61
+ # Disable cache and run original pipe.
62
+ cache_dit.disable_cache(pipe)
63
+ ```
64
+
65
+ ## Automatic Block Adapter
66
+
67
+ For custom or modified pipelines or transformers not included in Diffusers, use the `BlockAdapter` in `auto` mode or via manual configuration. Please check the [BlockAdapter](https://github.com/vipshop/cache-dit/blob/main/docs/User_Guide.md#automatic-block-adapter) docs for more details. Refer to [Qwen-Image w/ BlockAdapter](https://github.com/vipshop/cache-dit/blob/main/examples/adapter/run_qwen_image_adapter.py) as an example.
68
+
69
+
70
+ ```python
71
+ from cache_dit import ForwardPattern, BlockAdapter
72
+
73
+ # Use 🔥BlockAdapter with `auto` mode.
74
+ cache_dit.enable_cache(
75
+ BlockAdapter(
76
+ # Any DiffusionPipeline, Qwen-Image, etc.
77
+ pipe=pipe, auto=True,
78
+ # Check `📚Forward Pattern Matching` documentation and hack the code of
79
+ # of Qwen-Image, you will find that it has satisfied `FORWARD_PATTERN_1`.
80
+ forward_pattern=ForwardPattern.Pattern_1,
81
+ ),
82
+ )
83
+
84
+ # Or, manually setup transformer configurations.
85
+ cache_dit.enable_cache(
86
+ BlockAdapter(
87
+ pipe=pipe, # Qwen-Image, etc.
88
+ transformer=pipe.transformer,
89
+ blocks=pipe.transformer.transformer_blocks,
90
+ forward_pattern=ForwardPattern.Pattern_1,
91
+ ),
92
+ )
93
+ ```
94
+
95
+ Sometimes, a Transformer class will contain more than one transformer `blocks`. For example, FLUX.1 (HiDream, Chroma, etc) contains `transformer_blocks` and `single_transformer_blocks` (with different forward patterns). The BlockAdapter is able to detect this hybrid pattern type as well.
96
+ Refer to [FLUX.1](https://github.com/vipshop/cache-dit/blob/main/examples/adapter/run_flux_adapter.py) as an example.
97
+
98
+ ```python
99
+ # For diffusers <= 0.34.0, FLUX.1 transformer_blocks and
100
+ # single_transformer_blocks have different forward patterns.
101
+ cache_dit.enable_cache(
102
+ BlockAdapter(
103
+ pipe=pipe, # FLUX.1, etc.
104
+ transformer=pipe.transformer,
105
+ blocks=[
106
+ pipe.transformer.transformer_blocks,
107
+ pipe.transformer.single_transformer_blocks,
108
+ ],
109
+ forward_pattern=[
110
+ ForwardPattern.Pattern_1,
111
+ ForwardPattern.Pattern_3,
112
+ ],
113
+ ),
114
+ )
115
+ ```
116
+
117
+ This also works if there is more than one transformer (namely `transformer` and `transformer_2`) in its structure. Refer to [Wan 2.2 MoE](https://github.com/vipshop/cache-dit/blob/main/examples/pipeline/run_wan_2.2.py) as an example.
118
+
119
+ ## Patch Functor
120
+
121
+ For any pattern not included in CacheDiT, use the Patch Functor to convert the pattern into a known pattern. You need to subclass the Patch Functor and may also need to fuse the operations within the blocks for loop into block `forward`. After implementing a Patch Functor, set the `patch_functor` property in `BlockAdapter`.
122
+
123
+ ![](https://github.com/vipshop/cache-dit/raw/main/assets/patch-functor.png)
124
+
125
+ Some Patch Functors are already provided in CacheDiT, [HiDreamPatchFunctor](https://github.com/vipshop/cache-dit/blob/main/src/cache_dit/cache_factory/patch_functors/functor_hidream.py), [ChromaPatchFunctor](https://github.com/vipshop/cache-dit/blob/main/src/cache_dit/cache_factory/patch_functors/functor_chroma.py), etc.
126
+
127
+ ```python
128
+ @BlockAdapterRegistry.register("HiDream")
129
+ def hidream_adapter(pipe, **kwargs) -> BlockAdapter:
130
+ from diffusers import HiDreamImageTransformer2DModel
131
+ from cache_dit.cache_factory.patch_functors import HiDreamPatchFunctor
132
+
133
+ assert isinstance(pipe.transformer, HiDreamImageTransformer2DModel)
134
+ return BlockAdapter(
135
+ pipe=pipe,
136
+ transformer=pipe.transformer,
137
+ blocks=[
138
+ pipe.transformer.double_stream_blocks,
139
+ pipe.transformer.single_stream_blocks,
140
+ ],
141
+ forward_pattern=[
142
+ ForwardPattern.Pattern_0,
143
+ ForwardPattern.Pattern_3,
144
+ ],
145
+ # NOTE: Setup your custom patch functor here.
146
+ patch_functor=HiDreamPatchFunctor(),
147
+ **kwargs,
148
+ )
149
+ ```
150
+
151
+ Finally, you can call the `cache_dit.summary()` function on a pipeline after its completed inference to get the cache acceleration details.
152
+
153
+ ```python
154
+ stats = cache_dit.summary(pipe)
155
+ ```
156
+
157
+ ```python
158
+ ⚡️Cache Steps and Residual Diffs Statistics: QwenImagePipeline
159
+
160
+ | Cache Steps | Diffs Min | Diffs P25 | Diffs P50 | Diffs P75 | Diffs P95 | Diffs Max |
161
+ |-------------|-----------|-----------|-----------|-----------|-----------|-----------|
162
+ | 23 | 0.045 | 0.084 | 0.114 | 0.147 | 0.241 | 0.297 |
163
+ ```
164
+
165
+ ## DBCache: Dual Block Cache
166
+
167
+ ![](https://github.com/vipshop/cache-dit/raw/main/assets/dbcache-v1.png)
168
+
169
+ DBCache (Dual Block Caching) supports different configurations of compute blocks (F8B12, etc.) to enable a balanced trade-off between performance and precision.
170
+ - Fn_compute_blocks: Specifies that DBCache uses the **first n** Transformer blocks to fit the information at time step t, enabling the calculation of a more stable L1 diff and delivering more accurate information to subsequent blocks.
171
+ - Bn_compute_blocks: Further fuses approximate information in the **last n** Transformer blocks to enhance prediction accuracy. These blocks act as an auto-scaler for approximate hidden states that use residual cache.
172
+
173
+
174
+ ```python
175
+ import cache_dit
176
+ from diffusers import FluxPipeline
177
+
178
+ pipe_or_adapter = FluxPipeline.from_pretrained(
179
+ "black-forest-labs/FLUX.1-dev",
180
+ torch_dtype=torch.bfloat16,
181
+ ).to("cuda")
182
+
183
+ # Default options, F8B0, 8 warmup steps, and unlimited cached
184
+ # steps for good balance between performance and precision
185
+ cache_dit.enable_cache(pipe_or_adapter)
186
+
187
+ # Custom options, F8B8, higher precision
188
+ from cache_dit import BasicCacheConfig
189
+
190
+ cache_dit.enable_cache(
191
+ pipe_or_adapter,
192
+ cache_config=BasicCacheConfig(
193
+ max_warmup_steps=8, # steps do not cache
194
+ max_cached_steps=-1, # -1 means no limit
195
+ Fn_compute_blocks=8, # Fn, F8, etc.
196
+ Bn_compute_blocks=8, # Bn, B8, etc.
197
+ residual_diff_threshold=0.12,
198
+ ),
199
+ )
200
+ ```
201
+ Check the [DBCache](https://github.com/vipshop/cache-dit/blob/main/docs/DBCache.md) and [User Guide](https://github.com/vipshop/cache-dit/blob/main/docs/User_Guide.md#dbcache) docs for more design details.
202
+
203
+ ## TaylorSeer Calibrator
204
+
205
+ The [TaylorSeers](https://huggingface.co/papers/2503.06923) algorithm further improves the precision of DBCache in cases where the cached steps are large (Hybrid TaylorSeer + DBCache). At timesteps with significant intervals, the feature similarity in diffusion models decreases substantially, significantly harming the generation quality.
206
+
207
+ TaylorSeer employs a differential method to approximate the higher-order derivatives of features and predict features in future timesteps with Taylor series expansion. The TaylorSeer implemented in CacheDiT supports both hidden states and residual cache types. F_pred can be a residual cache or a hidden-state cache.
208
+
209
+ ```python
210
+ from cache_dit import BasicCacheConfig, TaylorSeerCalibratorConfig
211
+
212
+ cache_dit.enable_cache(
213
+ pipe_or_adapter,
214
+ # Basic DBCache w/ FnBn configurations
215
+ cache_config=BasicCacheConfig(
216
+ max_warmup_steps=8, # steps do not cache
217
+ max_cached_steps=-1, # -1 means no limit
218
+ Fn_compute_blocks=8, # Fn, F8, etc.
219
+ Bn_compute_blocks=8, # Bn, B8, etc.
220
+ residual_diff_threshold=0.12,
221
+ ),
222
+ # Then, you can use the TaylorSeer Calibrator to approximate
223
+ # the values in cached steps, taylorseer_order default is 1.
224
+ calibrator_config=TaylorSeerCalibratorConfig(
225
+ taylorseer_order=1,
226
+ ),
227
+ )
228
+ ```
229
+
230
+ > [!TIP]
231
+ > The `Bn_compute_blocks` parameter of DBCache can be set to `0` if you use TaylorSeer as the calibrator for approximate hidden states. DBCache's `Bn_compute_blocks` also acts as a calibrator, so you can choose either `Bn_compute_blocks` > 0 or TaylorSeer. We recommend using the configuration scheme of TaylorSeer + DBCache FnB0.
232
+
233
+ ## Hybrid Cache CFG
234
+
235
+ CacheDiT supports caching for CFG (classifier-free guidance). For models that fuse CFG and non-CFG into a single forward step, or models that do not include CFG in the forward step, please set `enable_separate_cfg` parameter to `False (default, None)`. Otherwise, set it to `True`.
236
+
237
+ ```python
238
+ from cache_dit import BasicCacheConfig
239
+
240
+ cache_dit.enable_cache(
241
+ pipe_or_adapter,
242
+ cache_config=BasicCacheConfig(
243
+ ...,
244
+ # For example, set it as True for Wan 2.1, Qwen-Image
245
+ # and set it as False for FLUX.1, HunyuanVideo, etc.
246
+ enable_separate_cfg=True,
247
+ ),
248
+ )
249
+ ```
250
+
251
+ ## torch.compile
252
+
253
+ CacheDiT is designed to work with torch.compile for even better performance. Call `torch.compile` after enabling the cache.
254
+
255
+
256
+ ```python
257
+ cache_dit.enable_cache(pipe)
258
+
259
+ # Compile the Transformer module
260
+ pipe.transformer = torch.compile(pipe.transformer)
261
+ ```
262
+
263
+ If you're using CacheDiT with dynamic input shapes, consider increasing the `recompile_limit` of `torch._dynamo`. Otherwise, the `recompile_limit` error may be triggered, causing the module to fall back to eager mode.
264
+
265
+ ```python
266
+ torch._dynamo.config.recompile_limit = 96 # default is 8
267
+ torch._dynamo.config.accumulated_recompile_limit = 2048 # default is 256
268
+ ```
269
+
270
+ Please check [perf.py](https://github.com/vipshop/cache-dit/blob/main/bench/perf.py) for more details.
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/coreml.md ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # How to run Stable Diffusion with Core ML
14
+
15
+ [Core ML](https://developer.apple.com/documentation/coreml) is the model format and machine learning library supported by Apple frameworks. If you are interested in running Stable Diffusion models inside your macOS or iOS/iPadOS apps, this guide will show you how to convert existing PyTorch checkpoints into the Core ML format and use them for inference with Python or Swift.
16
+
17
+ Core ML models can leverage all the compute engines available in Apple devices: the CPU, the GPU, and the Apple Neural Engine (or ANE, a tensor-optimized accelerator available in Apple Silicon Macs and modern iPhones/iPads). Depending on the model and the device it's running on, Core ML can mix and match compute engines too, so some portions of the model may run on the CPU while others run on GPU, for example.
18
+
19
+ > [!TIP]
20
+ > You can also run the `diffusers` Python codebase on Apple Silicon Macs using the `mps` accelerator built into PyTorch. This approach is explained in depth in [the mps guide](mps), but it is not compatible with native apps.
21
+
22
+ ## Stable Diffusion Core ML Checkpoints
23
+
24
+ Stable Diffusion weights (or checkpoints) are stored in the PyTorch format, so you need to convert them to the Core ML format before we can use them inside native apps.
25
+
26
+ Thankfully, Apple engineers developed [a conversion tool](https://github.com/apple/ml-stable-diffusion#-converting-models-to-core-ml) based on `diffusers` to convert the PyTorch checkpoints to Core ML.
27
+
28
+ Before you convert a model, though, take a moment to explore the Hugging Face Hub – chances are the model you're interested in is already available in Core ML format:
29
+
30
+ - the [Apple](https://huggingface.co/apple) organization includes Stable Diffusion versions 1.4, 1.5, 2.0 base, and 2.1 base
31
+ - [coreml community](https://huggingface.co/coreml-community) includes custom finetuned models
32
+ - use this [filter](https://huggingface.co/models?pipeline_tag=text-to-image&library=coreml&p=2&sort=likes) to return all available Core ML checkpoints
33
+
34
+ If you can't find the model you're interested in, we recommend you follow the instructions for [Converting Models to Core ML](https://github.com/apple/ml-stable-diffusion#-converting-models-to-core-ml) by Apple.
35
+
36
+ ## Selecting the Core ML Variant to Use
37
+
38
+ Stable Diffusion models can be converted to different Core ML variants intended for different purposes:
39
+
40
+ - The type of attention blocks used. The attention operation is used to "pay attention" to the relationship between different areas in the image representations and to understand how the image and text representations are related. Attention is compute- and memory-intensive, so different implementations exist that consider the hardware characteristics of different devices. For Core ML Stable Diffusion models, there are two attention variants:
41
+ * `split_einsum` ([introduced by Apple](https://machinelearning.apple.com/research/neural-engine-transformers)) is optimized for ANE devices, which is available in modern iPhones, iPads and M-series computers.
42
+ * The "original" attention (the base implementation used in `diffusers`) is only compatible with CPU/GPU and not ANE. It can be *faster* to run your model on CPU + GPU using `original` attention than ANE. See [this performance benchmark](https://huggingface.co/blog/fast-mac-diffusers#performance-benchmarks) as well as some [additional measures provided by the community](https://github.com/huggingface/swift-coreml-diffusers/issues/31) for additional details.
43
+
44
+ - The supported inference framework.
45
+ * `packages` are suitable for Python inference. This can be used to test converted Core ML models before attempting to integrate them inside native apps, or if you want to explore Core ML performance but don't need to support native apps. For example, an application with a web UI could perfectly use a Python Core ML backend.
46
+ * `compiled` models are required for Swift code. The `compiled` models in the Hub split the large UNet model weights into several files for compatibility with iOS and iPadOS devices. This corresponds to the [`--chunk-unet` conversion option](https://github.com/apple/ml-stable-diffusion#-converting-models-to-core-ml). If you want to support native apps, then you need to select the `compiled` variant.
47
+
48
+ The official Core ML Stable Diffusion [models](https://huggingface.co/apple/coreml-stable-diffusion-v1-4/tree/main) include these variants, but the community ones may vary:
49
+
50
+ ```
51
+ coreml-stable-diffusion-v1-4
52
+ ├── README.md
53
+ ├── original
54
+ │ ├── compiled
55
+ │ └── packages
56
+ └── split_einsum
57
+ ├── compiled
58
+ └── packages
59
+ ```
60
+
61
+ You can download and use the variant you need as shown below.
62
+
63
+ ## Core ML Inference in Python
64
+
65
+ Install the following libraries to run Core ML inference in Python:
66
+
67
+ ```bash
68
+ pip install huggingface_hub
69
+ pip install git+https://github.com/apple/ml-stable-diffusion
70
+ ```
71
+
72
+ ### Download the Model Checkpoints
73
+
74
+ To run inference in Python, use one of the versions stored in the `packages` folders because the `compiled` ones are only compatible with Swift. You may choose whether you want to use `original` or `split_einsum` attention.
75
+
76
+ This is how you'd download the `original` attention variant from the Hub to a directory called `models`:
77
+
78
+ ```Python
79
+ from huggingface_hub import snapshot_download
80
+ from pathlib import Path
81
+
82
+ repo_id = "apple/coreml-stable-diffusion-v1-4"
83
+ variant = "original/packages"
84
+
85
+ model_path = Path("./models") / (repo_id.split("/")[-1] + "_" + variant.replace("/", "_"))
86
+ snapshot_download(repo_id, allow_patterns=f"{variant}/*", local_dir=model_path, local_dir_use_symlinks=False)
87
+ print(f"Model downloaded at {model_path}")
88
+ ```
89
+
90
+ ### Inference[[python-inference]]
91
+
92
+ Once you have downloaded a snapshot of the model, you can test it using Apple's Python script.
93
+
94
+ ```shell
95
+ python -m python_coreml_stable_diffusion.pipeline --prompt "a photo of an astronaut riding a horse on mars" -i ./models/coreml-stable-diffusion-v1-4_original_packages/original/packages -o </path/to/output/image> --compute-unit CPU_AND_GPU --seed 93
96
+ ```
97
+
98
+ Pass the path of the downloaded checkpoint with `-i` flag to the script. `--compute-unit` indicates the hardware you want to allow for inference. It must be one of the following options: `ALL`, `CPU_AND_GPU`, `CPU_ONLY`, `CPU_AND_NE`. You may also provide an optional output path, and a seed for reproducibility.
99
+
100
+ The inference script assumes you're using the original version of the Stable Diffusion model, `CompVis/stable-diffusion-v1-4`. If you use another model, you *have* to specify its Hub id in the inference command line, using the `--model-version` option. This works for models already supported and custom models you trained or fine-tuned yourself.
101
+
102
+ For example, if you want to use [`stable-diffusion-v1-5/stable-diffusion-v1-5`](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5):
103
+
104
+ ```shell
105
+ python -m python_coreml_stable_diffusion.pipeline --prompt "a photo of an astronaut riding a horse on mars" --compute-unit ALL -o output --seed 93 -i models/coreml-stable-diffusion-v1-5_original_packages --model-version stable-diffusion-v1-5/stable-diffusion-v1-5
106
+ ```
107
+
108
+ ## Core ML inference in Swift
109
+
110
+ Running inference in Swift is slightly faster than in Python because the models are already compiled in the `mlmodelc` format. This is noticeable on app startup when the model is loaded but shouldn’t be noticeable if you run several generations afterward.
111
+
112
+ ### Download
113
+
114
+ To run inference in Swift on your Mac, you need one of the `compiled` checkpoint versions. We recommend you download them locally using Python code similar to the previous example, but with one of the `compiled` variants:
115
+
116
+ ```Python
117
+ from huggingface_hub import snapshot_download
118
+ from pathlib import Path
119
+
120
+ repo_id = "apple/coreml-stable-diffusion-v1-4"
121
+ variant = "original/compiled"
122
+
123
+ model_path = Path("./models") / (repo_id.split("/")[-1] + "_" + variant.replace("/", "_"))
124
+ snapshot_download(repo_id, allow_patterns=f"{variant}/*", local_dir=model_path, local_dir_use_symlinks=False)
125
+ print(f"Model downloaded at {model_path}")
126
+ ```
127
+
128
+ ### Inference[[swift-inference]]
129
+
130
+ To run inference, please clone Apple's repo:
131
+
132
+ ```bash
133
+ git clone https://github.com/apple/ml-stable-diffusion
134
+ cd ml-stable-diffusion
135
+ ```
136
+
137
+ And then use Apple's command line tool, [Swift Package Manager](https://www.swift.org/package-manager/#):
138
+
139
+ ```bash
140
+ swift run StableDiffusionSample --resource-path models/coreml-stable-diffusion-v1-4_original_compiled --compute-units all "a photo of an astronaut riding a horse on mars"
141
+ ```
142
+
143
+ You have to specify in `--resource-path` one of the checkpoints downloaded in the previous step, so please make sure it contains compiled Core ML bundles with the extension `.mlmodelc`. The `--compute-units` has to be one of these values: `all`, `cpuOnly`, `cpuAndGPU`, `cpuAndNeuralEngine`.
144
+
145
+ For more details, please refer to the [instructions in Apple's repo](https://github.com/apple/ml-stable-diffusion).
146
+
147
+ ## Supported Diffusers Features
148
+
149
+ The Core ML models and inference code don't support many of the features, options, and flexibility of 🧨 Diffusers. These are some of the limitations to keep in mind:
150
+
151
+ - Core ML models are only suitable for inference. They can't be used for training or fine-tuning.
152
+ - Only two schedulers have been ported to Swift, the default one used by Stable Diffusion and `DPMSolverMultistepScheduler`, which we ported to Swift from our `diffusers` implementation. We recommend you use `DPMSolverMultistepScheduler`, since it produces the same quality in about half the steps.
153
+ - Negative prompts, classifier-free guidance scale, and image-to-image tasks are available in the inference code. Advanced features such as depth guidance, ControlNet, and latent upscalers are not available yet.
154
+
155
+ Apple's [conversion and inference repo](https://github.com/apple/ml-stable-diffusion) and our own [swift-coreml-diffusers](https://github.com/huggingface/swift-coreml-diffusers) repos are intended as technology demonstrators to enable other developers to build upon.
156
+
157
+ If you feel strongly about any missing features, please feel free to open a feature request or, better yet, a contribution PR 🙂.
158
+
159
+ ## Native Diffusers Swift app
160
+
161
+ One easy way to run Stable Diffusion on your own Apple hardware is to use [our open-source Swift repo](https://github.com/huggingface/swift-coreml-diffusers), based on `diffusers` and Apple's conversion and inference repo. You can study the code, compile it with [Xcode](https://developer.apple.com/xcode/) and adapt it for your own needs. For your convenience, there's also a [standalone Mac app in the App Store](https://apps.apple.com/app/diffusers/id1666309574), so you can play with it without having to deal with the code or IDE. If you are a developer and have determined that Core ML is the best solution to build your Stable Diffusion app, then you can use the rest of this guide to get started with your project. We can't wait to see what you'll build 🙂.
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/deepcache.md ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # DeepCache
14
+ [DeepCache](https://huggingface.co/papers/2312.00858) accelerates [`StableDiffusionPipeline`] and [`StableDiffusionXLPipeline`] by strategically caching and reusing high-level features while efficiently updating low-level features by taking advantage of the U-Net architecture.
15
+
16
+ Start by installing [DeepCache](https://github.com/horseee/DeepCache):
17
+ ```bash
18
+ pip install DeepCache
19
+ ```
20
+
21
+ Then load and enable the [`DeepCacheSDHelper`](https://github.com/horseee/DeepCache#usage):
22
+
23
+ ```diff
24
+ import torch
25
+ from diffusers import StableDiffusionPipeline
26
+ pipe = StableDiffusionPipeline.from_pretrained('stable-diffusion-v1-5/stable-diffusion-v1-5', torch_dtype=torch.float16).to("cuda")
27
+
28
+ + from DeepCache import DeepCacheSDHelper
29
+ + helper = DeepCacheSDHelper(pipe=pipe)
30
+ + helper.set_params(
31
+ + cache_interval=3,
32
+ + cache_branch_id=0,
33
+ + )
34
+ + helper.enable()
35
+
36
+ image = pipe("a photo of an astronaut on a moon").images[0]
37
+ ```
38
+
39
+ The `set_params` method accepts two arguments: `cache_interval` and `cache_branch_id`. `cache_interval` means the frequency of feature caching, specified as the number of steps between each cache operation. `cache_branch_id` identifies which branch of the network (ordered from the shallowest to the deepest layer) is responsible for executing the caching processes.
40
+ Opting for a lower `cache_branch_id` or a larger `cache_interval` can lead to faster inference speed at the expense of reduced image quality (ablation experiments of these two hyperparameters can be found in the [paper](https://huggingface.co/papers/2312.00858)). Once those arguments are set, use the `enable` or `disable` methods to activate or deactivate the `DeepCacheSDHelper`.
41
+
42
+ <div class="flex justify-center">
43
+ <img src="https://github.com/horseee/Diffusion_DeepCache/raw/master/static/images/example.png">
44
+ </div>
45
+
46
+ You can find more generated samples (original pipeline vs DeepCache) and the corresponding inference latency in the [WandB report](https://wandb.ai/horseee/DeepCache/runs/jwlsqqgt?workspace=user-horseee). The prompts are randomly selected from the [MS-COCO 2017](https://cocodataset.org/#home) dataset.
47
+
48
+ ## Benchmark
49
+
50
+ We tested how much faster DeepCache accelerates [Stable Diffusion v2.1](https://huggingface.co/stabilityai/stable-diffusion-2-1) with 50 inference steps on an NVIDIA RTX A5000, using different configurations for resolution, batch size, cache interval (I), and cache branch (B).
51
+
52
+ | **Resolution** | **Batch size** | **Original** | **DeepCache(I=3, B=0)** | **DeepCache(I=5, B=0)** | **DeepCache(I=5, B=1)** |
53
+ |----------------|----------------|--------------|-------------------------|-------------------------|-------------------------|
54
+ | 512| 8| 15.96| 6.88(2.32x)| 5.03(3.18x)| 7.27(2.20x)|
55
+ | | 4| 8.39| 3.60(2.33x)| 2.62(3.21x)| 3.75(2.24x)|
56
+ | | 1| 2.61| 1.12(2.33x)| 0.81(3.24x)| 1.11(2.35x)|
57
+ | 768| 8| 43.58| 18.99(2.29x)| 13.96(3.12x)| 21.27(2.05x)|
58
+ | | 4| 22.24| 9.67(2.30x)| 7.10(3.13x)| 10.74(2.07x)|
59
+ | | 1| 6.33| 2.72(2.33x)| 1.97(3.21x)| 2.98(2.12x)|
60
+ | 1024| 8| 101.95| 45.57(2.24x)| 33.72(3.02x)| 53.00(1.92x)|
61
+ | | 4| 49.25| 21.86(2.25x)| 16.19(3.04x)| 25.78(1.91x)|
62
+ | | 1| 13.83| 6.07(2.28x)| 4.43(3.12x)| 7.15(1.93x)|
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/fp16.md ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Accelerate inference
14
+
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.
16
+
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.
20
+
21
+ ## Model data type
22
+
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.
24
+
25
+ <hfoptions id="dtypes">
26
+ <hfoption id="bfloat16">
27
+
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.
29
+
30
+ ```py
31
+ import torch
32
+ from diffusers import StableDiffusionXLPipeline
33
+
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]
57
+ ```
58
+
59
+ </hfoption>
60
+ <hfoption id="TensorFloat-32">
61
+
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.
63
+
64
+ PyTorch only enables tf32 mode for convolutions by default and you'll need to explicitly enable it for matrix multiplications.
65
+
66
+ ```py
67
+ import torch
68
+ from diffusers import StableDiffusionXLPipeline
69
+
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]
78
+ ```
79
+
80
+ Refer to the [mixed precision training](https://huggingface.co/docs/transformers/en/perf_train_gpu_one#mixed-precision) docs for more details.
81
+
82
+ </hfoption>
83
+ </hfoptions>
84
+
85
+ ## Scaled dot product attention
86
+
87
+ > [!TIP]
88
+ > Memory-efficient attention optimizes for inference speed *and* [memory usage](./memory#memory-efficient-attention)!
89
+
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.
91
+
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.
93
+
94
+ ```py
95
+ from torch.nn.attention import SDPBackend, sdpa_kernel
96
+ import torch
97
+ from diffusers import StableDiffusionXLPipeline
98
+
99
+ pipeline = StableDiffusionXLPipeline.from_pretrained(
100
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.bfloat16
101
+ ).to("cuda")
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]
107
+ ```
108
+
109
+ ## torch.compile
110
+
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.
112
+
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).
114
+
115
+ ```py
116
+ import torch
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.
126
+
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
135
+ ).to("cuda")
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
+ ### Dynamic shape compilation
154
+
155
+ > [!TIP]
156
+ > Make sure to always use the nightly version of PyTorch for better support.
157
+
158
+ `torch.compile` keeps track of input shapes and conditions, and if these are different, it recompiles the model. For example, if a model is compiled on a 1024x1024 resolution image and used on an image with a different resolution, it triggers recompilation.
159
+
160
+ To avoid recompilation, add `dynamic=True` to try and generate a more dynamic kernel to avoid recompilation when conditions change.
161
+
162
+ ```diff
163
+ + torch.fx.experimental._config.use_duck_shape = False
164
+ + pipeline.unet = torch.compile(
165
+ pipeline.unet, fullgraph=True, dynamic=True
166
+ )
167
+ ```
168
+
169
+ Specifying `use_duck_shape=False` instructs the compiler if it should use the same symbolic variable to represent input sizes that are the same. For more details, check out this [comment](https://github.com/huggingface/diffusers/pull/11327#discussion_r2047659790).
170
+
171
+ Not all models may benefit from dynamic compilation out of the box and may require changes. Refer to this [PR](https://github.com/huggingface/diffusers/pull/11297/) that improved the [`AuraFlowPipeline`] implementation to benefit from dynamic compilation.
172
+
173
+ Feel free to open an issue if dynamic compilation doesn't work as expected for a Diffusers model.
174
+
175
+ ### Regional compilation
176
+
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.
179
+
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.
181
+
182
+ ```py
183
+ # pip install -U diffusers
184
+ import torch
185
+ from diffusers import StableDiffusionXLPipeline
186
+
187
+ pipeline = StableDiffusionXLPipeline.from_pretrained(
188
+ "stabilityai/stable-diffusion-xl-base-1.0",
189
+ torch_dtype=torch.float16,
190
+ ).to("cuda")
191
+
192
+ # compile only the repeated transformer layers inside the UNet
193
+ pipeline.unet.compile_repeated_blocks(fullgraph=True)
194
+ ```
195
+
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.
197
+
198
+ ```py
199
+ class MyUNet(ModelMixin):
200
+ _repeated_blocks = ("Transformer2DModel",) # ← compiled by default
201
+ ```
202
+
203
+ > [!TIP]
204
+ > For more regional compilation examples, see the reference [PR](https://github.com/huggingface/diffusers/pull/11705).
205
+
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.
207
+
208
+ ```py
209
+ # pip install -U accelerate
210
+ import torch
211
+ from diffusers import StableDiffusionXLPipeline
212
+ from accelerate.utils import compile_regions
213
+
214
+ pipeline = StableDiffusionXLPipeline.from_pretrained(
215
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
216
+ ).to("cuda")
217
+ pipeline.unet = compile_regions(pipeline.unet, mode="reduce-overhead", fullgraph=True)
218
+ ```
219
+
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.
221
+
222
+ ### Graph breaks
223
+
224
+ 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.
225
+
226
+ ```diff
227
+ - latents = unet(
228
+ - latents, timestep=timestep, encoder_hidden_states=prompt_embeds
229
+ -).sample
230
+
231
+ + latents = unet(
232
+ + latents, timestep=timestep, encoder_hidden_states=prompt_embeds, return_dict=False
233
+ +)[0]
234
+ ```
235
+
236
+ ### GPU sync
237
+
238
+ 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.
239
+
240
+ 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.
241
+
242
+ > [!TIP]
243
+ > Refer to the [torch.compile and Diffusers: A Hands-On Guide to Peak Performance](https://pytorch.org/blog/torch-compile-and-diffusers-a-hands-on-guide-to-peak-performance/) blog post for maximizing performance with `torch.compile` for diffusion models.
244
+
245
+ ### Benchmarks
246
+
247
+ Refer to the [diffusers/benchmarks](https://huggingface.co/datasets/diffusers/benchmarks) dataset to see inference latency and memory usage data for compiled pipelines.
248
+
249
+ The [diffusers-torchao](https://github.com/sayakpaul/diffusers-torchao#benchmarking-results) repository also contains benchmarking results for compiled versions of Flux and CogVideoX.
250
+
251
+ ## Dynamic quantization
252
+
253
+ [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.
254
+
255
+ 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.
256
+
257
+ > [!TIP]
258
+ > Refer to our [torchao](../quantization/torchao) docs to learn more about how to use the Diffusers torchao integration.
259
+
260
+ Configure the compiler tags for maximum speed.
261
+
262
+ ```py
263
+ import torch
264
+ from torchao import apply_dynamic_quant
265
+ from diffusers import StableDiffusionXLPipeline
266
+
267
+ torch._inductor.config.conv_1x1_as_mm = True
268
+ torch._inductor.config.coordinate_descent_tuning = True
269
+ torch._inductor.config.epilogue_fusion = False
270
+ torch._inductor.config.coordinate_descent_check_all_directions = True
271
+ torch._inductor.config.force_fuse_int_mm_with_mul = True
272
+ torch._inductor.config.use_mixed_mm = True
273
+ ```
274
+
275
+ 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).
276
+
277
+ ```py
278
+ pipeline = StableDiffusionXLPipeline.from_pretrained(
279
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.bfloat16
280
+ ).to("cuda")
281
+
282
+ apply_dynamic_quant(pipeline.unet, dynamic_quant_filter_fn)
283
+ apply_dynamic_quant(pipeline.vae, dynamic_quant_filter_fn)
284
+
285
+ prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
286
+ pipeline(prompt, num_inference_steps=30).images[0]
287
+ ```
288
+
289
+ ## Fused projection matrices
290
+
291
+ > [!WARNING]
292
+ > 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
293
+
294
+ 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.
295
+
296
+ ```py
297
+ pipeline.fuse_qkv_projections()
298
+ ```
299
+
300
+ ## Resources
301
+
302
+ - 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).
303
+
304
+ These recipes support AMD hardware and [Flux.1 Kontext Dev](https://huggingface.co/black-forest-labs/FLUX.1-Kontext-dev).
305
+ - Read the [torch.compile and Diffusers: A Hands-On Guide to Peak Performance](https://pytorch.org/blog/torch-compile-and-diffusers-a-hands-on-guide-to-peak-performance/) blog post
306
+ to maximize performance when using `torch.compile`.
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/habana.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Intel Gaudi
14
+
15
+ The Intel Gaudi AI accelerator family includes [Intel Gaudi 1](https://habana.ai/products/gaudi/), [Intel Gaudi 2](https://habana.ai/products/gaudi2/), and [Intel Gaudi 3](https://habana.ai/products/gaudi3/). Each server is equipped with 8 devices, known as Habana Processing Units (HPUs), providing 128GB of memory on Gaudi 3, 96GB on Gaudi 2, and 32GB on the first-gen Gaudi. For more details on the underlying hardware architecture, check out the [Gaudi Architecture](https://docs.habana.ai/en/latest/Gaudi_Overview/Gaudi_Architecture.html) overview.
16
+
17
+ Diffusers pipelines can take advantage of HPU acceleration, even if a pipeline hasn't been added to [Optimum for Intel Gaudi](https://huggingface.co/docs/optimum/main/en/habana/index) yet, with the [GPU Migration Toolkit](https://docs.habana.ai/en/latest/PyTorch/PyTorch_Model_Porting/GPU_Migration_Toolkit/GPU_Migration_Toolkit.html).
18
+
19
+ Call `.to("hpu")` on your pipeline to move it to a HPU device as shown below for Flux:
20
+ ```py
21
+ import torch
22
+ from diffusers import DiffusionPipeline
23
+
24
+ pipeline = DiffusionPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16)
25
+ pipeline.to("hpu")
26
+
27
+ image = pipeline("An image of a squirrel in Picasso style").images[0]
28
+ ```
29
+
30
+ > [!TIP]
31
+ > For Gaudi-optimized diffusion pipeline implementations, we recommend using [Optimum for Intel Gaudi](https://huggingface.co/docs/optimum/main/en/habana/index).
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/memory.md ADDED
@@ -0,0 +1,625 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Reduce memory usage
14
+
15
+ Modern diffusion models like [Flux](../api/pipelines/flux) and [Wan](../api/pipelines/wan) have billions of parameters that take up a lot of memory on your hardware for inference. This is challenging because common GPUs often don't have sufficient memory. To overcome the memory limitations, you can use more than one GPU (if available), offload some of the pipeline components to the CPU, and more.
16
+
17
+ This guide will show you how to reduce your memory usage.
18
+
19
+ > [!TIP]
20
+ > Keep in mind these techniques may need to be adjusted depending on the model. For example, a transformer-based diffusion model may not benefit equally from these memory optimizations as a UNet-based model.
21
+
22
+ ## Multiple GPUs
23
+
24
+ If you have access to more than one GPU, there a few options for efficiently loading and distributing a large model across your hardware. These features are supported by the [Accelerate](https://huggingface.co/docs/accelerate/index) library, so make sure it is installed first.
25
+
26
+ ```bash
27
+ pip install -U accelerate
28
+ ```
29
+
30
+ ### Sharded checkpoints
31
+
32
+ Loading large checkpoints in several shards in useful because the shards are loaded one at a time. This keeps memory usage low, only requiring enough memory for the model size and the largest shard size. We recommend sharding when the fp32 checkpoint is greater than 5GB. The default shard size is 5GB.
33
+
34
+ Shard a checkpoint in [`~DiffusionPipeline.save_pretrained`] with the `max_shard_size` parameter.
35
+
36
+ ```py
37
+ from diffusers import AutoModel
38
+
39
+ unet = AutoModel.from_pretrained(
40
+ "stabilityai/stable-diffusion-xl-base-1.0", subfolder="unet"
41
+ )
42
+ unet.save_pretrained("sdxl-unet-sharded", max_shard_size="5GB")
43
+ ```
44
+
45
+ Now you can use the sharded checkpoint, instead of the regular checkpoint, to save memory.
46
+
47
+ ```py
48
+ import torch
49
+ from diffusers import AutoModel, StableDiffusionXLPipeline
50
+
51
+ unet = AutoModel.from_pretrained(
52
+ "username/sdxl-unet-sharded", torch_dtype=torch.float16
53
+ )
54
+ pipeline = StableDiffusionXLPipeline.from_pretrained(
55
+ "stabilityai/stable-diffusion-xl-base-1.0",
56
+ unet=unet,
57
+ torch_dtype=torch.float16
58
+ ).to("cuda")
59
+ ```
60
+
61
+ ### Device placement
62
+
63
+ > [!WARNING]
64
+ > Device placement is an experimental feature and the API may change. Only the `balanced` strategy is supported at the moment. We plan to support additional mapping strategies in the future.
65
+
66
+ The `device_map` parameter controls how the model components in a pipeline or the layers in an individual model are distributed across devices.
67
+
68
+ <hfoptions id="device-map">
69
+ <hfoption id="pipeline level">
70
+
71
+ The `balanced` device placement strategy evenly splits the pipeline across all available devices.
72
+
73
+ ```py
74
+ import torch
75
+ from diffusers import AutoModel, StableDiffusionXLPipeline
76
+
77
+ pipeline = StableDiffusionXLPipeline.from_pretrained(
78
+ "stabilityai/stable-diffusion-xl-base-1.0",
79
+ torch_dtype=torch.float16,
80
+ device_map="balanced"
81
+ )
82
+ ```
83
+
84
+ You can inspect a pipeline's device map with `hf_device_map`.
85
+
86
+ ```py
87
+ print(pipeline.hf_device_map)
88
+ {'unet': 1, 'vae': 1, 'safety_checker': 0, 'text_encoder': 0}
89
+ ```
90
+
91
+ </hfoption>
92
+ <hfoption id="model level">
93
+
94
+ The `device_map` is useful for loading large models, such as the Flux diffusion transformer which has 12.5B parameters. Set it to `"auto"` to automatically distribute a model across the fastest device first before moving to slower devices. Refer to the [Model sharding](../training/distributed_inference#model-sharding) docs for more details.
95
+
96
+ ```py
97
+ import torch
98
+ from diffusers import AutoModel
99
+
100
+ transformer = AutoModel.from_pretrained(
101
+ "black-forest-labs/FLUX.1-dev",
102
+ subfolder="transformer",
103
+ device_map="auto",
104
+ torch_dtype=torch.bfloat16
105
+ )
106
+ ```
107
+
108
+ You can inspect a model's device map with `hf_device_map`.
109
+
110
+ ```py
111
+ print(transformer.hf_device_map)
112
+ ```
113
+
114
+ </hfoption>
115
+ </hfoptions>
116
+
117
+ When designing your own `device_map`, it should be a dictionary of a model's specific module name or layer and a device identifier (an integer for GPUs, `cpu` for CPUs, and `disk` for disk).
118
+
119
+ Call `hf_device_map` on a model to see how model layers are distributed and then design your own.
120
+
121
+ ```py
122
+ print(transformer.hf_device_map)
123
+ {'pos_embed': 0, 'time_text_embed': 0, 'context_embedder': 0, 'x_embedder': 0, 'transformer_blocks': 0, 'single_transformer_blocks.0': 0, 'single_transformer_blocks.1': 0, 'single_transformer_blocks.2': 0, 'single_transformer_blocks.3': 0, 'single_transformer_blocks.4': 0, 'single_transformer_blocks.5': 0, 'single_transformer_blocks.6': 0, 'single_transformer_blocks.7': 0, 'single_transformer_blocks.8': 0, 'single_transformer_blocks.9': 0, 'single_transformer_blocks.10': 'cpu', 'single_transformer_blocks.11': 'cpu', 'single_transformer_blocks.12': 'cpu', 'single_transformer_blocks.13': 'cpu', 'single_transformer_blocks.14': 'cpu', 'single_transformer_blocks.15': 'cpu', 'single_transformer_blocks.16': 'cpu', 'single_transformer_blocks.17': 'cpu', 'single_transformer_blocks.18': 'cpu', 'single_transformer_blocks.19': 'cpu', 'single_transformer_blocks.20': 'cpu', 'single_transformer_blocks.21': 'cpu', 'single_transformer_blocks.22': 'cpu', 'single_transformer_blocks.23': 'cpu', 'single_transformer_blocks.24': 'cpu', 'single_transformer_blocks.25': 'cpu', 'single_transformer_blocks.26': 'cpu', 'single_transformer_blocks.27': 'cpu', 'single_transformer_blocks.28': 'cpu', 'single_transformer_blocks.29': 'cpu', 'single_transformer_blocks.30': 'cpu', 'single_transformer_blocks.31': 'cpu', 'single_transformer_blocks.32': 'cpu', 'single_transformer_blocks.33': 'cpu', 'single_transformer_blocks.34': 'cpu', 'single_transformer_blocks.35': 'cpu', 'single_transformer_blocks.36': 'cpu', 'single_transformer_blocks.37': 'cpu', 'norm_out': 'cpu', 'proj_out': 'cpu'}
124
+ ```
125
+
126
+ For example, the `device_map` below places `single_transformer_blocks.10` through `single_transformer_blocks.20` on a second GPU (`1`).
127
+
128
+ ```py
129
+ import torch
130
+ from diffusers import AutoModel
131
+
132
+ device_map = {
133
+ 'pos_embed': 0, 'time_text_embed': 0, 'context_embedder': 0, 'x_embedder': 0, 'transformer_blocks': 0, 'single_transformer_blocks.0': 0, 'single_transformer_blocks.1': 0, 'single_transformer_blocks.2': 0, 'single_transformer_blocks.3': 0, 'single_transformer_blocks.4': 0, 'single_transformer_blocks.5': 0, 'single_transformer_blocks.6': 0, 'single_transformer_blocks.7': 0, 'single_transformer_blocks.8': 0, 'single_transformer_blocks.9': 0, 'single_transformer_blocks.10': 1, 'single_transformer_blocks.11': 1, 'single_transformer_blocks.12': 1, 'single_transformer_blocks.13': 1, 'single_transformer_blocks.14': 1, 'single_transformer_blocks.15': 1, 'single_transformer_blocks.16': 1, 'single_transformer_blocks.17': 1, 'single_transformer_blocks.18': 1, 'single_transformer_blocks.19': 1, 'single_transformer_blocks.20': 1, 'single_transformer_blocks.21': 'cpu', 'single_transformer_blocks.22': 'cpu', 'single_transformer_blocks.23': 'cpu', 'single_transformer_blocks.24': 'cpu', 'single_transformer_blocks.25': 'cpu', 'single_transformer_blocks.26': 'cpu', 'single_transformer_blocks.27': 'cpu', 'single_transformer_blocks.28': 'cpu', 'single_transformer_blocks.29': 'cpu', 'single_transformer_blocks.30': 'cpu', 'single_transformer_blocks.31': 'cpu', 'single_transformer_blocks.32': 'cpu', 'single_transformer_blocks.33': 'cpu', 'single_transformer_blocks.34': 'cpu', 'single_transformer_blocks.35': 'cpu', 'single_transformer_blocks.36': 'cpu', 'single_transformer_blocks.37': 'cpu', 'norm_out': 'cpu', 'proj_out': 'cpu'
134
+ }
135
+
136
+ transformer = AutoModel.from_pretrained(
137
+ "black-forest-labs/FLUX.1-dev",
138
+ subfolder="transformer",
139
+ device_map=device_map,
140
+ torch_dtype=torch.bfloat16
141
+ )
142
+ ```
143
+
144
+ Pass a dictionary mapping maximum memory usage to each device to enforce a limit. If a device is not in `max_memory`, it is ignored and pipeline components won't be distributed to it.
145
+
146
+ ```py
147
+ import torch
148
+ from diffusers import AutoModel, StableDiffusionXLPipeline
149
+
150
+ max_memory = {0:"1GB", 1:"1GB"}
151
+ pipeline = StableDiffusionXLPipeline.from_pretrained(
152
+ "stabilityai/stable-diffusion-xl-base-1.0",
153
+ torch_dtype=torch.float16,
154
+ device_map="balanced",
155
+ max_memory=max_memory
156
+ )
157
+ ```
158
+
159
+ Diffusers uses the maxmium memory of all devices by default, but if they don't fit on the GPUs, then you'll need to use a single GPU and offload to the CPU with the methods below.
160
+
161
+ - [`~DiffusionPipeline.enable_model_cpu_offload`] only works on a single GPU but a very large model may not fit on it
162
+ - [`~DiffusionPipeline.enable_sequential_cpu_offload`] may work but it is extremely slow and also limited to a single GPU
163
+
164
+ Use the [`~DiffusionPipeline.reset_device_map`] method to reset the `device_map`. This is necessary if you want to use methods like `.to()`, [`~DiffusionPipeline.enable_sequential_cpu_offload`], and [`~DiffusionPipeline.enable_model_cpu_offload`] on a pipeline that was device-mapped.
165
+
166
+ ```py
167
+ pipeline.reset_device_map()
168
+ ```
169
+
170
+ ## VAE slicing
171
+
172
+ VAE slicing saves memory by splitting large batches of inputs into a single batch of data and separately processing them. This method works best when generating more than one image at a time.
173
+
174
+ For example, if you're generating 4 images at once, decoding would increase peak activation memory by 4x. VAE slicing reduces this by only decoding 1 image at a time instead of all 4 images at once.
175
+
176
+ Call [`~StableDiffusionPipeline.enable_vae_slicing`] to enable sliced VAE. You can expect a small increase in performance when decoding multi-image batches and no performance impact for single-image batches.
177
+
178
+ ```py
179
+ import torch
180
+ from diffusers import AutoModel, StableDiffusionXLPipeline
181
+
182
+ pipeline = StableDiffusionXLPipeline.from_pretrained(
183
+ "stabilityai/stable-diffusion-xl-base-1.0",
184
+ torch_dtype=torch.float16,
185
+ ).to("cuda")
186
+ pipeline.enable_vae_slicing()
187
+ pipeline(["An astronaut riding a horse on Mars"]*32).images[0]
188
+ print(f"Max memory reserved: {torch.cuda.max_memory_allocated() / 1024**3:.2f} GB")
189
+ ```
190
+
191
+ > [!WARNING]
192
+ > The [`AutoencoderKLWan`] and [`AsymmetricAutoencoderKL`] classes don't support slicing.
193
+
194
+ ## VAE tiling
195
+
196
+ VAE tiling saves memory by dividing an image into smaller overlapping tiles instead of processing the entire image at once. This also reduces peak memory usage because the GPU is only processing a tile at a time.
197
+
198
+ Call [`~StableDiffusionPipeline.enable_vae_tiling`] to enable VAE tiling. The generated image may have some tone variation from tile-to-tile because they're decoded separately, but there shouldn't be any obvious seams between the tiles. Tiling is disabled for resolutions lower than a pre-specified (but configurable) limit. For example, this limit is 512x512 for the VAE in [`StableDiffusionPipeline`].
199
+
200
+ ```py
201
+ import torch
202
+ from diffusers import AutoPipelineForImage2Image
203
+ from diffusers.utils import load_image
204
+
205
+ pipeline = AutoPipelineForImage2Image.from_pretrained(
206
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
207
+ ).to("cuda")
208
+ pipeline.enable_vae_tiling()
209
+
210
+ init_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-sdxl-init.png")
211
+ prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
212
+ pipeline(prompt, image=init_image, strength=0.5).images[0]
213
+ print(f"Max memory reserved: {torch.cuda.max_memory_allocated() / 1024**3:.2f} GB")
214
+ ```
215
+
216
+ > [!WARNING]
217
+ > [`AutoencoderKLWan`] and [`AsymmetricAutoencoderKL`] don't support tiling.
218
+
219
+ ## Offloading
220
+
221
+ Offloading strategies move not currently active layers or models to the CPU to avoid increasing GPU memory. These strategies can be combined with quantization and torch.compile to balance inference speed and memory usage.
222
+
223
+ Refer to the [Compile and offloading quantized models](./speed-memory-optims) guide for more details.
224
+
225
+ ### CPU offloading
226
+
227
+ CPU offloading selectively moves weights from the GPU to the CPU. When a component is required, it is transferred to the GPU and when it isn't required, it is moved to the CPU. This method works on submodules rather than whole models. It saves memory by avoiding storing the entire model on the GPU.
228
+
229
+ CPU offloading dramatically reduces memory usage, but it is also **extremely slow** because submodules are passed back and forth multiple times between devices. It can often be impractical due to how slow it is.
230
+
231
+ > [!WARNING]
232
+ > Don't move the pipeline to CUDA before calling [`~DiffusionPipeline.enable_sequential_cpu_offload`], otherwise the amount of memory saved is only minimal (refer to this [issue](https://github.com/huggingface/diffusers/issues/1934) for more details). This is a stateful operation that installs hooks on the model.
233
+
234
+ Call [`~DiffusionPipeline.enable_sequential_cpu_offload`] to enable it on a pipeline.
235
+
236
+ ```py
237
+ import torch
238
+ from diffusers import DiffusionPipeline
239
+
240
+ pipeline = DiffusionPipeline.from_pretrained(
241
+ "black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16
242
+ )
243
+ pipeline.enable_sequential_cpu_offload()
244
+
245
+ pipeline(
246
+ prompt="An astronaut riding a horse on Mars",
247
+ guidance_scale=0.,
248
+ height=768,
249
+ width=1360,
250
+ num_inference_steps=4,
251
+ max_sequence_length=256,
252
+ ).images[0]
253
+ print(f"Max memory reserved: {torch.cuda.max_memory_allocated() / 1024**3:.2f} GB")
254
+ ```
255
+
256
+ ### Model offloading
257
+
258
+ Model offloading moves entire models to the GPU instead of selectively moving *some* layers or model components. One of the main pipeline models, usually the text encoder, UNet, and VAE, is placed on the GPU while the other components are held on the CPU. Components like the UNet that run multiple times stays on the GPU until its completely finished and no longer needed. This eliminates the communication overhead of [CPU offloading](#cpu-offloading) and makes model offloading a faster alternative. The tradeoff is memory savings won't be as large.
259
+
260
+ > [!WARNING]
261
+ > Keep in mind that if models are reused outside the pipeline after hookes have been installed (see [Removing Hooks](https://huggingface.co/docs/accelerate/en/package_reference/big_modeling#accelerate.hooks.remove_hook_from_module) for more details), you need to run the entire pipeline and models in the expected order to properly offload them. This is a stateful operation that installs hooks on the model.
262
+
263
+ Call [`~DiffusionPipeline.enable_model_cpu_offload`] to enable it on a pipeline.
264
+
265
+ ```py
266
+ import torch
267
+ from diffusers import DiffusionPipeline
268
+
269
+ pipeline = DiffusionPipeline.from_pretrained(
270
+ "black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16
271
+ )
272
+ pipeline.enable_model_cpu_offload()
273
+
274
+ pipeline(
275
+ prompt="An astronaut riding a horse on Mars",
276
+ guidance_scale=0.,
277
+ height=768,
278
+ width=1360,
279
+ num_inference_steps=4,
280
+ max_sequence_length=256,
281
+ ).images[0]
282
+ print(f"Max memory reserved: {torch.cuda.max_memory_allocated() / 1024**3:.2f} GB")
283
+ ```
284
+
285
+ [`~DiffusionPipeline.enable_model_cpu_offload`] also helps when you're using the [`~StableDiffusionXLPipeline.encode_prompt`] method on its own to generate the text encoders hidden state.
286
+
287
+ ### Group offloading
288
+
289
+ Group offloading moves groups of internal layers ([torch.nn.ModuleList](https://pytorch.org/docs/stable/generated/torch.nn.ModuleList.html) or [torch.nn.Sequential](https://pytorch.org/docs/stable/generated/torch.nn.Sequential.html)) to the CPU. It uses less memory than [model offloading](#model-offloading) and it is faster than [CPU offloading](#cpu-offloading) because it reduces communication overhead.
290
+
291
+ > [!WARNING]
292
+ > 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.
293
+
294
+ Enable group offloading by configuring the `offload_type` parameter to `block_level` or `leaf_level`.
295
+
296
+ - `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.
297
+ - `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.
298
+
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
+
341
+ ```py
342
+ import torch
343
+ from diffusers import CogVideoXPipeline
344
+ from diffusers.hooks import apply_group_offloading
345
+ from diffusers.utils import export_to_video
346
+
347
+ onload_device = torch.device("cuda")
348
+ offload_device = torch.device("cpu")
349
+ pipeline = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-5b", torch_dtype=torch.bfloat16)
350
+
351
+ # Use the enable_group_offload method for Diffusers model implementations
352
+ pipeline.transformer.enable_group_offload(onload_device=onload_device, offload_device=offload_device, offload_type="leaf_level")
353
+ pipeline.vae.enable_group_offload(onload_device=onload_device, offload_type="leaf_level")
354
+
355
+ # Use the apply_group_offloading method for other model components
356
+ apply_group_offloading(pipeline.text_encoder, onload_device=onload_device, offload_type="block_level", num_blocks_per_group=2)
357
+
358
+ prompt = (
359
+ "A panda, dressed in a small, red jacket and a tiny hat, sits on a wooden stool in a serene bamboo forest. "
360
+ "The panda's fluffy paws strum a miniature acoustic guitar, producing soft, melodic tunes. Nearby, a few other "
361
+ "pandas gather, watching curiously and some clapping in rhythm. Sunlight filters through the tall bamboo, "
362
+ "casting a gentle glow on the scene. The panda's face is expressive, showing concentration and joy as it plays. "
363
+ "The background includes a small, flowing stream and vibrant green foliage, enhancing the peaceful and magical "
364
+ "atmosphere of this unique musical performance."
365
+ )
366
+ video = pipeline(prompt=prompt, guidance_scale=6, num_inference_steps=50).frames[0]
367
+ print(f"Max memory reserved: {torch.cuda.max_memory_allocated() / 1024**3:.2f} GB")
368
+ export_to_video(video, "output.mp4", fps=8)
369
+ ```
370
+
371
+ </hfoption>
372
+ </hfoptions>
373
+
374
+ #### CUDA stream
375
+
376
+ 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.
377
+
378
+ Set `record_stream=True` for more of a speedup at the cost of slightly increased memory usage. Refer to the [torch.Tensor.record_stream](https://pytorch.org/docs/stable/generated/torch.Tensor.record_stream.html) docs to learn more.
379
+
380
+ > [!TIP]
381
+ > When `use_stream=True` on VAEs with tiling enabled, make sure to do a dummy forward pass (possible with dummy inputs as well) before inference to avoid device mismatch errors. This may not work on all implementations, so feel free to open an issue if you encounter any problems.
382
+
383
+ If you're using `block_level` group offloading with `use_stream` enabled, the `num_blocks_per_group` parameter should be set to `1`, otherwise a warning will be raised.
384
+
385
+ ```py
386
+ pipeline.transformer.enable_group_offload(onload_device=onload_device, offload_device=offload_device, offload_type="leaf_level", use_stream=True, record_stream=True)
387
+ ```
388
+
389
+ The `low_cpu_mem_usage` parameter can be set to `True` to reduce CPU memory usage when using streams during group offloading. It is best for `leaf_level` offloading and when CPU memory is bottlenecked. Memory is saved by creating pinned tensors on the fly instead of pre-pinning them. However, this may increase overall execution time.
390
+
391
+ #### Offloading to disk
392
+
393
+ Group offloading can consume significant system memory depending on the model size. On systems with limited memory, try group offloading onto the disk as a secondary memory.
394
+
395
+ Set the `offload_to_disk_path` argument in either [`~ModelMixin.enable_group_offload`] or [`~hooks.apply_group_offloading`] to offload the model to the disk.
396
+
397
+ ```py
398
+ pipeline.transformer.enable_group_offload(onload_device=onload_device, offload_device=offload_device, offload_type="leaf_level", offload_to_disk_path="path/to/disk")
399
+
400
+ apply_group_offloading(pipeline.text_encoder, onload_device=onload_device, offload_type="block_level", num_blocks_per_group=2, offload_to_disk_path="path/to/disk")
401
+ ```
402
+
403
+ Refer to these [two](https://github.com/huggingface/diffusers/pull/11682#issue-3129365363) [tables](https://github.com/huggingface/diffusers/pull/11682#issuecomment-2955715126) to compare the speed and memory trade-offs.
404
+
405
+ ## Layerwise casting
406
+
407
+ > [!TIP]
408
+ > Combine layerwise casting with [group offloading](#group-offloading) for even more memory savings.
409
+
410
+ Layerwise casting stores weights in a smaller data format (for example, `torch.float8_e4m3fn` and `torch.float8_e5m2`) to use less memory and upcasts those weights to a higher precision like `torch.float16` or `torch.bfloat16` for computation. Certain layers (normalization and modulation related weights) are skipped because storing them in fp8 can degrade generation quality.
411
+
412
+ > [!WARNING]
413
+ > Layerwise casting may not work with all models if the forward implementation contains internal typecasting of weights. The current implementation of layerwise casting assumes the forward pass is independent of the weight precision and the input datatypes are always specified in `compute_dtype` (see [here](https://github.com/huggingface/transformers/blob/7f5077e53682ca855afc826162b204ebf809f1f9/src/transformers/models/t5/modeling_t5.py#L294-L299) for an incompatible implementation).
414
+ >
415
+ > Layerwise casting may also fail on custom modeling implementations with [PEFT](https://huggingface.co/docs/peft/index) layers. There are some checks available but they are not extensively tested or guaranteed to work in all cases.
416
+
417
+ Call [`~ModelMixin.enable_layerwise_casting`] to set the storage and computation datatypes.
418
+
419
+ ```py
420
+ import torch
421
+ from diffusers import CogVideoXPipeline, CogVideoXTransformer3DModel
422
+ from diffusers.utils import export_to_video
423
+
424
+ transformer = CogVideoXTransformer3DModel.from_pretrained(
425
+ "THUDM/CogVideoX-5b",
426
+ subfolder="transformer",
427
+ torch_dtype=torch.bfloat16
428
+ )
429
+ transformer.enable_layerwise_casting(storage_dtype=torch.float8_e4m3fn, compute_dtype=torch.bfloat16)
430
+
431
+ pipeline = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-5b",
432
+ transformer=transformer,
433
+ torch_dtype=torch.bfloat16
434
+ ).to("cuda")
435
+ prompt = (
436
+ "A panda, dressed in a small, red jacket and a tiny hat, sits on a wooden stool in a serene bamboo forest. "
437
+ "The panda's fluffy paws strum a miniature acoustic guitar, producing soft, melodic tunes. Nearby, a few other "
438
+ "pandas gather, watching curiously and some clapping in rhythm. Sunlight filters through the tall bamboo, "
439
+ "casting a gentle glow on the scene. The panda's face is expressive, showing concentration and joy as it plays. "
440
+ "The background includes a small, flowing stream and vibrant green foliage, enhancing the peaceful and magical "
441
+ "atmosphere of this unique musical performance."
442
+ )
443
+ video = pipeline(prompt=prompt, guidance_scale=6, num_inference_steps=50).frames[0]
444
+ print(f"Max memory reserved: {torch.cuda.max_memory_allocated() / 1024**3:.2f} GB")
445
+ export_to_video(video, "output.mp4", fps=8)
446
+ ```
447
+
448
+ The [`~hooks.apply_layerwise_casting`] method can also be used if you need more control and flexibility. It can be partially applied to model layers by calling it on specific internal modules. Use the `skip_modules_pattern` or `skip_modules_classes` parameters to specify modules to avoid, such as the normalization and modulation layers.
449
+
450
+ ```python
451
+ import torch
452
+ from diffusers import CogVideoXTransformer3DModel
453
+ from diffusers.hooks import apply_layerwise_casting
454
+
455
+ transformer = CogVideoXTransformer3DModel.from_pretrained(
456
+ "THUDM/CogVideoX-5b",
457
+ subfolder="transformer",
458
+ torch_dtype=torch.bfloat16
459
+ )
460
+
461
+ # skip the normalization layer
462
+ apply_layerwise_casting(
463
+ transformer,
464
+ storage_dtype=torch.float8_e4m3fn,
465
+ compute_dtype=torch.bfloat16,
466
+ skip_modules_classes=["norm"],
467
+ non_blocking=True,
468
+ )
469
+ ```
470
+
471
+ ## torch.channels_last
472
+
473
+ [torch.channels_last](https://pytorch.org/tutorials/intermediate/memory_format_tutorial.html) flips how tensors are stored from `(batch size, channels, height, width)` to `(batch size, heigh, width, channels)`. This aligns the tensors with how the hardware sequentially accesses the tensors stored in memory and avoids skipping around in memory to access the pixel values.
474
+
475
+ Not all operators currently support the channels-last format and may result in worst performance, but it is still worth trying.
476
+
477
+ ```py
478
+ print(pipeline.unet.conv_out.state_dict()["weight"].stride()) # (2880, 9, 3, 1)
479
+ pipeline.unet.to(memory_format=torch.channels_last) # in-place operation
480
+ print(
481
+ pipeline.unet.conv_out.state_dict()["weight"].stride()
482
+ ) # (2880, 1, 960, 320) having a stride of 1 for the 2nd dimension proves that it works
483
+ ```
484
+
485
+ ## torch.jit.trace
486
+
487
+ [torch.jit.trace](https://pytorch.org/docs/stable/generated/torch.jit.trace.html) records the operations a model performs on a sample input and creates a new, optimized representation of the model based on the recorded execution path. During tracing, the model is optimized to reduce overhead from Python and dynamic control flows and operations are fused together for more efficiency. The returned executable or [ScriptFunction](https://pytorch.org/docs/stable/generated/torch.jit.ScriptFunction.html) can be compiled.
488
+
489
+ ```py
490
+ import time
491
+ import torch
492
+ from diffusers import StableDiffusionPipeline
493
+ import functools
494
+
495
+ # torch disable grad
496
+ torch.set_grad_enabled(False)
497
+
498
+ # set variables
499
+ n_experiments = 2
500
+ unet_runs_per_experiment = 50
501
+
502
+ # load sample inputs
503
+ def generate_inputs():
504
+ sample = torch.randn((2, 4, 64, 64), device="cuda", dtype=torch.float16)
505
+ timestep = torch.rand(1, device="cuda", dtype=torch.float16) * 999
506
+ encoder_hidden_states = torch.randn((2, 77, 768), device="cuda", dtype=torch.float16)
507
+ return sample, timestep, encoder_hidden_states
508
+
509
+
510
+ pipeline = StableDiffusionPipeline.from_pretrained(
511
+ "stable-diffusion-v1-5/stable-diffusion-v1-5",
512
+ torch_dtype=torch.float16,
513
+ use_safetensors=True,
514
+ ).to("cuda")
515
+ unet = pipeline.unet
516
+ unet.eval()
517
+ unet.to(memory_format=torch.channels_last) # use channels_last memory format
518
+ unet.forward = functools.partial(unet.forward, return_dict=False) # set return_dict=False as default
519
+
520
+ # warmup
521
+ for _ in range(3):
522
+ with torch.inference_mode():
523
+ inputs = generate_inputs()
524
+ orig_output = unet(*inputs)
525
+
526
+ # trace
527
+ print("tracing..")
528
+ unet_traced = torch.jit.trace(unet, inputs)
529
+ unet_traced.eval()
530
+ print("done tracing")
531
+
532
+ # warmup and optimize graph
533
+ for _ in range(5):
534
+ with torch.inference_mode():
535
+ inputs = generate_inputs()
536
+ orig_output = unet_traced(*inputs)
537
+
538
+ # benchmarking
539
+ with torch.inference_mode():
540
+ for _ in range(n_experiments):
541
+ torch.cuda.synchronize()
542
+ start_time = time.time()
543
+ for _ in range(unet_runs_per_experiment):
544
+ orig_output = unet_traced(*inputs)
545
+ torch.cuda.synchronize()
546
+ print(f"unet traced inference took {time.time() - start_time:.2f} seconds")
547
+ for _ in range(n_experiments):
548
+ torch.cuda.synchronize()
549
+ start_time = time.time()
550
+ for _ in range(unet_runs_per_experiment):
551
+ orig_output = unet(*inputs)
552
+ torch.cuda.synchronize()
553
+ print(f"unet inference took {time.time() - start_time:.2f} seconds")
554
+
555
+ # save the model
556
+ unet_traced.save("unet_traced.pt")
557
+ ```
558
+
559
+ Replace the pipeline's UNet with the traced version.
560
+
561
+ ```py
562
+ import torch
563
+ from diffusers import StableDiffusionPipeline
564
+ from dataclasses import dataclass
565
+
566
+ @dataclass
567
+ class UNet2DConditionOutput:
568
+ sample: torch.Tensor
569
+
570
+ pipeline = StableDiffusionPipeline.from_pretrained(
571
+ "stable-diffusion-v1-5/stable-diffusion-v1-5",
572
+ torch_dtype=torch.float16,
573
+ use_safetensors=True,
574
+ ).to("cuda")
575
+
576
+ # use jitted unet
577
+ unet_traced = torch.jit.load("unet_traced.pt")
578
+
579
+ # del pipeline.unet
580
+ class TracedUNet(torch.nn.Module):
581
+ def __init__(self):
582
+ super().__init__()
583
+ self.in_channels = pipe.unet.config.in_channels
584
+ self.device = pipe.unet.device
585
+
586
+ def forward(self, latent_model_input, t, encoder_hidden_states):
587
+ sample = unet_traced(latent_model_input, t, encoder_hidden_states)[0]
588
+ return UNet2DConditionOutput(sample=sample)
589
+
590
+ pipeline.unet = TracedUNet()
591
+
592
+ with torch.inference_mode():
593
+ image = pipe([prompt] * 1, num_inference_steps=50).images[0]
594
+ ```
595
+
596
+ ## Memory-efficient attention
597
+
598
+ > [!TIP]
599
+ > Memory-efficient attention optimizes for memory usage *and* [inference speed](./fp16#scaled-dot-product-attention)!
600
+
601
+ The Transformers attention mechanism is memory-intensive, especially for long sequences, so you can try using different and more memory-efficient attention types.
602
+
603
+ By default, if PyTorch >= 2.0 is installed, [scaled dot-product attention (SDPA)](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html) is used. You don't need to make any additional changes to your code.
604
+
605
+ SDPA supports [FlashAttention](https://github.com/Dao-AILab/flash-attention) and [xFormers](https://github.com/facebookresearch/xformers) as well as a native C++ PyTorch implementation. It automatically selects the most optimal implementation based on your input.
606
+
607
+ You can explicitly use xFormers with the [`~ModelMixin.enable_xformers_memory_efficient_attention`] method.
608
+
609
+ ```py
610
+ # pip install xformers
611
+ import torch
612
+ from diffusers import StableDiffusionXLPipeline
613
+
614
+ pipeline = StableDiffusionXLPipeline.from_pretrained(
615
+ "stabilityai/stable-diffusion-xl-base-1.0",
616
+ torch_dtype=torch.float16,
617
+ ).to("cuda")
618
+ pipeline.enable_xformers_memory_efficient_attention()
619
+ ```
620
+
621
+ Call [`~ModelMixin.disable_xformers_memory_efficient_attention`] to disable it.
622
+
623
+ ```py
624
+ pipeline.disable_xformers_memory_efficient_attention()
625
+ ```
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/mps.md ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Metal Performance Shaders (MPS)
14
+
15
+ > [!TIP]
16
+ > Pipelines with a <img alt="MPS" src="https://img.shields.io/badge/MPS-000000?style=flat&logo=apple&logoColor=white%22"> badge indicate a model can take advantage of the MPS backend on Apple silicon devices for faster inference. Feel free to open a [Pull Request](https://github.com/huggingface/diffusers/compare) to add this badge to pipelines that are missing it.
17
+
18
+ 🤗 Diffusers is compatible with Apple silicon (M1/M2 chips) using the PyTorch [`mps`](https://pytorch.org/docs/stable/notes/mps.html) device, which uses the Metal framework to leverage the GPU on MacOS devices. You'll need to have:
19
+
20
+ - macOS computer with Apple silicon (M1/M2) hardware
21
+ - macOS 12.6 or later (13.0 or later recommended)
22
+ - arm64 version of Python
23
+ - [PyTorch 2.0](https://pytorch.org/get-started/locally/) (recommended) or 1.13 (minimum version supported for `mps`)
24
+
25
+ The `mps` backend uses PyTorch's `.to()` interface to move the Stable Diffusion pipeline on to your M1 or M2 device:
26
+
27
+ ```python
28
+ from diffusers import DiffusionPipeline
29
+
30
+ pipe = DiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5")
31
+ pipe = pipe.to("mps")
32
+
33
+ # Recommended if your computer has < 64 GB of RAM
34
+ pipe.enable_attention_slicing()
35
+
36
+ prompt = "a photo of an astronaut riding a horse on mars"
37
+ image = pipe(prompt).images[0]
38
+ image
39
+ ```
40
+
41
+ > [!WARNING]
42
+ > The PyTorch [mps](https://pytorch.org/docs/stable/notes/mps.html) backend does not support NDArray sizes greater than `2**32`. Please open an [Issue](https://github.com/huggingface/diffusers/issues/new/choose) if you encounter this problem so we can investigate.
43
+
44
+ If you're using **PyTorch 1.13**, you need to "prime" the pipeline with an additional one-time pass through it. This is a temporary workaround for an issue where the first inference pass produces slightly different results than subsequent ones. You only need to do this pass once, and after just one inference step you can discard the result.
45
+
46
+ ```diff
47
+ from diffusers import DiffusionPipeline
48
+
49
+ pipe = DiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5").to("mps")
50
+ pipe.enable_attention_slicing()
51
+
52
+ prompt = "a photo of an astronaut riding a horse on mars"
53
+ # First-time "warmup" pass if PyTorch version is 1.13
54
+ + _ = pipe(prompt, num_inference_steps=1)
55
+
56
+ # Results match those from the CPU device after the warmup pass.
57
+ image = pipe(prompt).images[0]
58
+ ```
59
+
60
+ ## Troubleshoot
61
+
62
+ This section lists some common issues with using the `mps` backend and how to solve them.
63
+
64
+ ### Attention slicing
65
+
66
+ M1/M2 performance is very sensitive to memory pressure. When this occurs, the system automatically swaps if it needs to which significantly degrades performance.
67
+
68
+ To prevent this from happening, we recommend *attention slicing* to reduce memory pressure during inference and prevent swapping. This is especially relevant if your computer has less than 64GB of system RAM, or if you generate images at non-standard resolutions larger than 512×512 pixels. Call the [`~DiffusionPipeline.enable_attention_slicing`] function on your pipeline:
69
+
70
+ ```py
71
+ from diffusers import DiffusionPipeline
72
+ import torch
73
+
74
+ pipeline = DiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16, variant="fp16", use_safetensors=True).to("mps")
75
+ pipeline.enable_attention_slicing()
76
+ ```
77
+
78
+ Attention slicing performs the costly attention operation in multiple steps instead of all at once. It usually improves performance by ~20% in computers without universal memory, but we've observed *better performance* in most Apple silicon computers unless you have 64GB of RAM or more.
79
+
80
+ ### Batch inference
81
+
82
+ Generating multiple prompts in a batch can crash or fail to work reliably. If this is the case, try iterating instead of batching.
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/neuron.md ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # AWS Neuron
14
+
15
+ Diffusers functionalities are available on [AWS Inf2 instances](https://aws.amazon.com/ec2/instance-types/inf2/), which are EC2 instances powered by [Neuron machine learning accelerators](https://aws.amazon.com/machine-learning/inferentia/). These instances aim to provide better compute performance (higher throughput, lower latency) with good cost-efficiency, making them good candidates for AWS users to deploy diffusion models to production.
16
+
17
+ [Optimum Neuron](https://huggingface.co/docs/optimum-neuron/en/index) is the interface between Hugging Face libraries and AWS Accelerators, including AWS [Trainium](https://aws.amazon.com/machine-learning/trainium/) and AWS [Inferentia](https://aws.amazon.com/machine-learning/inferentia/). It supports many of the features in Diffusers with similar APIs, so it is easier to learn if you're already familiar with Diffusers. Once you have created an AWS Inf2 instance, install Optimum Neuron.
18
+
19
+ ```bash
20
+ python -m pip install --upgrade-strategy eager optimum[neuronx]
21
+ ```
22
+
23
+ > [!TIP]
24
+ > We provide pre-built [Hugging Face Neuron Deep Learning AMI](https://aws.amazon.com/marketplace/pp/prodview-gr3e6yiscria2) (DLAMI) and Optimum Neuron containers for Amazon SageMaker. It's recommended to correctly set up your environment.
25
+
26
+ The example below demonstrates how to generate images with the Stable Diffusion XL model on an inf2.8xlarge instance (you can switch to cheaper inf2.xlarge instances once the model is compiled). To generate some images, use the [`~optimum.neuron.NeuronStableDiffusionXLPipeline`] class, which is similar to the [`StableDiffusionXLPipeline`] class in Diffusers.
27
+
28
+ Unlike Diffusers, you need to compile models in the pipeline to the Neuron format, `.neuron`. Launch the following command to export the model to the `.neuron` format.
29
+
30
+ ```bash
31
+ optimum-cli export neuron --model stabilityai/stable-diffusion-xl-base-1.0 \
32
+ --batch_size 1 \
33
+ --height 1024 `# height in pixels of generated image, eg. 768, 1024` \
34
+ --width 1024 `# width in pixels of generated image, eg. 768, 1024` \
35
+ --num_images_per_prompt 1 `# number of images to generate per prompt, defaults to 1` \
36
+ --auto_cast matmul `# cast only matrix multiplication operations` \
37
+ --auto_cast_type bf16 `# cast operations from FP32 to BF16` \
38
+ sd_neuron_xl/
39
+ ```
40
+
41
+ Now generate some images with the pre-compiled SDXL model.
42
+
43
+ ```python
44
+ >>> from optimum.neuron import NeuronStableDiffusionXLPipeline
45
+
46
+ >>> stable_diffusion_xl = NeuronStableDiffusionXLPipeline.from_pretrained("sd_neuron_xl/")
47
+ >>> prompt = "a pig with wings flying in floating US dollar banknotes in the air, skyscrapers behind, warm color palette, muted colors, detailed, 8k"
48
+ >>> image = stable_diffusion_xl(prompt).images[0]
49
+ ```
50
+
51
+ <img
52
+ src="https://huggingface.co/datasets/Jingya/document_images/resolve/main/optimum/neuron/sdxl_pig.png"
53
+ width="256"
54
+ height="256"
55
+ alt="peggy generated by sdxl on inf2"
56
+ />
57
+
58
+ Feel free to check out more guides and examples on different use cases from the Optimum Neuron [documentation](https://huggingface.co/docs/optimum-neuron/en/inference_tutorials/stable_diffusion#generate-images-with-stable-diffusion-models-on-aws-inferentia)!
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/onnx.md ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # ONNX Runtime
14
+
15
+ 🤗 [Optimum](https://github.com/huggingface/optimum) provides a Stable Diffusion pipeline compatible with ONNX Runtime. You'll need to install 🤗 Optimum with the following command for ONNX Runtime support:
16
+
17
+ ```bash
18
+ pip install -q optimum["onnxruntime"]
19
+ ```
20
+
21
+ This guide will show you how to use the Stable Diffusion and Stable Diffusion XL (SDXL) pipelines with ONNX Runtime.
22
+
23
+ ## Stable Diffusion
24
+
25
+ To load and run inference, use the [`~optimum.onnxruntime.ORTStableDiffusionPipeline`]. If you want to load a PyTorch model and convert it to the ONNX format on-the-fly, set `export=True`:
26
+
27
+ ```python
28
+ from optimum.onnxruntime import ORTStableDiffusionPipeline
29
+
30
+ model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
31
+ pipeline = ORTStableDiffusionPipeline.from_pretrained(model_id, export=True)
32
+ prompt = "sailing ship in storm by Leonardo da Vinci"
33
+ image = pipeline(prompt).images[0]
34
+ pipeline.save_pretrained("./onnx-stable-diffusion-v1-5")
35
+ ```
36
+
37
+ > [!WARNING]
38
+ > Generating multiple prompts in a batch seems to take too much memory. While we look into it, you may need to iterate instead of batching.
39
+
40
+ To export the pipeline in the ONNX format offline and use it later for inference,
41
+ use the [`optimum-cli export`](https://huggingface.co/docs/optimum/main/en/exporters/onnx/usage_guides/export_a_model#exporting-a-model-to-onnx-using-the-cli) command:
42
+
43
+ ```bash
44
+ optimum-cli export onnx --model stable-diffusion-v1-5/stable-diffusion-v1-5 sd_v15_onnx/
45
+ ```
46
+
47
+ Then to perform inference (you don't have to specify `export=True` again):
48
+
49
+ ```python
50
+ from optimum.onnxruntime import ORTStableDiffusionPipeline
51
+
52
+ model_id = "sd_v15_onnx"
53
+ pipeline = ORTStableDiffusionPipeline.from_pretrained(model_id)
54
+ prompt = "sailing ship in storm by Leonardo da Vinci"
55
+ image = pipeline(prompt).images[0]
56
+ ```
57
+
58
+ <div class="flex justify-center">
59
+ <img src="https://huggingface.co/datasets/optimum/documentation-images/resolve/main/onnxruntime/stable_diffusion_v1_5_ort_sail_boat.png">
60
+ </div>
61
+
62
+ You can find more examples in 🤗 Optimum [documentation](https://huggingface.co/docs/optimum/), and Stable Diffusion is supported for text-to-image, image-to-image, and inpainting.
63
+
64
+ ## Stable Diffusion XL
65
+
66
+ To load and run inference with SDXL, use the [`~optimum.onnxruntime.ORTStableDiffusionXLPipeline`]:
67
+
68
+ ```python
69
+ from optimum.onnxruntime import ORTStableDiffusionXLPipeline
70
+
71
+ model_id = "stabilityai/stable-diffusion-xl-base-1.0"
72
+ pipeline = ORTStableDiffusionXLPipeline.from_pretrained(model_id)
73
+ prompt = "sailing ship in storm by Leonardo da Vinci"
74
+ image = pipeline(prompt).images[0]
75
+ ```
76
+
77
+ To export the pipeline in the ONNX format and use it later for inference, use the [`optimum-cli export`](https://huggingface.co/docs/optimum/main/en/exporters/onnx/usage_guides/export_a_model#exporting-a-model-to-onnx-using-the-cli) command:
78
+
79
+ ```bash
80
+ optimum-cli export onnx --model stabilityai/stable-diffusion-xl-base-1.0 --task stable-diffusion-xl sd_xl_onnx/
81
+ ```
82
+
83
+ SDXL in the ONNX format is supported for text-to-image and image-to-image.
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/open_vino.md ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # OpenVINO
14
+
15
+ 🤗 [Optimum](https://github.com/huggingface/optimum-intel) provides Stable Diffusion pipelines compatible with OpenVINO to perform inference on a variety of Intel processors (see the [full list](https://docs.openvino.ai/latest/openvino_docs_OV_UG_supported_plugins_Supported_Devices.html) of supported devices).
16
+
17
+ You'll need to install 🤗 Optimum Intel with the `--upgrade-strategy eager` option to ensure [`optimum-intel`](https://github.com/huggingface/optimum-intel) is using the latest version:
18
+
19
+ ```bash
20
+ pip install --upgrade-strategy eager optimum["openvino"]
21
+ ```
22
+
23
+ This guide will show you how to use the Stable Diffusion and Stable Diffusion XL (SDXL) pipelines with OpenVINO.
24
+
25
+ ## Stable Diffusion
26
+
27
+ To load and run inference, use the [`~optimum.intel.OVStableDiffusionPipeline`]. If you want to load a PyTorch model and convert it to the OpenVINO format on-the-fly, set `export=True`:
28
+
29
+ ```python
30
+ from optimum.intel import OVStableDiffusionPipeline
31
+
32
+ model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
33
+ pipeline = OVStableDiffusionPipeline.from_pretrained(model_id, export=True)
34
+ prompt = "sailing ship in storm by Rembrandt"
35
+ image = pipeline(prompt).images[0]
36
+
37
+ # Don't forget to save the exported model
38
+ pipeline.save_pretrained("openvino-sd-v1-5")
39
+ ```
40
+
41
+ To further speed-up inference, statically reshape the model. If you change any parameters such as the outputs height or width, you’ll need to statically reshape your model again.
42
+
43
+ ```python
44
+ # Define the shapes related to the inputs and desired outputs
45
+ batch_size, num_images, height, width = 1, 1, 512, 512
46
+
47
+ # Statically reshape the model
48
+ pipeline.reshape(batch_size, height, width, num_images)
49
+ # Compile the model before inference
50
+ pipeline.compile()
51
+
52
+ image = pipeline(
53
+ prompt,
54
+ height=height,
55
+ width=width,
56
+ num_images_per_prompt=num_images,
57
+ ).images[0]
58
+ ```
59
+ <div class="flex justify-center">
60
+ <img src="https://huggingface.co/datasets/optimum/documentation-images/resolve/main/intel/openvino/stable_diffusion_v1_5_sail_boat_rembrandt.png">
61
+ </div>
62
+
63
+ You can find more examples in the 🤗 Optimum [documentation](https://huggingface.co/docs/optimum/intel/inference#stable-diffusion), and Stable Diffusion is supported for text-to-image, image-to-image, and inpainting.
64
+
65
+ ## Stable Diffusion XL
66
+
67
+ To load and run inference with SDXL, use the [`~optimum.intel.OVStableDiffusionXLPipeline`]:
68
+
69
+ ```python
70
+ from optimum.intel import OVStableDiffusionXLPipeline
71
+
72
+ model_id = "stabilityai/stable-diffusion-xl-base-1.0"
73
+ pipeline = OVStableDiffusionXLPipeline.from_pretrained(model_id)
74
+ prompt = "sailing ship in storm by Rembrandt"
75
+ image = pipeline(prompt).images[0]
76
+ ```
77
+
78
+ To further speed-up inference, [statically reshape](#stable-diffusion) the model as shown in the Stable Diffusion section.
79
+
80
+ You can find more examples in the 🤗 Optimum [documentation](https://huggingface.co/docs/optimum/intel/inference#stable-diffusion-xl), and running SDXL in OpenVINO is supported for text-to-image and image-to-image.
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/para_attn.md ADDED
@@ -0,0 +1,497 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ParaAttention
2
+
3
+ <div class="flex justify-center">
4
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/para-attn/flux-performance.png">
5
+ </div>
6
+ <div class="flex justify-center">
7
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/para-attn/hunyuan-video-performance.png">
8
+ </div>
9
+
10
+
11
+ Large image and video generation models, such as [FLUX.1-dev](https://huggingface.co/black-forest-labs/FLUX.1-dev) and [HunyuanVideo](https://huggingface.co/tencent/HunyuanVideo), can be an inference challenge for real-time applications and deployment because of their size.
12
+
13
+ [ParaAttention](https://github.com/chengzeyi/ParaAttention) is a library that implements **context parallelism** and **first block cache**, and can be combined with other techniques (torch.compile, fp8 dynamic quantization), to accelerate inference.
14
+
15
+ This guide will show you how to apply ParaAttention to FLUX.1-dev and HunyuanVideo on NVIDIA L20 GPUs.
16
+ No optimizations are applied for our baseline benchmark, except for HunyuanVideo to avoid out-of-memory errors.
17
+
18
+ Our baseline benchmark shows that FLUX.1-dev is able to generate a 1024x1024 resolution image in 28 steps in 26.36 seconds, and HunyuanVideo is able to generate 129 frames at 720p resolution in 30 steps in 3675.71 seconds.
19
+
20
+ > [!TIP]
21
+ > For even faster inference with context parallelism, try using NVIDIA A100 or H100 GPUs (if available) with NVLink support, especially when there is a large number of GPUs.
22
+
23
+ ## First Block Cache
24
+
25
+ Caching the output of the transformers blocks in the model and reusing them in the next inference steps reduces the computation cost and makes inference faster.
26
+
27
+ However, it is hard to decide when to reuse the cache to ensure quality generated images or videos. ParaAttention directly uses the **residual difference of the first transformer block output** to approximate the difference among model outputs. When the difference is small enough, the residual difference of previous inference steps is reused. In other words, the denoising step is skipped.
28
+
29
+ This achieves a 2x speedup on FLUX.1-dev and HunyuanVideo inference with very good quality.
30
+
31
+ <figure>
32
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/para-attn/ada-cache.png" alt="Cache in Diffusion Transformer" />
33
+ <figcaption>How AdaCache works, First Block Cache is a variant of it</figcaption>
34
+ </figure>
35
+
36
+ <hfoptions id="first-block-cache">
37
+ <hfoption id="FLUX-1.dev">
38
+
39
+ To apply first block cache on FLUX.1-dev, call `apply_cache_on_pipe` as shown below. 0.08 is the default residual difference value for FLUX models.
40
+
41
+ ```python
42
+ import time
43
+ import torch
44
+ from diffusers import FluxPipeline
45
+
46
+ pipe = FluxPipeline.from_pretrained(
47
+ "black-forest-labs/FLUX.1-dev",
48
+ torch_dtype=torch.bfloat16,
49
+ ).to("cuda")
50
+
51
+ from para_attn.first_block_cache.diffusers_adapters import apply_cache_on_pipe
52
+
53
+ apply_cache_on_pipe(pipe, residual_diff_threshold=0.08)
54
+
55
+ # Enable memory savings
56
+ # pipe.enable_model_cpu_offload()
57
+ # pipe.enable_sequential_cpu_offload()
58
+
59
+ begin = time.time()
60
+ image = pipe(
61
+ "A cat holding a sign that says hello world",
62
+ num_inference_steps=28,
63
+ ).images[0]
64
+ end = time.time()
65
+ print(f"Time: {end - begin:.2f}s")
66
+
67
+ print("Saving image to flux.png")
68
+ image.save("flux.png")
69
+ ```
70
+
71
+ | Optimizations | Original | FBCache rdt=0.06 | FBCache rdt=0.08 | FBCache rdt=0.10 | FBCache rdt=0.12 |
72
+ | - | - | - | - | - | - |
73
+ | Preview | ![Original](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/para-attn/flux-original.png) | ![FBCache rdt=0.06](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/para-attn/flux-fbc-0.06.png) | ![FBCache rdt=0.08](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/para-attn/flux-fbc-0.08.png) | ![FBCache rdt=0.10](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/para-attn/flux-fbc-0.10.png) | ![FBCache rdt=0.12](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/para-attn/flux-fbc-0.12.png) |
74
+ | Wall Time (s) | 26.36 | 21.83 | 17.01 | 16.00 | 13.78 |
75
+
76
+ First Block Cache reduced the inference speed to 17.01 seconds compared to the baseline, or 1.55x faster, while maintaining nearly zero quality loss.
77
+
78
+ </hfoption>
79
+ <hfoption id="HunyuanVideo">
80
+
81
+ To apply First Block Cache on HunyuanVideo, `apply_cache_on_pipe` as shown below. 0.06 is the default residual difference value for HunyuanVideo models.
82
+
83
+ ```python
84
+ import time
85
+ import torch
86
+ from diffusers import HunyuanVideoPipeline, HunyuanVideoTransformer3DModel
87
+ from diffusers.utils import export_to_video
88
+
89
+ model_id = "tencent/HunyuanVideo"
90
+ transformer = HunyuanVideoTransformer3DModel.from_pretrained(
91
+ model_id,
92
+ subfolder="transformer",
93
+ torch_dtype=torch.bfloat16,
94
+ revision="refs/pr/18",
95
+ )
96
+ pipe = HunyuanVideoPipeline.from_pretrained(
97
+ model_id,
98
+ transformer=transformer,
99
+ torch_dtype=torch.float16,
100
+ revision="refs/pr/18",
101
+ ).to("cuda")
102
+
103
+ from para_attn.first_block_cache.diffusers_adapters import apply_cache_on_pipe
104
+
105
+ apply_cache_on_pipe(pipe, residual_diff_threshold=0.6)
106
+
107
+ pipe.vae.enable_tiling()
108
+
109
+ begin = time.time()
110
+ output = pipe(
111
+ prompt="A cat walks on the grass, realistic",
112
+ height=720,
113
+ width=1280,
114
+ num_frames=129,
115
+ num_inference_steps=30,
116
+ ).frames[0]
117
+ end = time.time()
118
+ print(f"Time: {end - begin:.2f}s")
119
+
120
+ print("Saving video to hunyuan_video.mp4")
121
+ export_to_video(output, "hunyuan_video.mp4", fps=15)
122
+ ```
123
+
124
+ <video controls>
125
+ <source src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/para-attn/hunyuan-video-original.mp4" type="video/mp4">
126
+ Your browser does not support the video tag.
127
+ </video>
128
+
129
+ <small> HunyuanVideo without FBCache </small>
130
+
131
+ <video controls>
132
+ <source src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/para-attn/hunyuan-video-fbc.mp4" type="video/mp4">
133
+ Your browser does not support the video tag.
134
+ </video>
135
+
136
+ <small> HunyuanVideo with FBCache </small>
137
+
138
+ First Block Cache reduced the inference speed to 2271.06 seconds compared to the baseline, or 1.62x faster, while maintaining nearly zero quality loss.
139
+
140
+ </hfoption>
141
+ </hfoptions>
142
+
143
+ ## fp8 quantization
144
+
145
+ fp8 with dynamic quantization further speeds up inference and reduces memory usage. Both the activations and weights must be quantized in order to use the 8-bit [NVIDIA Tensor Cores](https://www.nvidia.com/en-us/data-center/tensor-cores/).
146
+
147
+ Use `float8_weight_only` and `float8_dynamic_activation_float8_weight` to quantize the text encoder and transformer model.
148
+
149
+ The default quantization method is per tensor quantization, but if your GPU supports row-wise quantization, you can also try it for better accuracy.
150
+
151
+ Install [torchao](https://github.com/pytorch/ao/tree/main) with the command below.
152
+
153
+ ```bash
154
+ pip3 install -U torch torchao
155
+ ```
156
+
157
+ [torch.compile](https://pytorch.org/tutorials/intermediate/torch_compile_tutorial.html) with `mode="max-autotune-no-cudagraphs"` or `mode="max-autotune"` selects the best kernel for performance. Compilation can take a long time if it's the first time the model is called, but it is worth it once the model has been compiled.
158
+
159
+ This example only quantizes the transformer model, but you can also quantize the text encoder to reduce memory usage even more.
160
+
161
+ > [!TIP]
162
+ > Dynamic quantization can significantly change the distribution of the model output, so you need to change the `residual_diff_threshold` to a larger value for it to take effect.
163
+
164
+ <hfoptions id="fp8-quantization">
165
+ <hfoption id="FLUX-1.dev">
166
+
167
+ ```python
168
+ import time
169
+ import torch
170
+ from diffusers import FluxPipeline
171
+
172
+ pipe = FluxPipeline.from_pretrained(
173
+ "black-forest-labs/FLUX.1-dev",
174
+ torch_dtype=torch.bfloat16,
175
+ ).to("cuda")
176
+
177
+ from para_attn.first_block_cache.diffusers_adapters import apply_cache_on_pipe
178
+
179
+ apply_cache_on_pipe(
180
+ pipe,
181
+ residual_diff_threshold=0.12, # Use a larger value to make the cache take effect
182
+ )
183
+
184
+ from torchao.quantization import quantize_, float8_dynamic_activation_float8_weight, float8_weight_only
185
+
186
+ quantize_(pipe.text_encoder, float8_weight_only())
187
+ quantize_(pipe.transformer, float8_dynamic_activation_float8_weight())
188
+ pipe.transformer = torch.compile(
189
+ pipe.transformer, mode="max-autotune-no-cudagraphs",
190
+ )
191
+
192
+ # Enable memory savings
193
+ # pipe.enable_model_cpu_offload()
194
+ # pipe.enable_sequential_cpu_offload()
195
+
196
+ for i in range(2):
197
+ begin = time.time()
198
+ image = pipe(
199
+ "A cat holding a sign that says hello world",
200
+ num_inference_steps=28,
201
+ ).images[0]
202
+ end = time.time()
203
+ if i == 0:
204
+ print(f"Warm up time: {end - begin:.2f}s")
205
+ else:
206
+ print(f"Time: {end - begin:.2f}s")
207
+
208
+ print("Saving image to flux.png")
209
+ image.save("flux.png")
210
+ ```
211
+
212
+ fp8 dynamic quantization and torch.compile reduced the inference speed to 7.56 seconds compared to the baseline, or 3.48x faster.
213
+
214
+ </hfoption>
215
+ <hfoption id="HunyuanVideo">
216
+
217
+ ```python
218
+ import time
219
+ import torch
220
+ from diffusers import HunyuanVideoPipeline, HunyuanVideoTransformer3DModel
221
+ from diffusers.utils import export_to_video
222
+
223
+ model_id = "tencent/HunyuanVideo"
224
+ transformer = HunyuanVideoTransformer3DModel.from_pretrained(
225
+ model_id,
226
+ subfolder="transformer",
227
+ torch_dtype=torch.bfloat16,
228
+ revision="refs/pr/18",
229
+ )
230
+ pipe = HunyuanVideoPipeline.from_pretrained(
231
+ model_id,
232
+ transformer=transformer,
233
+ torch_dtype=torch.float16,
234
+ revision="refs/pr/18",
235
+ ).to("cuda")
236
+
237
+ from para_attn.first_block_cache.diffusers_adapters import apply_cache_on_pipe
238
+
239
+ apply_cache_on_pipe(pipe)
240
+
241
+ from torchao.quantization import quantize_, float8_dynamic_activation_float8_weight, float8_weight_only
242
+
243
+ quantize_(pipe.text_encoder, float8_weight_only())
244
+ quantize_(pipe.transformer, float8_dynamic_activation_float8_weight())
245
+ pipe.transformer = torch.compile(
246
+ pipe.transformer, mode="max-autotune-no-cudagraphs",
247
+ )
248
+
249
+ # Enable memory savings
250
+ pipe.vae.enable_tiling()
251
+ # pipe.enable_model_cpu_offload()
252
+ # pipe.enable_sequential_cpu_offload()
253
+
254
+ for i in range(2):
255
+ begin = time.time()
256
+ output = pipe(
257
+ prompt="A cat walks on the grass, realistic",
258
+ height=720,
259
+ width=1280,
260
+ num_frames=129,
261
+ num_inference_steps=1 if i == 0 else 30,
262
+ ).frames[0]
263
+ end = time.time()
264
+ if i == 0:
265
+ print(f"Warm up time: {end - begin:.2f}s")
266
+ else:
267
+ print(f"Time: {end - begin:.2f}s")
268
+
269
+ print("Saving video to hunyuan_video.mp4")
270
+ export_to_video(output, "hunyuan_video.mp4", fps=15)
271
+ ```
272
+
273
+ A NVIDIA L20 GPU only has 48GB memory and could face out-of-memory (OOM) errors after compilation and if `enable_model_cpu_offload` isn't called because HunyuanVideo has very large activation tensors when running with high resolution and large number of frames. For GPUs with less than 80GB of memory, you can try reducing the resolution and number of frames to avoid OOM errors.
274
+
275
+ Large video generation models are usually bottlenecked by the attention computations rather than the fully connected layers. These models don't significantly benefit from quantization and torch.compile.
276
+
277
+ </hfoption>
278
+ </hfoptions>
279
+
280
+ ## Context Parallelism
281
+
282
+ Context Parallelism parallelizes inference and scales with multiple GPUs. The ParaAttention compositional design allows you to combine Context Parallelism with First Block Cache and dynamic quantization.
283
+
284
+ > [!TIP]
285
+ > Refer to the [ParaAttention](https://github.com/chengzeyi/ParaAttention/tree/main) repository for detailed instructions and examples of how to scale inference with multiple GPUs.
286
+
287
+ If the inference process needs to be persistent and serviceable, it is suggested to use [torch.multiprocessing](https://pytorch.org/docs/stable/multiprocessing.html) to write your own inference processor. This can eliminate the overhead of launching the process and loading and recompiling the model.
288
+
289
+ <hfoptions id="context-parallelism">
290
+ <hfoption id="FLUX-1.dev">
291
+
292
+ The code sample below combines First Block Cache, fp8 dynamic quantization, torch.compile, and Context Parallelism for the fastest inference speed.
293
+
294
+ ```python
295
+ import time
296
+ import torch
297
+ import torch.distributed as dist
298
+ from diffusers import FluxPipeline
299
+
300
+ dist.init_process_group()
301
+
302
+ torch.cuda.set_device(dist.get_rank())
303
+
304
+ pipe = FluxPipeline.from_pretrained(
305
+ "black-forest-labs/FLUX.1-dev",
306
+ torch_dtype=torch.bfloat16,
307
+ ).to("cuda")
308
+
309
+ from para_attn.context_parallel import init_context_parallel_mesh
310
+ from para_attn.context_parallel.diffusers_adapters import parallelize_pipe
311
+ from para_attn.parallel_vae.diffusers_adapters import parallelize_vae
312
+
313
+ mesh = init_context_parallel_mesh(
314
+ pipe.device.type,
315
+ max_ring_dim_size=2,
316
+ )
317
+ parallelize_pipe(
318
+ pipe,
319
+ mesh=mesh,
320
+ )
321
+ parallelize_vae(pipe.vae, mesh=mesh._flatten())
322
+
323
+ from para_attn.first_block_cache.diffusers_adapters import apply_cache_on_pipe
324
+
325
+ apply_cache_on_pipe(
326
+ pipe,
327
+ residual_diff_threshold=0.12, # Use a larger value to make the cache take effect
328
+ )
329
+
330
+ from torchao.quantization import quantize_, float8_dynamic_activation_float8_weight, float8_weight_only
331
+
332
+ quantize_(pipe.text_encoder, float8_weight_only())
333
+ quantize_(pipe.transformer, float8_dynamic_activation_float8_weight())
334
+ torch._inductor.config.reorder_for_compute_comm_overlap = True
335
+ pipe.transformer = torch.compile(
336
+ pipe.transformer, mode="max-autotune-no-cudagraphs",
337
+ )
338
+
339
+ # Enable memory savings
340
+ # pipe.enable_model_cpu_offload(gpu_id=dist.get_rank())
341
+ # pipe.enable_sequential_cpu_offload(gpu_id=dist.get_rank())
342
+
343
+ for i in range(2):
344
+ begin = time.time()
345
+ image = pipe(
346
+ "A cat holding a sign that says hello world",
347
+ num_inference_steps=28,
348
+ output_type="pil" if dist.get_rank() == 0 else "pt",
349
+ ).images[0]
350
+ end = time.time()
351
+ if dist.get_rank() == 0:
352
+ if i == 0:
353
+ print(f"Warm up time: {end - begin:.2f}s")
354
+ else:
355
+ print(f"Time: {end - begin:.2f}s")
356
+
357
+ if dist.get_rank() == 0:
358
+ print("Saving image to flux.png")
359
+ image.save("flux.png")
360
+
361
+ dist.destroy_process_group()
362
+ ```
363
+
364
+ Save to `run_flux.py` and launch it with [torchrun](https://pytorch.org/docs/stable/elastic/run.html).
365
+
366
+ ```bash
367
+ # Use --nproc_per_node to specify the number of GPUs
368
+ torchrun --nproc_per_node=2 run_flux.py
369
+ ```
370
+
371
+ Inference speed is reduced to 8.20 seconds compared to the baseline, or 3.21x faster, with 2 NVIDIA L20 GPUs. On 4 L20s, inference speed is 3.90 seconds, or 6.75x faster.
372
+
373
+ </hfoption>
374
+ <hfoption id="HunyuanVideo">
375
+
376
+ The code sample below combines First Block Cache and Context Parallelism for the fastest inference speed.
377
+
378
+ ```python
379
+ import time
380
+ import torch
381
+ import torch.distributed as dist
382
+ from diffusers import HunyuanVideoPipeline, HunyuanVideoTransformer3DModel
383
+ from diffusers.utils import export_to_video
384
+
385
+ dist.init_process_group()
386
+
387
+ torch.cuda.set_device(dist.get_rank())
388
+
389
+ model_id = "tencent/HunyuanVideo"
390
+ transformer = HunyuanVideoTransformer3DModel.from_pretrained(
391
+ model_id,
392
+ subfolder="transformer",
393
+ torch_dtype=torch.bfloat16,
394
+ revision="refs/pr/18",
395
+ )
396
+ pipe = HunyuanVideoPipeline.from_pretrained(
397
+ model_id,
398
+ transformer=transformer,
399
+ torch_dtype=torch.float16,
400
+ revision="refs/pr/18",
401
+ ).to("cuda")
402
+
403
+ from para_attn.context_parallel import init_context_parallel_mesh
404
+ from para_attn.context_parallel.diffusers_adapters import parallelize_pipe
405
+ from para_attn.parallel_vae.diffusers_adapters import parallelize_vae
406
+
407
+ mesh = init_context_parallel_mesh(
408
+ pipe.device.type,
409
+ )
410
+ parallelize_pipe(
411
+ pipe,
412
+ mesh=mesh,
413
+ )
414
+ parallelize_vae(pipe.vae, mesh=mesh._flatten())
415
+
416
+ from para_attn.first_block_cache.diffusers_adapters import apply_cache_on_pipe
417
+
418
+ apply_cache_on_pipe(pipe)
419
+
420
+ # from torchao.quantization import quantize_, float8_dynamic_activation_float8_weight, float8_weight_only
421
+ #
422
+ # torch._inductor.config.reorder_for_compute_comm_overlap = True
423
+ #
424
+ # quantize_(pipe.text_encoder, float8_weight_only())
425
+ # quantize_(pipe.transformer, float8_dynamic_activation_float8_weight())
426
+ # pipe.transformer = torch.compile(
427
+ # pipe.transformer, mode="max-autotune-no-cudagraphs",
428
+ # )
429
+
430
+ # Enable memory savings
431
+ pipe.vae.enable_tiling()
432
+ # pipe.enable_model_cpu_offload(gpu_id=dist.get_rank())
433
+ # pipe.enable_sequential_cpu_offload(gpu_id=dist.get_rank())
434
+
435
+ for i in range(2):
436
+ begin = time.time()
437
+ output = pipe(
438
+ prompt="A cat walks on the grass, realistic",
439
+ height=720,
440
+ width=1280,
441
+ num_frames=129,
442
+ num_inference_steps=1 if i == 0 else 30,
443
+ output_type="pil" if dist.get_rank() == 0 else "pt",
444
+ ).frames[0]
445
+ end = time.time()
446
+ if dist.get_rank() == 0:
447
+ if i == 0:
448
+ print(f"Warm up time: {end - begin:.2f}s")
449
+ else:
450
+ print(f"Time: {end - begin:.2f}s")
451
+
452
+ if dist.get_rank() == 0:
453
+ print("Saving video to hunyuan_video.mp4")
454
+ export_to_video(output, "hunyuan_video.mp4", fps=15)
455
+
456
+ dist.destroy_process_group()
457
+ ```
458
+
459
+ Save to `run_hunyuan_video.py` and launch it with [torchrun](https://pytorch.org/docs/stable/elastic/run.html).
460
+
461
+ ```bash
462
+ # Use --nproc_per_node to specify the number of GPUs
463
+ torchrun --nproc_per_node=8 run_hunyuan_video.py
464
+ ```
465
+
466
+ Inference speed is reduced to 649.23 seconds compared to the baseline, or 5.66x faster, with 8 NVIDIA L20 GPUs.
467
+
468
+ </hfoption>
469
+ </hfoptions>
470
+
471
+ ## Benchmarks
472
+
473
+ <hfoptions id="conclusion">
474
+ <hfoption id="FLUX-1.dev">
475
+
476
+ | GPU Type | Number of GPUs | Optimizations | Wall Time (s) | Speedup |
477
+ | - | - | - | - | - |
478
+ | NVIDIA L20 | 1 | Baseline | 26.36 | 1.00x |
479
+ | NVIDIA L20 | 1 | FBCache (rdt=0.08) | 17.01 | 1.55x |
480
+ | NVIDIA L20 | 1 | FP8 DQ | 13.40 | 1.96x |
481
+ | NVIDIA L20 | 1 | FBCache (rdt=0.12) + FP8 DQ | 7.56 | 3.48x |
482
+ | NVIDIA L20 | 2 | FBCache (rdt=0.12) + FP8 DQ + CP | 4.92 | 5.35x |
483
+ | NVIDIA L20 | 4 | FBCache (rdt=0.12) + FP8 DQ + CP | 3.90 | 6.75x |
484
+
485
+ </hfoption>
486
+ <hfoption id="HunyuanVideo">
487
+
488
+ | GPU Type | Number of GPUs | Optimizations | Wall Time (s) | Speedup |
489
+ | - | - | - | - | - |
490
+ | NVIDIA L20 | 1 | Baseline | 3675.71 | 1.00x |
491
+ | NVIDIA L20 | 1 | FBCache | 2271.06 | 1.62x |
492
+ | NVIDIA L20 | 2 | FBCache + CP | 1132.90 | 3.24x |
493
+ | NVIDIA L20 | 4 | FBCache + CP | 718.15 | 5.12x |
494
+ | NVIDIA L20 | 8 | FBCache + CP | 649.23 | 5.66x |
495
+
496
+ </hfoption>
497
+ </hfoptions>
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/pruna.md ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Pruna
2
+
3
+ [Pruna](https://github.com/PrunaAI/pruna) is a model optimization framework that offers various optimization methods - quantization, pruning, caching, compilation - for accelerating inference and reducing memory usage. A general overview of the optimization methods are shown below.
4
+
5
+
6
+ | Technique | Description | Speed | Memory | Quality |
7
+ |--------------|-----------------------------------------------------------------------------------------------|:-----:|:------:|:-------:|
8
+ | `batcher` | Groups multiple inputs together to be processed simultaneously, improving computational efficiency and reducing processing time. | ✅ | ❌ | ➖ |
9
+ | `cacher` | Stores intermediate results of computations to speed up subsequent operations. | ✅ | ➖ | ➖ |
10
+ | `compiler` | Optimises the model with instructions for specific hardware. | ✅ | ➖ | ➖ |
11
+ | `distiller` | Trains a smaller, simpler model to mimic a larger, more complex model. | ✅ | ✅ | ❌ |
12
+ | `quantizer` | Reduces the precision of weights and activations, lowering memory requirements. | ✅ | ✅ | ❌ |
13
+ | `pruner` | Removes less important or redundant connections and neurons, resulting in a sparser, more efficient network. | ✅ | ✅ | ❌ |
14
+ | `recoverer` | Restores the performance of a model after compression. | ➖ | ➖ | ✅ |
15
+ | `factorizer` | Factorization batches several small matrix multiplications into one large fused operation. | ✅ | ➖ | ➖ |
16
+ | `enhancer` | Enhances the model output by applying post-processing algorithms such as denoising or upscaling. | ❌ | - | ✅ |
17
+
18
+ ✅ (improves), ➖ (approx. the same), ❌ (worsens)
19
+
20
+ Explore the full range of optimization methods in the [Pruna documentation](https://docs.pruna.ai/en/stable/docs_pruna/user_manual/configure.html#configure-algorithms).
21
+
22
+ ## Installation
23
+
24
+ Install Pruna with the following command.
25
+
26
+ ```bash
27
+ pip install pruna
28
+ ```
29
+
30
+
31
+ ## Optimize Diffusers models
32
+
33
+ A broad range of optimization algorithms are supported for Diffusers models as shown below.
34
+
35
+ <div class="flex justify-center">
36
+ <img src="https://huggingface.co/datasets/PrunaAI/documentation-images/resolve/main/diffusers/diffusers_combinations.png" alt="Overview of the supported optimization algorithms for diffusers models">
37
+ </div>
38
+
39
+ The example below optimizes [black-forest-labs/FLUX.1-dev](https://huggingface.co/black-forest-labs/FLUX.1-dev)
40
+ with a combination of factorizer, compiler, and cacher algorithms. This combination accelerates inference by up to 4.2x and cuts peak GPU memory usage from 34.7GB to 28.0GB, all while maintaining virtually the same output quality.
41
+
42
+ > [!TIP]
43
+ > Refer to the [Pruna optimization](https://docs.pruna.ai/en/stable/docs_pruna/user_manual/configure.html) docs to learn more about the optimization techniques used in this example.
44
+
45
+ <div class="flex justify-center">
46
+ <img src="https://huggingface.co/datasets/PrunaAI/documentation-images/resolve/main/diffusers/flux_combination.png" alt="Optimization techniques used for FLUX.1-dev showing the combination of factorizer, compiler, and cacher algorithms">
47
+ </div>
48
+
49
+ Start by defining a `SmashConfig` with the optimization algorithms to use. To optimize the model, wrap the pipeline and the `SmashConfig` with `smash` and then use the pipeline as normal for inference.
50
+
51
+ ```python
52
+ import torch
53
+ from diffusers import FluxPipeline
54
+
55
+ from pruna import PrunaModel, SmashConfig, smash
56
+
57
+ # load the model
58
+ # Try segmind/Segmind-Vega or black-forest-labs/FLUX.1-schnell with a small GPU memory
59
+ pipe = FluxPipeline.from_pretrained(
60
+ "black-forest-labs/FLUX.1-dev",
61
+ torch_dtype=torch.bfloat16
62
+ ).to("cuda")
63
+
64
+ # define the configuration
65
+ smash_config = SmashConfig()
66
+ smash_config["factorizer"] = "qkv_diffusers"
67
+ smash_config["compiler"] = "torch_compile"
68
+ smash_config["torch_compile_target"] = "module_list"
69
+ smash_config["cacher"] = "fora"
70
+ smash_config["fora_interval"] = 2
71
+
72
+ # for the best results in terms of speed you can add these configs
73
+ # however they will increase your warmup time from 1.5 min to 10 min
74
+ # smash_config["torch_compile_mode"] = "max-autotune-no-cudagraphs"
75
+ # smash_config["quantizer"] = "torchao"
76
+ # smash_config["torchao_quant_type"] = "fp8dq"
77
+ # smash_config["torchao_excluded_modules"] = "norm+embedding"
78
+
79
+ # optimize the model
80
+ smashed_pipe = smash(pipe, smash_config)
81
+
82
+ # run the model
83
+ smashed_pipe("a knitted purple prune").images[0]
84
+ ```
85
+
86
+ <div class="flex justify-center">
87
+ <img src="https://huggingface.co/datasets/PrunaAI/documentation-images/resolve/main/diffusers/flux_smashed_comparison.png">
88
+ </div>
89
+
90
+ After optimization, we can share and load the optimized model using the Hugging Face Hub.
91
+
92
+ ```python
93
+ # save the model
94
+ smashed_pipe.save_to_hub("<username>/FLUX.1-dev-smashed")
95
+
96
+ # load the model
97
+ smashed_pipe = PrunaModel.from_hub("<username>/FLUX.1-dev-smashed")
98
+ ```
99
+
100
+ ## Evaluate and benchmark Diffusers models
101
+
102
+ Pruna provides the [EvaluationAgent](https://docs.pruna.ai/en/stable/docs_pruna/user_manual/evaluate.html) to evaluate the quality of your optimized models.
103
+
104
+ We can metrics we care about, such as total time and throughput, and the dataset to evaluate on. We can define a model and pass it to the `EvaluationAgent`.
105
+
106
+ <hfoptions id="eval">
107
+ <hfoption id="optimized model">
108
+
109
+ We can load and evaluate an optimized model by using the `EvaluationAgent` and pass it to the `Task`.
110
+
111
+ ```python
112
+ import torch
113
+ from diffusers import FluxPipeline
114
+
115
+ from pruna import PrunaModel
116
+ from pruna.data.pruna_datamodule import PrunaDataModule
117
+ from pruna.evaluation.evaluation_agent import EvaluationAgent
118
+ from pruna.evaluation.metrics import (
119
+ ThroughputMetric,
120
+ TorchMetricWrapper,
121
+ TotalTimeMetric,
122
+ )
123
+ from pruna.evaluation.task import Task
124
+
125
+ # define the device
126
+ device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
127
+
128
+ # load the model
129
+ # Try PrunaAI/Segmind-Vega-smashed or PrunaAI/FLUX.1-dev-smashed with a small GPU memory
130
+ smashed_pipe = PrunaModel.from_hub("PrunaAI/FLUX.1-dev-smashed")
131
+
132
+ # Define the metrics
133
+ metrics = [
134
+ TotalTimeMetric(n_iterations=20, n_warmup_iterations=5),
135
+ ThroughputMetric(n_iterations=20, n_warmup_iterations=5),
136
+ TorchMetricWrapper("clip"),
137
+ ]
138
+
139
+ # Define the datamodule
140
+ datamodule = PrunaDataModule.from_string("LAION256")
141
+ datamodule.limit_datasets(10)
142
+
143
+ # Define the task and evaluation agent
144
+ task = Task(metrics, datamodule=datamodule, device=device)
145
+ eval_agent = EvaluationAgent(task)
146
+
147
+ # Evaluate smashed model and offload it to CPU
148
+ smashed_pipe.move_to_device(device)
149
+ smashed_pipe_results = eval_agent.evaluate(smashed_pipe)
150
+ smashed_pipe.move_to_device("cpu")
151
+ ```
152
+
153
+ </hfoption>
154
+ <hfoption id="standalone model">
155
+
156
+ Instead of comparing the optimized model to the base model, you can also evaluate the standalone `diffusers` model. This is useful if you want to evaluate the performance of the model without the optimization. We can do so by using the `PrunaModel` wrapper and run the `EvaluationAgent` on it.
157
+
158
+ ```python
159
+ import torch
160
+ from diffusers import FluxPipeline
161
+
162
+ from pruna import PrunaModel
163
+
164
+ # load the model
165
+ # Try PrunaAI/Segmind-Vega-smashed or PrunaAI/FLUX.1-dev-smashed with a small GPU memory
166
+ pipe = FluxPipeline.from_pretrained(
167
+ "black-forest-labs/FLUX.1-dev",
168
+ torch_dtype=torch.bfloat16
169
+ ).to("cpu")
170
+ wrapped_pipe = PrunaModel(model=pipe)
171
+ ```
172
+
173
+ </hfoption>
174
+ </hfoptions>
175
+
176
+ Now that you have seen how to optimize and evaluate your models, you can start using Pruna to optimize your own models. Luckily, we have many examples to help you get started.
177
+
178
+ > [!TIP]
179
+ > For more details about benchmarking Flux, check out the [Announcing FLUX-Juiced: The Fastest Image Generation Endpoint (2.6 times faster)!](https://huggingface.co/blog/PrunaAI/flux-fastest-image-generation-endpoint) blog post and the [InferBench](https://huggingface.co/spaces/PrunaAI/InferBench) Space.
180
+
181
+ ## Reference
182
+
183
+ - [Pruna](https://github.com/pruna-ai/pruna)
184
+ - [Pruna optimization](https://docs.pruna.ai/en/stable/docs_pruna/user_manual/configure.html#configure-algorithms)
185
+ - [Pruna evaluation](https://docs.pruna.ai/en/stable/docs_pruna/user_manual/evaluate.html)
186
+ - [Pruna tutorials](https://docs.pruna.ai/en/stable/docs_pruna/tutorials/index.html)
187
+
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/speed-memory-optims.md ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2024 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
+ # Compiling and offloading quantized models
14
+
15
+ 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).
16
+
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
+
20
+ 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.
21
+
22
+ For video generation, combining quantization and [group-offloading](./memory#group-offloading) tends to be better because video models are more compute-bound.
23
+
24
+ The table below provides a comparison of optimization strategy combinations and their impact on latency and memory-usage for Flux.
25
+
26
+ | combination | latency (s) | memory-usage (GB) |
27
+ |---|---|---|
28
+ | quantization | 32.602 | 14.9453 |
29
+ | quantization, torch.compile | 25.847 | 14.9448 |
30
+ | quantization, torch.compile, model CPU offloading | 32.312 | 12.2369 |
31
+
32
+ <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>
33
+
34
+ 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.
35
+
36
+ ```bash
37
+ pip install -U bitsandbytes
38
+ ```
39
+
40
+ ## Quantization and torch.compile
41
+
42
+ Start by [quantizing](../quantization/overview) a model to reduce the memory required for storage and [compiling](./fp16#torchcompile) it to accelerate inference.
43
+
44
+ Configure the [Dynamo](https://docs.pytorch.org/docs/stable/torch.compiler_dynamo_overview.html) `capture_dynamic_output_shape_ops = True` to handle dynamic outputs when compiling bitsandbytes models.
45
+
46
+ ```py
47
+ import torch
48
+ from diffusers import DiffusionPipeline
49
+ from diffusers.quantizers import PipelineQuantizationConfig
50
+
51
+ torch._dynamo.config.capture_dynamic_output_shape_ops = True
52
+
53
+ # quantize
54
+ pipeline_quant_config = PipelineQuantizationConfig(
55
+ quant_backend="bitsandbytes_4bit",
56
+ quant_kwargs={"load_in_4bit": True, "bnb_4bit_quant_type": "nf4", "bnb_4bit_compute_dtype": torch.bfloat16},
57
+ components_to_quantize=["transformer", "text_encoder_2"],
58
+ )
59
+ pipeline = DiffusionPipeline.from_pretrained(
60
+ "black-forest-labs/FLUX.1-dev",
61
+ quantization_config=pipeline_quant_config,
62
+ torch_dtype=torch.bfloat16,
63
+ ).to("cuda")
64
+
65
+ # compile
66
+ pipeline.transformer.to(memory_format=torch.channels_last)
67
+ pipeline.transformer.compile(mode="max-autotune", fullgraph=True)
68
+ pipeline("""
69
+ cinematic film still of a cat sipping a margarita in a pool in Palm Springs, California
70
+ highly detailed, high budget hollywood movie, cinemascope, moody, epic, gorgeous, film grain
71
+ """
72
+ ).images[0]
73
+ ```
74
+
75
+ ## Quantization, torch.compile, and offloading
76
+
77
+ In addition to quantization and torch.compile, try offloading if you need to reduce memory-usage further. Offloading moves various layers or model components from the CPU to the GPU as needed for computations.
78
+
79
+ Configure the [Dynamo](https://docs.pytorch.org/docs/stable/torch.compiler_dynamo_overview.html) `cache_size_limit` during offloading to avoid excessive recompilation and set `capture_dynamic_output_shape_ops = True` to handle dynamic outputs when compiling bitsandbytes models.
80
+
81
+ <hfoptions id="offloading">
82
+ <hfoption id="model CPU offloading">
83
+
84
+ [Model CPU offloading](./memory#model-offloading) moves an individual pipeline component, like the transformer model, to the GPU when it is needed for computation. Otherwise, it is offloaded to the CPU.
85
+
86
+ ```py
87
+ import torch
88
+ from diffusers import DiffusionPipeline
89
+ from diffusers.quantizers import PipelineQuantizationConfig
90
+
91
+ torch._dynamo.config.cache_size_limit = 1000
92
+ torch._dynamo.config.capture_dynamic_output_shape_ops = True
93
+
94
+ # quantize
95
+ pipeline_quant_config = PipelineQuantizationConfig(
96
+ quant_backend="bitsandbytes_4bit",
97
+ quant_kwargs={"load_in_4bit": True, "bnb_4bit_quant_type": "nf4", "bnb_4bit_compute_dtype": torch.bfloat16},
98
+ components_to_quantize=["transformer", "text_encoder_2"],
99
+ )
100
+ pipeline = DiffusionPipeline.from_pretrained(
101
+ "black-forest-labs/FLUX.1-dev",
102
+ quantization_config=pipeline_quant_config,
103
+ torch_dtype=torch.bfloat16,
104
+ ).to("cuda")
105
+
106
+ # model CPU offloading
107
+ pipeline.enable_model_cpu_offload()
108
+
109
+ # compile
110
+ pipeline.transformer.compile()
111
+ pipeline(
112
+ "cinematic film still of a cat sipping a margarita in a pool in Palm Springs, California, highly detailed, high budget hollywood movie, cinemascope, moody, epic, gorgeous, film grain"
113
+ ).images[0]
114
+ ```
115
+
116
+ </hfoption>
117
+ <hfoption id="group offloading">
118
+
119
+ [Group offloading](./memory#group-offloading) moves the internal layers of an individual pipeline component, like the transformer model, to the GPU for computation and offloads it when it's not required. At the same time, it uses the [CUDA stream](./memory#cuda-stream) feature to prefetch the next layer for execution.
120
+
121
+ By overlapping computation and data transfer, it is faster than model CPU offloading while also saving memory.
122
+
123
+ ```py
124
+ # pip install ftfy
125
+ import torch
126
+ from diffusers import AutoModel, DiffusionPipeline
127
+ from diffusers.hooks import apply_group_offloading
128
+ from diffusers.utils import export_to_video
129
+ from diffusers.quantizers import PipelineQuantizationConfig
130
+ from transformers import UMT5EncoderModel
131
+
132
+ torch._dynamo.config.cache_size_limit = 1000
133
+ torch._dynamo.config.capture_dynamic_output_shape_ops = True
134
+
135
+ # quantize
136
+ pipeline_quant_config = PipelineQuantizationConfig(
137
+ quant_backend="bitsandbytes_4bit",
138
+ quant_kwargs={"load_in_4bit": True, "bnb_4bit_quant_type": "nf4", "bnb_4bit_compute_dtype": torch.bfloat16},
139
+ components_to_quantize=["transformer", "text_encoder"],
140
+ )
141
+
142
+ text_encoder = UMT5EncoderModel.from_pretrained(
143
+ "Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="text_encoder", torch_dtype=torch.bfloat16
144
+ )
145
+ pipeline = DiffusionPipeline.from_pretrained(
146
+ "Wan-AI/Wan2.1-T2V-14B-Diffusers",
147
+ quantization_config=pipeline_quant_config,
148
+ torch_dtype=torch.bfloat16,
149
+ ).to("cuda")
150
+
151
+ # group offloading
152
+ onload_device = torch.device("cuda")
153
+ offload_device = torch.device("cpu")
154
+
155
+ pipeline.transformer.enable_group_offload(
156
+ onload_device=onload_device,
157
+ offload_device=offload_device,
158
+ offload_type="leaf_level",
159
+ use_stream=True,
160
+ non_blocking=True
161
+ )
162
+ pipeline.vae.enable_group_offload(
163
+ onload_device=onload_device,
164
+ offload_device=offload_device,
165
+ offload_type="leaf_level",
166
+ use_stream=True,
167
+ non_blocking=True
168
+ )
169
+ apply_group_offloading(
170
+ pipeline.text_encoder,
171
+ onload_device=onload_device,
172
+ offload_type="leaf_level",
173
+ use_stream=True,
174
+ non_blocking=True
175
+ )
176
+
177
+ # compile
178
+ pipeline.transformer.compile()
179
+
180
+ prompt = """
181
+ The camera rushes from far to near in a low-angle shot,
182
+ revealing a white ferret on a log. It plays, leaps into the water, and emerges, as the camera zooms in
183
+ for a close-up. Water splashes berry bushes nearby, while moss, snow, and leaves blanket the ground.
184
+ Birch trees and a light blue sky frame the scene, with ferns in the foreground. Side lighting casts dynamic
185
+ shadows and warm highlights. Medium composition, front view, low angle, with depth of field.
186
+ """
187
+ negative_prompt = """
188
+ Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality,
189
+ low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured,
190
+ misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards
191
+ """
192
+
193
+ output = pipeline(
194
+ prompt=prompt,
195
+ negative_prompt=negative_prompt,
196
+ num_frames=81,
197
+ guidance_scale=5.0,
198
+ ).frames[0]
199
+ export_to_video(output, "output.mp4", fps=16)
200
+ ```
201
+
202
+ </hfoption>
203
+ </hfoptions>
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/tgate.md ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # T-GATE
2
+
3
+ [T-GATE](https://github.com/HaozheLiu-ST/T-GATE/tree/main) accelerates inference for [Stable Diffusion](../api/pipelines/stable_diffusion/overview), [PixArt](../api/pipelines/pixart), and [Latency Consistency Model](../api/pipelines/latent_consistency_models.md) pipelines by skipping the cross-attention calculation once it converges. This method doesn't require any additional training and it can speed up inference from 10-50%. T-GATE is also compatible with other optimization methods like [DeepCache](./deepcache).
4
+
5
+ Before you begin, make sure you install T-GATE.
6
+
7
+ ```bash
8
+ pip install tgate
9
+ pip install -U torch diffusers transformers accelerate DeepCache
10
+ ```
11
+
12
+
13
+ To use T-GATE with a pipeline, you need to use its corresponding loader.
14
+
15
+ | Pipeline | T-GATE Loader |
16
+ |---|---|
17
+ | PixArt | TgatePixArtLoader |
18
+ | Stable Diffusion XL | TgateSDXLLoader |
19
+ | Stable Diffusion XL + DeepCache | TgateSDXLDeepCacheLoader |
20
+ | Stable Diffusion | TgateSDLoader |
21
+ | Stable Diffusion + DeepCache | TgateSDDeepCacheLoader |
22
+
23
+ Next, create a `TgateLoader` with a pipeline, the gate step (the time step to stop calculating the cross attention), and the number of inference steps. Then call the `tgate` method on the pipeline with a prompt, gate step, and the number of inference steps.
24
+
25
+ Let's see how to enable this for several different pipelines.
26
+
27
+ <hfoptions id="pipelines">
28
+ <hfoption id="PixArt">
29
+
30
+ Accelerate `PixArtAlphaPipeline` with T-GATE:
31
+
32
+ ```py
33
+ import torch
34
+ from diffusers import PixArtAlphaPipeline
35
+ from tgate import TgatePixArtLoader
36
+
37
+ pipe = PixArtAlphaPipeline.from_pretrained("PixArt-alpha/PixArt-XL-2-1024-MS", torch_dtype=torch.float16)
38
+
39
+ gate_step = 8
40
+ inference_step = 25
41
+ pipe = TgatePixArtLoader(
42
+ pipe,
43
+ gate_step=gate_step,
44
+ num_inference_steps=inference_step,
45
+ ).to("cuda")
46
+
47
+ image = pipe.tgate(
48
+ "An alpaca made of colorful building blocks, cyberpunk.",
49
+ gate_step=gate_step,
50
+ num_inference_steps=inference_step,
51
+ ).images[0]
52
+ ```
53
+ </hfoption>
54
+ <hfoption id="Stable Diffusion XL">
55
+
56
+ Accelerate `StableDiffusionXLPipeline` with T-GATE:
57
+
58
+ ```py
59
+ import torch
60
+ from diffusers import StableDiffusionXLPipeline
61
+ from diffusers import DPMSolverMultistepScheduler
62
+ from tgate import TgateSDXLLoader
63
+
64
+ pipe = StableDiffusionXLPipeline.from_pretrained(
65
+ "stabilityai/stable-diffusion-xl-base-1.0",
66
+ torch_dtype=torch.float16,
67
+ variant="fp16",
68
+ use_safetensors=True,
69
+ )
70
+ pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
71
+
72
+ gate_step = 10
73
+ inference_step = 25
74
+ pipe = TgateSDXLLoader(
75
+ pipe,
76
+ gate_step=gate_step,
77
+ num_inference_steps=inference_step,
78
+ ).to("cuda")
79
+
80
+ image = pipe.tgate(
81
+ "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k.",
82
+ gate_step=gate_step,
83
+ num_inference_steps=inference_step
84
+ ).images[0]
85
+ ```
86
+ </hfoption>
87
+ <hfoption id="StableDiffusionXL with DeepCache">
88
+
89
+ Accelerate `StableDiffusionXLPipeline` with [DeepCache](https://github.com/horseee/DeepCache) and T-GATE:
90
+
91
+ ```py
92
+ import torch
93
+ from diffusers import StableDiffusionXLPipeline
94
+ from diffusers import DPMSolverMultistepScheduler
95
+ from tgate import TgateSDXLDeepCacheLoader
96
+
97
+ pipe = StableDiffusionXLPipeline.from_pretrained(
98
+ "stabilityai/stable-diffusion-xl-base-1.0",
99
+ torch_dtype=torch.float16,
100
+ variant="fp16",
101
+ use_safetensors=True,
102
+ )
103
+ pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
104
+
105
+ gate_step = 10
106
+ inference_step = 25
107
+ pipe = TgateSDXLDeepCacheLoader(
108
+ pipe,
109
+ cache_interval=3,
110
+ cache_branch_id=0,
111
+ ).to("cuda")
112
+
113
+ image = pipe.tgate(
114
+ "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k.",
115
+ gate_step=gate_step,
116
+ num_inference_steps=inference_step
117
+ ).images[0]
118
+ ```
119
+ </hfoption>
120
+ <hfoption id="Latent Consistency Model">
121
+
122
+ Accelerate `latent-consistency/lcm-sdxl` with T-GATE:
123
+
124
+ ```py
125
+ import torch
126
+ from diffusers import StableDiffusionXLPipeline
127
+ from diffusers import UNet2DConditionModel, LCMScheduler
128
+ from diffusers import DPMSolverMultistepScheduler
129
+ from tgate import TgateSDXLLoader
130
+
131
+ unet = UNet2DConditionModel.from_pretrained(
132
+ "latent-consistency/lcm-sdxl",
133
+ torch_dtype=torch.float16,
134
+ variant="fp16",
135
+ )
136
+ pipe = StableDiffusionXLPipeline.from_pretrained(
137
+ "stabilityai/stable-diffusion-xl-base-1.0",
138
+ unet=unet,
139
+ torch_dtype=torch.float16,
140
+ variant="fp16",
141
+ )
142
+ pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)
143
+
144
+ gate_step = 1
145
+ inference_step = 4
146
+ pipe = TgateSDXLLoader(
147
+ pipe,
148
+ gate_step=gate_step,
149
+ num_inference_steps=inference_step,
150
+ lcm=True
151
+ ).to("cuda")
152
+
153
+ image = pipe.tgate(
154
+ "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k.",
155
+ gate_step=gate_step,
156
+ num_inference_steps=inference_step
157
+ ).images[0]
158
+ ```
159
+ </hfoption>
160
+ </hfoptions>
161
+
162
+ T-GATE also supports [`StableDiffusionPipeline`] and [PixArt-alpha/PixArt-LCM-XL-2-1024-MS](https://hf.co/PixArt-alpha/PixArt-LCM-XL-2-1024-MS).
163
+
164
+ ## Benchmarks
165
+ | Model | MACs | Param | Latency | Zero-shot 10K-FID on MS-COCO |
166
+ |-----------------------|----------|-----------|---------|---------------------------|
167
+ | SD-1.5 | 16.938T | 859.520M | 7.032s | 23.927 |
168
+ | SD-1.5 w/ T-GATE | 9.875T | 815.557M | 4.313s | 20.789 |
169
+ | SD-2.1 | 38.041T | 865.785M | 16.121s | 22.609 |
170
+ | SD-2.1 w/ T-GATE | 22.208T | 815.433 M | 9.878s | 19.940 |
171
+ | SD-XL | 149.438T | 2.570B | 53.187s | 24.628 |
172
+ | SD-XL w/ T-GATE | 84.438T | 2.024B | 27.932s | 22.738 |
173
+ | Pixart-Alpha | 107.031T | 611.350M | 61.502s | 38.669 |
174
+ | Pixart-Alpha w/ T-GATE | 65.318T | 462.585M | 37.867s | 35.825 |
175
+ | DeepCache (SD-XL) | 57.888T | - | 19.931s | 23.755 |
176
+ | DeepCache w/ T-GATE | 43.868T | - | 14.666s | 23.999 |
177
+ | LCM (SD-XL) | 11.955T | 2.570B | 3.805s | 25.044 |
178
+ | LCM w/ T-GATE | 11.171T | 2.024B | 3.533s | 25.028 |
179
+ | LCM (Pixart-Alpha) | 8.563T | 611.350M | 4.733s | 36.086 |
180
+ | LCM w/ T-GATE | 7.623T | 462.585M | 4.543s | 37.048 |
181
+
182
+ The latency is tested on an NVIDIA 1080TI, MACs and Params are calculated with [calflops](https://github.com/MrYxJ/calculate-flops.pytorch), and the FID is calculated with [PytorchFID](https://github.com/mseitzer/pytorch-fid).
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/tome.md ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Token merging
14
+
15
+ [Token merging](https://huggingface.co/papers/2303.17604) (ToMe) merges redundant tokens/patches progressively in the forward pass of a Transformer-based network which can speed-up the inference latency of [`StableDiffusionPipeline`].
16
+
17
+ Install ToMe from `pip`:
18
+
19
+ ```bash
20
+ pip install tomesd
21
+ ```
22
+
23
+ You can use ToMe from the [`tomesd`](https://github.com/dbolya/tomesd) library with the [`apply_patch`](https://github.com/dbolya/tomesd?tab=readme-ov-file#usage) function:
24
+
25
+ ```diff
26
+ from diffusers import StableDiffusionPipeline
27
+ import torch
28
+ import tomesd
29
+
30
+ pipeline = StableDiffusionPipeline.from_pretrained(
31
+ "stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16, use_safetensors=True,
32
+ ).to("cuda")
33
+ + tomesd.apply_patch(pipeline, ratio=0.5)
34
+
35
+ image = pipeline("a photo of an astronaut riding a horse on mars").images[0]
36
+ ```
37
+
38
+ The `apply_patch` function exposes a number of [arguments](https://github.com/dbolya/tomesd#usage) to help strike a balance between pipeline inference speed and the quality of the generated tokens. The most important argument is `ratio` which controls the number of tokens that are merged during the forward pass.
39
+
40
+ As reported in the [paper](https://huggingface.co/papers/2303.17604), ToMe can greatly preserve the quality of the generated images while boosting inference speed. By increasing the `ratio`, you can speed-up inference even further, but at the cost of some degraded image quality.
41
+
42
+ To test the quality of the generated images, we sampled a few prompts from [Parti Prompts](https://parti.research.google/) and performed inference with the [`StableDiffusionPipeline`] with the following settings:
43
+
44
+ <div class="flex justify-center">
45
+ <img src="https://huggingface.co/datasets/diffusers/docs-images/resolve/main/tome/tome_samples.png">
46
+ </div>
47
+
48
+ We didn’t notice any significant decrease in the quality of the generated samples, and you can check out the generated samples in this [WandB report](https://wandb.ai/sayakpaul/tomesd-results/runs/23j4bj3i?workspace=). If you're interested in reproducing this experiment, use this [script](https://gist.github.com/sayakpaul/8cac98d7f22399085a060992f411ecbd).
49
+
50
+ ## Benchmarks
51
+
52
+ We also benchmarked the impact of `tomesd` on the [`StableDiffusionPipeline`] with [xFormers](https://huggingface.co/docs/diffusers/optimization/xformers) enabled across several image resolutions. The results are obtained from A100 and V100 GPUs in the following development environment:
53
+
54
+ ```bash
55
+ - `diffusers` version: 0.15.1
56
+ - Python version: 3.8.16
57
+ - PyTorch version (GPU?): 1.13.1+cu116 (True)
58
+ - Huggingface_hub version: 0.13.2
59
+ - Transformers version: 4.27.2
60
+ - Accelerate version: 0.18.0
61
+ - xFormers version: 0.0.16
62
+ - tomesd version: 0.1.2
63
+ ```
64
+
65
+ To reproduce this benchmark, feel free to use this [script](https://gist.github.com/sayakpaul/27aec6bca7eb7b0e0aa4112205850335). The results are reported in seconds, and where applicable we report the speed-up percentage over the vanilla pipeline when using ToMe and ToMe + xFormers.
66
+
67
+ | **GPU** | **Resolution** | **Batch size** | **Vanilla** | **ToMe** | **ToMe + xFormers** |
68
+ |----------|----------------|----------------|-------------|----------------|---------------------|
69
+ | **A100** | 512 | 10 | 6.88 | 5.26 (+23.55%) | 4.69 (+31.83%) |
70
+ | | 768 | 10 | OOM | 14.71 | 11 |
71
+ | | | 8 | OOM | 11.56 | 8.84 |
72
+ | | | 4 | OOM | 5.98 | 4.66 |
73
+ | | | 2 | 4.99 | 3.24 (+35.07%) | 2.1 (+37.88%) |
74
+ | | | 1 | 3.29 | 2.24 (+31.91%) | 2.03 (+38.3%) |
75
+ | | 1024 | 10 | OOM | OOM | OOM |
76
+ | | | 8 | OOM | OOM | OOM |
77
+ | | | 4 | OOM | 12.51 | 9.09 |
78
+ | | | 2 | OOM | 6.52 | 4.96 |
79
+ | | | 1 | 6.4 | 3.61 (+43.59%) | 2.81 (+56.09%) |
80
+ | **V100** | 512 | 10 | OOM | 10.03 | 9.29 |
81
+ | | | 8 | OOM | 8.05 | 7.47 |
82
+ | | | 4 | 5.7 | 4.3 (+24.56%) | 3.98 (+30.18%) |
83
+ | | | 2 | 3.14 | 2.43 (+22.61%) | 2.27 (+27.71%) |
84
+ | | | 1 | 1.88 | 1.57 (+16.49%) | 1.57 (+16.49%) |
85
+ | | 768 | 10 | OOM | OOM | 23.67 |
86
+ | | | 8 | OOM | OOM | 18.81 |
87
+ | | | 4 | OOM | 11.81 | 9.7 |
88
+ | | | 2 | OOM | 6.27 | 5.2 |
89
+ | | | 1 | 5.43 | 3.38 (+37.75%) | 2.82 (+48.07%) |
90
+ | | 1024 | 10 | OOM | OOM | OOM |
91
+ | | | 8 | OOM | OOM | OOM |
92
+ | | | 4 | OOM | OOM | 19.35 |
93
+ | | | 2 | OOM | 13 | 10.78 |
94
+ | | | 1 | OOM | 6.66 | 5.54 |
95
+
96
+ As seen in the tables above, the speed-up from `tomesd` becomes more pronounced for larger image resolutions. It is also interesting to note that with `tomesd`, it is possible to run the pipeline on a higher resolution like 1024x1024. You may be able to speed-up inference even more with [`torch.compile`](fp16#torchcompile).
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/xdit.md ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # xDiT
2
+
3
+ [xDiT](https://github.com/xdit-project/xDiT) is an inference engine designed for the large scale parallel deployment of Diffusion Transformers (DiTs). xDiT provides a suite of efficient parallel approaches for Diffusion Models, as well as GPU kernel accelerations.
4
+
5
+ There are four parallel methods supported in xDiT, including [Unified Sequence Parallelism](https://huggingface.co/papers/2405.07719), [PipeFusion](https://huggingface.co/papers/2405.14430), CFG parallelism and data parallelism. The four parallel methods in xDiT can be configured in a hybrid manner, optimizing communication patterns to best suit the underlying network hardware.
6
+
7
+ Optimization orthogonal to parallelization focuses on accelerating single GPU performance. In addition to utilizing well-known Attention optimization libraries, we leverage compilation acceleration technologies such as torch.compile and onediff.
8
+
9
+ The overview of xDiT is shown as follows.
10
+
11
+ <div class="flex justify-center">
12
+ <img src="https://huggingface.co/datasets/xDiT/documentation-images/resolve/main/methods/xdit_overview.png">
13
+ </div>
14
+ You can install xDiT using the following command:
15
+
16
+
17
+ ```bash
18
+ pip install xfuser
19
+ ```
20
+
21
+ Here's an example of using xDiT to accelerate inference of a Diffusers model.
22
+
23
+ ```diff
24
+ import torch
25
+ from diffusers import StableDiffusion3Pipeline
26
+
27
+ from xfuser import xFuserArgs, xDiTParallel
28
+ from xfuser.config import FlexibleArgumentParser
29
+ from xfuser.core.distributed import get_world_group
30
+
31
+ def main():
32
+ + parser = FlexibleArgumentParser(description="xFuser Arguments")
33
+ + args = xFuserArgs.add_cli_args(parser).parse_args()
34
+ + engine_args = xFuserArgs.from_cli_args(args)
35
+ + engine_config, input_config = engine_args.create_config()
36
+
37
+ local_rank = get_world_group().local_rank
38
+ pipe = StableDiffusion3Pipeline.from_pretrained(
39
+ pretrained_model_name_or_path=engine_config.model_config.model,
40
+ torch_dtype=torch.float16,
41
+ ).to(f"cuda:{local_rank}")
42
+
43
+ # do anything you want with pipeline here
44
+
45
+ + pipe = xDiTParallel(pipe, engine_config, input_config)
46
+
47
+ pipe(
48
+ height=input_config.height,
49
+ width=input_config.height,
50
+ prompt=input_config.prompt,
51
+ num_inference_steps=input_config.num_inference_steps,
52
+ output_type=input_config.output_type,
53
+ generator=torch.Generator(device="cuda").manual_seed(input_config.seed),
54
+ )
55
+
56
+ + if input_config.output_type == "pil":
57
+ + pipe.save("results", "stable_diffusion_3")
58
+
59
+ if __name__ == "__main__":
60
+ main()
61
+
62
+ ```
63
+
64
+ As you can see, we only need to use xFuserArgs from xDiT to get configuration parameters, and pass these parameters along with the pipeline object from the Diffusers library into xDiTParallel to complete the parallelization of a specific pipeline in Diffusers.
65
+
66
+ xDiT runtime parameters can be viewed in the command line using `-h`, and you can refer to this [usage](https://github.com/xdit-project/xDiT?tab=readme-ov-file#2-usage) example for more details.
67
+
68
+ xDiT needs to be launched using torchrun to support its multi-node, multi-GPU parallel capabilities. For example, the following command can be used for 8-GPU parallel inference:
69
+
70
+ ```bash
71
+ torchrun --nproc_per_node=8 ./inference.py --model models/FLUX.1-dev --data_parallel_degree 2 --ulysses_degree 2 --ring_degree 2 --prompt "A snowy mountain" "A small dog" --num_inference_steps 50
72
+ ```
73
+
74
+ ## Supported models
75
+
76
+ A subset of Diffusers models are supported in xDiT, such as Flux.1, Stable Diffusion 3, etc. The latest supported models can be found [here](https://github.com/xdit-project/xDiT?tab=readme-ov-file#-supported-dits).
77
+
78
+ ## Benchmark
79
+ We tested different models on various machines, and here is some of the benchmark data.
80
+
81
+ ### Flux.1-schnell
82
+ <div class="flex justify-center">
83
+ <img src="https://huggingface.co/datasets/xDiT/documentation-images/resolve/main/performance/flux/Flux-2k-L40.png">
84
+ </div>
85
+
86
+
87
+ <div class="flex justify-center">
88
+ <img src="https://huggingface.co/datasets/xDiT/documentation-images/resolve/main/performance/flux/Flux-2K-A100.png">
89
+ </div>
90
+
91
+ ### Stable Diffusion 3
92
+ <div class="flex justify-center">
93
+ <img src="https://huggingface.co/datasets/xDiT/documentation-images/resolve/main/performance/sd3/L40-SD3.png">
94
+ </div>
95
+
96
+ <div class="flex justify-center">
97
+ <img src="https://huggingface.co/datasets/xDiT/documentation-images/resolve/main/performance/sd3/A100-SD3.png">
98
+ </div>
99
+
100
+ ### HunyuanDiT
101
+ <div class="flex justify-center">
102
+ <img src="https://huggingface.co/datasets/xDiT/documentation-images/resolve/main/performance/hunuyuandit/L40-HunyuanDiT.png">
103
+ </div>
104
+
105
+ <div class="flex justify-center">
106
+ <img src="https://huggingface.co/datasets/xDiT/documentation-images/resolve/main/performance/hunuyuandit/V100-HunyuanDiT.png">
107
+ </div>
108
+
109
+ <div class="flex justify-center">
110
+ <img src="https://huggingface.co/datasets/xDiT/documentation-images/resolve/main/performance/hunuyuandit/T4-HunyuanDiT.png">
111
+ </div>
112
+
113
+ More detailed performance metric can be found on our [github page](https://github.com/xdit-project/xDiT?tab=readme-ov-file#perf).
114
+
115
+ ## Reference
116
+
117
+ [xDiT-project](https://github.com/xdit-project/xDiT)
118
+
119
+ [USP: A Unified Sequence Parallelism Approach for Long Context Generative AI](https://huggingface.co/papers/2405.07719)
120
+
121
+ [PipeFusion: Displaced Patch Pipeline Parallelism for Inference of Diffusion Transformer Models](https://huggingface.co/papers/2405.14430)
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/optimization/xformers.md ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # xFormers
14
+
15
+ We recommend [xFormers](https://github.com/facebookresearch/xformers) for both inference and training. In our tests, the optimizations performed in the attention blocks allow for both faster speed and reduced memory consumption.
16
+
17
+ Install xFormers from `pip`:
18
+
19
+ ```bash
20
+ pip install xformers
21
+ ```
22
+
23
+ > [!TIP]
24
+ > The xFormers `pip` package requires the latest version of PyTorch. If you need to use a previous version of PyTorch, then we recommend [installing xFormers from the source](https://github.com/facebookresearch/xformers#installing-xformers).
25
+
26
+ After xFormers is installed, you can use `enable_xformers_memory_efficient_attention()` for faster inference and reduced memory consumption as shown in this [section](memory#memory-efficient-attention).
27
+
28
+ > [!WARNING]
29
+ > According to this [issue](https://github.com/huggingface/diffusers/issues/2234#issuecomment-1416931212), xFormers `v0.0.16` cannot be used for training (fine-tune or DreamBooth) in some GPUs. If you observe this problem, please install a development version as indicated in the issue comments.
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/quantization/bitsandbytes.md ADDED
@@ -0,0 +1,452 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
14
+ # bitsandbytes
15
+
16
+ [bitsandbytes](https://huggingface.co/docs/bitsandbytes/index) is the easiest option for quantizing a model to 8 and 4-bit. 8-bit quantization multiplies outliers in fp16 with non-outliers in int8, converts the non-outlier values back to fp16, and then adds them together to return the weights in fp16. This reduces the degradative effect outlier values have on a model's performance.
17
+
18
+ 4-bit quantization compresses a model even further, and it is commonly used with [QLoRA](https://hf.co/papers/2305.14314) to finetune quantized LLMs.
19
+
20
+ This guide demonstrates how quantization can enable running
21
+ [FLUX.1-dev](https://huggingface.co/black-forest-labs/FLUX.1-dev)
22
+ on less than 16GB of VRAM and even on a free Google
23
+ Colab instance.
24
+
25
+ ![comparison image](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/quant-bnb/comparison.png)
26
+
27
+ To use bitsandbytes, make sure you have the following libraries installed:
28
+
29
+ ```bash
30
+ pip install diffusers transformers accelerate bitsandbytes -U
31
+ ```
32
+
33
+ Now you can quantize a model by passing a [`BitsAndBytesConfig`] to [`~ModelMixin.from_pretrained`]. This works for any model in any modality, as long as it supports loading with [Accelerate](https://hf.co/docs/accelerate/index) and contains `torch.nn.Linear` layers.
34
+
35
+ <hfoptions id="bnb">
36
+ <hfoption id="8-bit">
37
+
38
+ Quantizing a model in 8-bit halves the memory-usage:
39
+
40
+ bitsandbytes is supported in both Transformers and Diffusers, so you can quantize both the
41
+ [`FluxTransformer2DModel`] and [`~transformers.T5EncoderModel`].
42
+
43
+ For Ada and higher-series GPUs. we recommend changing `torch_dtype` to `torch.bfloat16`.
44
+
45
+ > [!TIP]
46
+ > The [`CLIPTextModel`] and [`AutoencoderKL`] aren't quantized because they're already small in size and because [`AutoencoderKL`] only has a few `torch.nn.Linear` layers.
47
+
48
+ ```py
49
+ from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig
50
+ from transformers import BitsAndBytesConfig as TransformersBitsAndBytesConfig
51
+ import torch
52
+ from diffusers import AutoModel
53
+ from transformers import T5EncoderModel
54
+
55
+ quant_config = TransformersBitsAndBytesConfig(load_in_8bit=True,)
56
+
57
+ text_encoder_2_8bit = T5EncoderModel.from_pretrained(
58
+ "black-forest-labs/FLUX.1-dev",
59
+ subfolder="text_encoder_2",
60
+ quantization_config=quant_config,
61
+ torch_dtype=torch.float16,
62
+ )
63
+
64
+ quant_config = DiffusersBitsAndBytesConfig(load_in_8bit=True,)
65
+
66
+ transformer_8bit = AutoModel.from_pretrained(
67
+ "black-forest-labs/FLUX.1-dev",
68
+ subfolder="transformer",
69
+ quantization_config=quant_config,
70
+ torch_dtype=torch.float16,
71
+ )
72
+ ```
73
+
74
+ By default, all the other modules such as `torch.nn.LayerNorm` are converted to `torch.float16`. You can change the data type of these modules with the `torch_dtype` parameter.
75
+
76
+ ```diff
77
+ transformer_8bit = AutoModel.from_pretrained(
78
+ "black-forest-labs/FLUX.1-dev",
79
+ subfolder="transformer",
80
+ quantization_config=quant_config,
81
+ + torch_dtype=torch.float32,
82
+ )
83
+ ```
84
+
85
+ Let's generate an image using our quantized models.
86
+
87
+ Setting `device_map="auto"` automatically fills all available space on the GPU(s) first, then the
88
+ CPU, and finally, the hard drive (the absolute slowest option) if there is still not enough memory.
89
+
90
+ ```py
91
+ from diffusers import FluxPipeline
92
+
93
+ pipe = FluxPipeline.from_pretrained(
94
+ "black-forest-labs/FLUX.1-dev",
95
+ transformer=transformer_8bit,
96
+ text_encoder_2=text_encoder_2_8bit,
97
+ torch_dtype=torch.float16,
98
+ device_map="auto",
99
+ )
100
+
101
+ pipe_kwargs = {
102
+ "prompt": "A cat holding a sign that says hello world",
103
+ "height": 1024,
104
+ "width": 1024,
105
+ "guidance_scale": 3.5,
106
+ "num_inference_steps": 50,
107
+ "max_sequence_length": 512,
108
+ }
109
+
110
+ image = pipe(**pipe_kwargs, generator=torch.manual_seed(0),).images[0]
111
+ ```
112
+
113
+ <div class="flex justify-center">
114
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/quant-bnb/8bit.png"/>
115
+ </div>
116
+
117
+ When there is enough memory, you can also directly move the pipeline to the GPU with `.to("cuda")` and apply [`~DiffusionPipeline.enable_model_cpu_offload`] to optimize GPU memory usage.
118
+
119
+ Once a model is quantized, you can push the model to the Hub with the [`~ModelMixin.push_to_hub`] method. The quantization `config.json` file is pushed first, followed by the quantized model weights. You can also save the serialized 8-bit models locally with [`~ModelMixin.save_pretrained`].
120
+
121
+ </hfoption>
122
+ <hfoption id="4-bit">
123
+
124
+ Quantizing a model in 4-bit reduces your memory-usage by 4x:
125
+
126
+ bitsandbytes is supported in both Transformers and Diffusers, so you can can quantize both the
127
+ [`FluxTransformer2DModel`] and [`~transformers.T5EncoderModel`].
128
+
129
+ For Ada and higher-series GPUs. we recommend changing `torch_dtype` to `torch.bfloat16`.
130
+
131
+ > [!TIP]
132
+ > The [`CLIPTextModel`] and [`AutoencoderKL`] aren't quantized because they're already small in size and because [`AutoencoderKL`] only has a few `torch.nn.Linear` layers.
133
+
134
+ ```py
135
+ from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig
136
+ from transformers import BitsAndBytesConfig as TransformersBitsAndBytesConfig
137
+ import torch
138
+ from diffusers import AutoModel
139
+ from transformers import T5EncoderModel
140
+
141
+ quant_config = TransformersBitsAndBytesConfig(load_in_4bit=True,)
142
+
143
+ text_encoder_2_4bit = T5EncoderModel.from_pretrained(
144
+ "black-forest-labs/FLUX.1-dev",
145
+ subfolder="text_encoder_2",
146
+ quantization_config=quant_config,
147
+ torch_dtype=torch.float16,
148
+ )
149
+
150
+ quant_config = DiffusersBitsAndBytesConfig(load_in_4bit=True,)
151
+
152
+ transformer_4bit = AutoModel.from_pretrained(
153
+ "black-forest-labs/FLUX.1-dev",
154
+ subfolder="transformer",
155
+ quantization_config=quant_config,
156
+ torch_dtype=torch.float16,
157
+ )
158
+ ```
159
+
160
+ By default, all the other modules such as `torch.nn.LayerNorm` are converted to `torch.float16`. You can change the data type of these modules with the `torch_dtype` parameter.
161
+
162
+ ```diff
163
+ transformer_4bit = AutoModel.from_pretrained(
164
+ "black-forest-labs/FLUX.1-dev",
165
+ subfolder="transformer",
166
+ quantization_config=quant_config,
167
+ + torch_dtype=torch.float32,
168
+ )
169
+ ```
170
+
171
+ Let's generate an image using our quantized models.
172
+
173
+ Setting `device_map="auto"` automatically fills all available space on the GPU(s) first, then the CPU, and finally, the hard drive (the absolute slowest option) if there is still not enough memory.
174
+
175
+ ```py
176
+ from diffusers import FluxPipeline
177
+
178
+ pipe = FluxPipeline.from_pretrained(
179
+ "black-forest-labs/FLUX.1-dev",
180
+ transformer=transformer_4bit,
181
+ text_encoder_2=text_encoder_2_4bit,
182
+ torch_dtype=torch.float16,
183
+ device_map="auto",
184
+ )
185
+
186
+ pipe_kwargs = {
187
+ "prompt": "A cat holding a sign that says hello world",
188
+ "height": 1024,
189
+ "width": 1024,
190
+ "guidance_scale": 3.5,
191
+ "num_inference_steps": 50,
192
+ "max_sequence_length": 512,
193
+ }
194
+
195
+ image = pipe(**pipe_kwargs, generator=torch.manual_seed(0),).images[0]
196
+ ```
197
+
198
+ <div class="flex justify-center">
199
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/quant-bnb/4bit.png"/>
200
+ </div>
201
+
202
+ When there is enough memory, you can also directly move the pipeline to the GPU with `.to("cuda")` and apply [`~DiffusionPipeline.enable_model_cpu_offload`] to optimize GPU memory usage.
203
+
204
+ Once a model is quantized, you can push the model to the Hub with the [`~ModelMixin.push_to_hub`] method. The quantization `config.json` file is pushed first, followed by the quantized model weights. You can also save the serialized 4-bit models locally with [`~ModelMixin.save_pretrained`].
205
+
206
+ </hfoption>
207
+ </hfoptions>
208
+
209
+ > [!WARNING]
210
+ > Training with 8-bit and 4-bit weights are only supported for training *extra* parameters.
211
+
212
+ Check your memory footprint with the `get_memory_footprint` method:
213
+
214
+ ```py
215
+ print(model.get_memory_footprint())
216
+ ```
217
+
218
+ Note that this only tells you the memory footprint of the model params and does _not_ estimate the inference memory requirements.
219
+
220
+ Quantized models can be loaded from the [`~ModelMixin.from_pretrained`] method without needing to specify the `quantization_config` parameters:
221
+
222
+ ```py
223
+ from diffusers import AutoModel, BitsAndBytesConfig
224
+
225
+ quantization_config = BitsAndBytesConfig(load_in_4bit=True)
226
+
227
+ model_4bit = AutoModel.from_pretrained(
228
+ "hf-internal-testing/flux.1-dev-nf4-pkg", subfolder="transformer"
229
+ )
230
+ ```
231
+
232
+ ## 8-bit (LLM.int8() algorithm)
233
+
234
+ > [!TIP]
235
+ > Learn more about the details of 8-bit quantization in this [blog post](https://huggingface.co/blog/hf-bitsandbytes-integration)!
236
+
237
+ This section explores some of the specific features of 8-bit models, such as outlier thresholds and skipping module conversion.
238
+
239
+ ### Outlier threshold
240
+
241
+ An "outlier" is a hidden state value greater than a certain threshold, and these values are computed in fp16. While the values are usually normally distributed ([-3.5, 3.5]), this distribution can be very different for large models ([-60, 6] or [6, 60]). 8-bit quantization works well for values ~5, but beyond that, there is a significant performance penalty. A good default threshold value is 6, but a lower threshold may be needed for more unstable models (small models or finetuning).
242
+
243
+ To find the best threshold for your model, we recommend experimenting with the `llm_int8_threshold` parameter in [`BitsAndBytesConfig`]:
244
+
245
+ ```py
246
+ from diffusers import AutoModel, BitsAndBytesConfig
247
+
248
+ quantization_config = BitsAndBytesConfig(
249
+ load_in_8bit=True, llm_int8_threshold=10,
250
+ )
251
+
252
+ model_8bit = AutoModel.from_pretrained(
253
+ "black-forest-labs/FLUX.1-dev",
254
+ subfolder="transformer",
255
+ quantization_config=quantization_config,
256
+ )
257
+ ```
258
+
259
+ ### Skip module conversion
260
+
261
+ For some models, you don't need to quantize every module to 8-bit which can actually cause instability. For example, for diffusion models like [Stable Diffusion 3](../api/pipelines/stable_diffusion/stable_diffusion_3), the `proj_out` module can be skipped using the `llm_int8_skip_modules` parameter in [`BitsAndBytesConfig`]:
262
+
263
+ ```py
264
+ from diffusers import SD3Transformer2DModel, BitsAndBytesConfig
265
+
266
+ quantization_config = BitsAndBytesConfig(
267
+ load_in_8bit=True, llm_int8_skip_modules=["proj_out"],
268
+ )
269
+
270
+ model_8bit = SD3Transformer2DModel.from_pretrained(
271
+ "stabilityai/stable-diffusion-3-medium-diffusers",
272
+ subfolder="transformer",
273
+ quantization_config=quantization_config,
274
+ )
275
+ ```
276
+
277
+
278
+ ## 4-bit (QLoRA algorithm)
279
+
280
+ > [!TIP]
281
+ > Learn more about its details in this [blog post](https://huggingface.co/blog/4bit-transformers-bitsandbytes).
282
+
283
+ This section explores some of the specific features of 4-bit models, such as changing the compute data type, using the Normal Float 4 (NF4) data type, and using nested quantization.
284
+
285
+
286
+ ### Compute data type
287
+
288
+ To speedup computation, you can change the data type from float32 (the default value) to bf16 using the `bnb_4bit_compute_dtype` parameter in [`BitsAndBytesConfig`]:
289
+
290
+ ```py
291
+ import torch
292
+ from diffusers import BitsAndBytesConfig
293
+
294
+ quantization_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16)
295
+ ```
296
+
297
+ ### Normal Float 4 (NF4)
298
+
299
+ NF4 is a 4-bit data type from the [QLoRA](https://hf.co/papers/2305.14314) paper, adapted for weights initialized from a normal distribution. You should use NF4 for training 4-bit base models. This can be configured with the `bnb_4bit_quant_type` parameter in the [`BitsAndBytesConfig`]:
300
+
301
+ ```py
302
+ from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig
303
+ from transformers import BitsAndBytesConfig as TransformersBitsAndBytesConfig
304
+
305
+ from diffusers import AutoModel
306
+ from transformers import T5EncoderModel
307
+
308
+ quant_config = TransformersBitsAndBytesConfig(
309
+ load_in_4bit=True,
310
+ bnb_4bit_quant_type="nf4",
311
+ )
312
+
313
+ text_encoder_2_4bit = T5EncoderModel.from_pretrained(
314
+ "black-forest-labs/FLUX.1-dev",
315
+ subfolder="text_encoder_2",
316
+ quantization_config=quant_config,
317
+ torch_dtype=torch.float16,
318
+ )
319
+
320
+ quant_config = DiffusersBitsAndBytesConfig(
321
+ load_in_4bit=True,
322
+ bnb_4bit_quant_type="nf4",
323
+ )
324
+
325
+ transformer_4bit = AutoModel.from_pretrained(
326
+ "black-forest-labs/FLUX.1-dev",
327
+ subfolder="transformer",
328
+ quantization_config=quant_config,
329
+ torch_dtype=torch.float16,
330
+ )
331
+ ```
332
+
333
+ For inference, the `bnb_4bit_quant_type` does not have a huge impact on performance. However, to remain consistent with the model weights, you should use the `bnb_4bit_compute_dtype` and `torch_dtype` values.
334
+
335
+ ### Nested quantization
336
+
337
+ Nested quantization is a technique that can save additional memory at no additional performance cost. This feature performs a second quantization of the already quantized weights to save an additional 0.4 bits/parameter.
338
+
339
+ ```py
340
+ from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig
341
+ from transformers import BitsAndBytesConfig as TransformersBitsAndBytesConfig
342
+
343
+ from diffusers import AutoModel
344
+ from transformers import T5EncoderModel
345
+
346
+ quant_config = TransformersBitsAndBytesConfig(
347
+ load_in_4bit=True,
348
+ bnb_4bit_use_double_quant=True,
349
+ )
350
+
351
+ text_encoder_2_4bit = T5EncoderModel.from_pretrained(
352
+ "black-forest-labs/FLUX.1-dev",
353
+ subfolder="text_encoder_2",
354
+ quantization_config=quant_config,
355
+ torch_dtype=torch.float16,
356
+ )
357
+
358
+ quant_config = DiffusersBitsAndBytesConfig(
359
+ load_in_4bit=True,
360
+ bnb_4bit_use_double_quant=True,
361
+ )
362
+
363
+ transformer_4bit = AutoModel.from_pretrained(
364
+ "black-forest-labs/FLUX.1-dev",
365
+ subfolder="transformer",
366
+ quantization_config=quant_config,
367
+ torch_dtype=torch.float16,
368
+ )
369
+ ```
370
+
371
+ ## Dequantizing `bitsandbytes` models
372
+
373
+ Once quantized, you can dequantize a model to its original precision, but this might result in a small loss of quality. Make sure you have enough GPU RAM to fit the dequantized model.
374
+
375
+ ```python
376
+ from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig
377
+ from transformers import BitsAndBytesConfig as TransformersBitsAndBytesConfig
378
+
379
+ from diffusers import AutoModel
380
+ from transformers import T5EncoderModel
381
+
382
+ quant_config = TransformersBitsAndBytesConfig(
383
+ load_in_4bit=True,
384
+ bnb_4bit_use_double_quant=True,
385
+ )
386
+
387
+ text_encoder_2_4bit = T5EncoderModel.from_pretrained(
388
+ "black-forest-labs/FLUX.1-dev",
389
+ subfolder="text_encoder_2",
390
+ quantization_config=quant_config,
391
+ torch_dtype=torch.float16,
392
+ )
393
+
394
+ quant_config = DiffusersBitsAndBytesConfig(
395
+ load_in_4bit=True,
396
+ bnb_4bit_use_double_quant=True,
397
+ )
398
+
399
+ transformer_4bit = AutoModel.from_pretrained(
400
+ "black-forest-labs/FLUX.1-dev",
401
+ subfolder="transformer",
402
+ quantization_config=quant_config,
403
+ torch_dtype=torch.float16,
404
+ )
405
+
406
+ text_encoder_2_4bit.dequantize()
407
+ transformer_4bit.dequantize()
408
+ ```
409
+
410
+ ## torch.compile
411
+
412
+ Speed up inference with `torch.compile`. Make sure you have the latest `bitsandbytes` installed and we also recommend installing [PyTorch nightly](https://pytorch.org/get-started/locally/).
413
+
414
+ <hfoptions id="bnb">
415
+ <hfoption id="8-bit">
416
+ ```py
417
+ torch._dynamo.config.capture_dynamic_output_shape_ops = True
418
+
419
+ quant_config = DiffusersBitsAndBytesConfig(load_in_8bit=True)
420
+ transformer_4bit = AutoModel.from_pretrained(
421
+ "black-forest-labs/FLUX.1-dev",
422
+ subfolder="transformer",
423
+ quantization_config=quant_config,
424
+ torch_dtype=torch.float16,
425
+ )
426
+ transformer_4bit.compile(fullgraph=True)
427
+ ```
428
+
429
+ </hfoption>
430
+ <hfoption id="4-bit">
431
+
432
+ ```py
433
+ quant_config = DiffusersBitsAndBytesConfig(load_in_4bit=True)
434
+ transformer_4bit = AutoModel.from_pretrained(
435
+ "black-forest-labs/FLUX.1-dev",
436
+ subfolder="transformer",
437
+ quantization_config=quant_config,
438
+ torch_dtype=torch.float16,
439
+ )
440
+ transformer_4bit.compile(fullgraph=True)
441
+ ```
442
+ </hfoption>
443
+ </hfoptions>
444
+
445
+ On an RTX 4090 with compilation, 4-bit Flux generation completed in 25.809 seconds versus 32.570 seconds without.
446
+
447
+ Check out the [benchmarking script](https://gist.github.com/sayakpaul/0db9d8eeeb3d2a0e5ed7cf0d9ca19b7d) for more details.
448
+
449
+ ## Resources
450
+
451
+ * [End-to-end notebook showing Flux.1 Dev inference in a free-tier Colab](https://gist.github.com/sayakpaul/c76bd845b48759e11687ac550b99d8b4)
452
+ * [Training](https://github.com/huggingface/diffusers/blob/8c661ea586bf11cb2440da740dd3c4cf84679b85/examples/dreambooth/README_hidream.md#using-quantization)
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/quantization/gguf.md ADDED
@@ -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
+
14
+ # GGUF
15
+
16
+ The GGUF file format is typically used to store models for inference with [GGML](https://github.com/ggerganov/ggml) and supports a variety of block wise quantization options. Diffusers supports loading checkpoints prequantized and saved in the GGUF format via `from_single_file` loading with Model classes. Loading GGUF checkpoints via Pipelines is currently not supported.
17
+
18
+ The following example will load the [FLUX.1 DEV](https://huggingface.co/black-forest-labs/FLUX.1-dev) transformer model using the GGUF Q2_K quantization variant.
19
+
20
+ Before starting please install gguf in your environment
21
+
22
+ ```shell
23
+ pip install -U gguf
24
+ ```
25
+
26
+ Since GGUF is a single file format, use [`~FromSingleFileMixin.from_single_file`] to load the model and pass in the [`GGUFQuantizationConfig`].
27
+
28
+ When using GGUF checkpoints, the quantized weights remain in a low memory `dtype`(typically `torch.uint8`) and are dynamically dequantized and cast to the configured `compute_dtype` during each module's forward pass through the model. The `GGUFQuantizationConfig` allows you to set the `compute_dtype`.
29
+
30
+ The functions used for dynamic dequantizatation are based on the great work done by [city96](https://github.com/city96/ComfyUI-GGUF), who created the Pytorch ports of the original [`numpy`](https://github.com/ggerganov/llama.cpp/blob/master/gguf-py/gguf/quants.py) implementation by [compilade](https://github.com/compilade).
31
+
32
+ ```python
33
+ import torch
34
+
35
+ from diffusers import FluxPipeline, FluxTransformer2DModel, GGUFQuantizationConfig
36
+
37
+ ckpt_path = (
38
+ "https://huggingface.co/city96/FLUX.1-dev-gguf/blob/main/flux1-dev-Q2_K.gguf"
39
+ )
40
+ transformer = FluxTransformer2DModel.from_single_file(
41
+ ckpt_path,
42
+ quantization_config=GGUFQuantizationConfig(compute_dtype=torch.bfloat16),
43
+ torch_dtype=torch.bfloat16,
44
+ )
45
+ pipe = FluxPipeline.from_pretrained(
46
+ "black-forest-labs/FLUX.1-dev",
47
+ transformer=transformer,
48
+ torch_dtype=torch.bfloat16,
49
+ )
50
+ pipe.enable_model_cpu_offload()
51
+ prompt = "A cat holding a sign that says hello world"
52
+ image = pipe(prompt, generator=torch.manual_seed(0)).images[0]
53
+ image.save("flux-gguf.png")
54
+ ```
55
+
56
+ ## Using Optimized CUDA Kernels with GGUF
57
+
58
+ Optimized CUDA kernels can accelerate GGUF quantized model inference by approximately 10%. This functionality requires a compatible GPU with `torch.cuda.get_device_capability` greater than 7 and the kernels library:
59
+
60
+ ```shell
61
+ pip install -U kernels
62
+ ```
63
+
64
+ Once installed, set `DIFFUSERS_GGUF_CUDA_KERNELS=true` to use optimized kernels when available. Note that CUDA kernels may introduce minor numerical differences compared to the original GGUF implementation, potentially causing subtle visual variations in generated images. To disable CUDA kernel usage, set the environment variable `DIFFUSERS_GGUF_CUDA_KERNELS=false`.
65
+
66
+ ## Supported Quantization Types
67
+
68
+ - BF16
69
+ - Q4_0
70
+ - Q4_1
71
+ - Q5_0
72
+ - Q5_1
73
+ - Q8_0
74
+ - Q2_K
75
+ - Q3_K
76
+ - Q4_K
77
+ - Q5_K
78
+ - Q6_K
79
+
80
+ ## Convert to GGUF
81
+
82
+ Use the Space below to convert a Diffusers checkpoint into the GGUF format for inference.
83
+ run conversion:
84
+
85
+ <iframe
86
+ src="https://diffusers-internal-dev-diffusers-to-gguf.hf.space"
87
+ frameborder="0"
88
+ width="850"
89
+ height="450"
90
+ ></iframe>
91
+
92
+
93
+ ```py
94
+ import torch
95
+
96
+ from diffusers import FluxPipeline, FluxTransformer2DModel, GGUFQuantizationConfig
97
+
98
+ ckpt_path = (
99
+ "https://huggingface.co/sayakpaul/different-lora-from-civitai/blob/main/flux_dev_diffusers-q4_0.gguf"
100
+ )
101
+ transformer = FluxTransformer2DModel.from_single_file(
102
+ ckpt_path,
103
+ quantization_config=GGUFQuantizationConfig(compute_dtype=torch.bfloat16),
104
+ config="black-forest-labs/FLUX.1-dev",
105
+ subfolder="transformer",
106
+ torch_dtype=torch.bfloat16,
107
+ )
108
+ pipe = FluxPipeline.from_pretrained(
109
+ "black-forest-labs/FLUX.1-dev",
110
+ transformer=transformer,
111
+ torch_dtype=torch.bfloat16,
112
+ )
113
+ pipe.enable_model_cpu_offload()
114
+ prompt = "A cat holding a sign that says hello world"
115
+ image = pipe(prompt, generator=torch.manual_seed(0)).images[0]
116
+ image.save("flux-gguf.png")
117
+ ```
118
+
119
+ When using Diffusers format GGUF checkpoints, it's a must to provide the model `config` path. If the
120
+ model config resides in a `subfolder`, that needs to be specified, too.
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/quantization/modelopt.md ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # NVIDIA ModelOpt
13
+
14
+ [NVIDIA-ModelOpt](https://github.com/NVIDIA/TensorRT-Model-Optimizer) is a unified library of state-of-the-art model optimization techniques like quantization, pruning, distillation, speculative decoding, etc. It compresses deep learning models for downstream deployment frameworks like TensorRT-LLM or TensorRT to optimize inference speed.
15
+
16
+ Before you begin, make sure you have nvidia_modelopt installed.
17
+
18
+ ```bash
19
+ pip install -U "nvidia_modelopt[hf]"
20
+ ```
21
+
22
+ Quantize a model by passing [`NVIDIAModelOptConfig`] to [`~ModelMixin.from_pretrained`] (you can also load pre-quantized models). This works for any model in any modality, as long as it supports loading with [Accelerate](https://hf.co/docs/accelerate/index) and contains `torch.nn.Linear` layers.
23
+
24
+ The example below only quantizes the weights to FP8.
25
+
26
+ ```python
27
+ import torch
28
+ from diffusers import AutoModel, SanaPipeline, NVIDIAModelOptConfig
29
+
30
+ model_id = "Efficient-Large-Model/Sana_600M_1024px_diffusers"
31
+ dtype = torch.bfloat16
32
+
33
+ quantization_config = NVIDIAModelOptConfig(quant_type="FP8", quant_method="modelopt")
34
+ transformer = AutoModel.from_pretrained(
35
+ model_id,
36
+ subfolder="transformer",
37
+ quantization_config=quantization_config,
38
+ torch_dtype=dtype,
39
+ )
40
+ pipe = SanaPipeline.from_pretrained(
41
+ model_id,
42
+ transformer=transformer,
43
+ torch_dtype=dtype,
44
+ )
45
+ pipe.to("cuda")
46
+
47
+ print(f"Pipeline memory usage: {torch.cuda.max_memory_reserved() / 1024**3:.3f} GB")
48
+
49
+ prompt = "A cat holding a sign that says hello world"
50
+ image = pipe(
51
+ prompt, num_inference_steps=50, guidance_scale=4.5, max_sequence_length=512
52
+ ).images[0]
53
+ image.save("output.png")
54
+ ```
55
+
56
+ > **Note:**
57
+ >
58
+ > The quantization methods in NVIDIA-ModelOpt are designed to reduce the memory footprint of model weights using various QAT (Quantization-Aware Training) and PTQ (Post-Training Quantization) techniques while maintaining model performance. However, the actual performance gain during inference depends on the deployment framework (e.g., TRT-LLM, TensorRT) and the specific hardware configuration.
59
+ >
60
+ > More details can be found [here](https://github.com/NVIDIA/TensorRT-Model-Optimizer/tree/main/examples).
61
+
62
+ ## NVIDIAModelOptConfig
63
+
64
+ The `NVIDIAModelOptConfig` class accepts three parameters:
65
+ - `quant_type`: A string value mentioning one of the quantization types below.
66
+ - `modules_to_not_convert`: A list of module full/partial module names for which quantization should not be performed. For example, to not perform any quantization of the [`SD3Transformer2DModel`]'s pos_embed projection blocks, one would specify: `modules_to_not_convert=["pos_embed.proj.weight"]`.
67
+ - `disable_conv_quantization`: A boolean value which when set to `True` disables quantization for all convolutional layers in the model. This is useful as channel and block quantization generally don't work well with convolutional layers (used with INT4, NF4, NVFP4). If you want to disable quantization for specific convolutional layers, use `modules_to_not_convert` instead.
68
+ - `algorithm`: The algorithm to use for determining scale, defaults to `"max"`. You can check modelopt documentation for more algorithms and details.
69
+ - `forward_loop`: The forward loop function to use for calibrating activation during quantization. If not provided, it relies on static scale values computed using the weights only.
70
+ - `kwargs`: A dict of keyword arguments to pass to the underlying quantization method which will be invoked based on `quant_type`.
71
+
72
+ ## Supported quantization types
73
+
74
+ ModelOpt supports weight-only, channel and block quantization int8, fp8, int4, nf4, and nvfp4. The quantization methods are designed to reduce the memory footprint of the model weights while maintaining the performance of the model during inference.
75
+
76
+ Weight-only quantization stores the model weights in a specific low-bit data type but performs computation with a higher-precision data type, like `bfloat16`. This lowers the memory requirements from model weights but retains the memory peaks for activation computation.
77
+
78
+ The quantization methods supported are as follows:
79
+
80
+ | **Quantization Type** | **Supported Schemes** | **Required Kwargs** | **Additional Notes** |
81
+ |-----------------------|-----------------------|---------------------|----------------------|
82
+ | **INT8** | `int8 weight only`, `int8 channel quantization`, `int8 block quantization` | `quant_type`, `quant_type + channel_quantize`, `quant_type + channel_quantize + block_quantize` |
83
+ | **FP8** | `fp8 weight only`, `fp8 channel quantization`, `fp8 block quantization` | `quant_type`, `quant_type + channel_quantize`, `quant_type + channel_quantize + block_quantize` |
84
+ | **INT4** | `int4 weight only`, `int4 block quantization` | `quant_type`, `quant_type + channel_quantize + block_quantize` | `channel_quantize = -1 is only supported for now`|
85
+ | **NF4** | `nf4 weight only`, `nf4 double block quantization` | `quant_type`, `quant_type + channel_quantize + block_quantize + scale_channel_quantize` + `scale_block_quantize` | `channel_quantize = -1 and scale_channel_quantize = -1 are only supported for now` |
86
+ | **NVFP4** | `nvfp4 weight only`, `nvfp4 block quantization` | `quant_type`, `quant_type + channel_quantize + block_quantize` | `channel_quantize = -1 is only supported for now`|
87
+
88
+
89
+ Refer to the [official modelopt documentation](https://nvidia.github.io/TensorRT-Model-Optimizer/) for a better understanding of the available quantization methods and the exhaustive list of configuration options available.
90
+
91
+ ## Serializing and Deserializing quantized models
92
+
93
+ To serialize a quantized model in a given dtype, first load the model with the desired quantization dtype and then save it using the [`~ModelMixin.save_pretrained`] method.
94
+
95
+ ```python
96
+ import torch
97
+ from diffusers import AutoModel, NVIDIAModelOptConfig
98
+ from modelopt.torch.opt import enable_huggingface_checkpointing
99
+
100
+ enable_huggingface_checkpointing()
101
+
102
+ model_id = "Efficient-Large-Model/Sana_600M_1024px_diffusers"
103
+ quant_config_fp8 = {"quant_type": "FP8", "quant_method": "modelopt"}
104
+ quant_config_fp8 = NVIDIAModelOptConfig(**quant_config_fp8)
105
+ model = AutoModel.from_pretrained(
106
+ model_id,
107
+ subfolder="transformer",
108
+ quantization_config=quant_config_fp8,
109
+ torch_dtype=torch.bfloat16,
110
+ )
111
+ model.save_pretrained('path/to/sana_fp8', safe_serialization=False)
112
+ ```
113
+
114
+ To load a serialized quantized model, use the [`~ModelMixin.from_pretrained`] method.
115
+
116
+ ```python
117
+ import torch
118
+ from diffusers import AutoModel, NVIDIAModelOptConfig, SanaPipeline
119
+ from modelopt.torch.opt import enable_huggingface_checkpointing
120
+
121
+ enable_huggingface_checkpointing()
122
+
123
+ quantization_config = NVIDIAModelOptConfig(quant_type="FP8", quant_method="modelopt")
124
+ transformer = AutoModel.from_pretrained(
125
+ "path/to/sana_fp8",
126
+ subfolder="transformer",
127
+ quantization_config=quantization_config,
128
+ torch_dtype=torch.bfloat16,
129
+ )
130
+ pipe = SanaPipeline.from_pretrained(
131
+ "Efficient-Large-Model/Sana_600M_1024px_diffusers",
132
+ transformer=transformer,
133
+ torch_dtype=torch.bfloat16,
134
+ )
135
+ pipe.to("cuda")
136
+ prompt = "A cat holding a sign that says hello world"
137
+ image = pipe(
138
+ prompt, num_inference_steps=50, guidance_scale=4.5, max_sequence_length=512
139
+ ).images[0]
140
+ image.save("output.png")
141
+ ```
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/quantization/overview.md ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
14
+ # Getting started
15
+
16
+ Quantization focuses on representing data with fewer bits while also trying to preserve the precision of the original data. This often means converting a data type to represent the same information with fewer bits. For example, if your model weights are stored as 32-bit floating points and they're quantized to 16-bit floating points, this halves the model size which makes it easier to store and reduces memory usage. Lower precision can also speedup inference because it takes less time to perform calculations with fewer bits.
17
+
18
+ Diffusers supports multiple quantization backends to make large diffusion models like [Flux](../api/pipelines/flux) more accessible. This guide shows how to use the [`~quantizers.PipelineQuantizationConfig`] class to quantize a pipeline during its initialization from a pretrained or non-quantized checkpoint.
19
+
20
+ ## Pipeline-level quantization
21
+
22
+ There are two ways to use [`~quantizers.PipelineQuantizationConfig`] depending on how much customization you want to apply to the quantization configuration.
23
+
24
+ - for basic use cases, define the `quant_backend`, `quant_kwargs`, and `components_to_quantize` arguments
25
+ - for granular quantization control, define a `quant_mapping` that provides the quantization configuration for individual model components
26
+
27
+ ### Basic quantization
28
+
29
+ Initialize [`~quantizers.PipelineQuantizationConfig`] with the following parameters.
30
+
31
+ - `quant_backend` specifies which quantization backend to use. Currently supported backends include: `bitsandbytes_4bit`, `bitsandbytes_8bit`, `gguf`, `quanto`, and `torchao`.
32
+ - `quant_kwargs` specifies the quantization arguments to use.
33
+
34
+ > [!TIP]
35
+ > These `quant_kwargs` arguments are different for each backend. Refer to the [Quantization API](../api/quantization) docs to view the arguments for each backend.
36
+
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.
40
+
41
+ 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`.
42
+
43
+ ```py
44
+ import torch
45
+ from diffusers import DiffusionPipeline
46
+ from diffusers.quantizers import PipelineQuantizationConfig
47
+
48
+ pipeline_quant_config = PipelineQuantizationConfig(
49
+ quant_backend="bitsandbytes_4bit",
50
+ quant_kwargs={"load_in_4bit": True, "bnb_4bit_quant_type": "nf4", "bnb_4bit_compute_dtype": torch.bfloat16},
51
+ components_to_quantize=["transformer", "text_encoder_2"],
52
+ )
53
+ ```
54
+
55
+ Pass the `pipeline_quant_config` to [`~DiffusionPipeline.from_pretrained`] to quantize the pipeline.
56
+
57
+ ```py
58
+ pipe = DiffusionPipeline.from_pretrained(
59
+ "black-forest-labs/FLUX.1-dev",
60
+ quantization_config=pipeline_quant_config,
61
+ torch_dtype=torch.bfloat16,
62
+ ).to("cuda")
63
+
64
+ image = pipe("photo of a cute dog").images[0]
65
+ ```
66
+
67
+
68
+ ### Advanced quantization
69
+
70
+ The `quant_mapping` argument provides more options for how to quantize each individual component in a pipeline, like combining different quantization backends.
71
+
72
+ Initialize [`~quantizers.PipelineQuantizationConfig`] and pass a `quant_mapping` to it. The `quant_mapping` allows you to specify the quantization options for each component in the pipeline such as the transformer and text encoder.
73
+
74
+ The example below uses two quantization backends, [`~quantizers.quantization_config.QuantoConfig`] and [`transformers.BitsAndBytesConfig`], for the transformer and text encoder.
75
+
76
+ ```py
77
+ import torch
78
+ from diffusers import DiffusionPipeline
79
+ from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig
80
+ from diffusers.quantizers.quantization_config import QuantoConfig
81
+ from diffusers.quantizers import PipelineQuantizationConfig
82
+ from transformers import BitsAndBytesConfig as TransformersBitsAndBytesConfig
83
+
84
+ pipeline_quant_config = PipelineQuantizationConfig(
85
+ quant_mapping={
86
+ "transformer": QuantoConfig(weights_dtype="int8"),
87
+ "text_encoder_2": TransformersBitsAndBytesConfig(
88
+ load_in_4bit=True, compute_dtype=torch.bfloat16
89
+ ),
90
+ }
91
+ )
92
+ ```
93
+
94
+ There is a separate bitsandbytes backend in [Transformers](https://huggingface.co/docs/transformers/main_classes/quantization#transformers.BitsAndBytesConfig). You need to import and use [`transformers.BitsAndBytesConfig`] for components that come from Transformers. For example, `text_encoder_2` in [`FluxPipeline`] is a [`~transformers.T5EncoderModel`] from Transformers so you need to use [`transformers.BitsAndBytesConfig`] instead of [`diffusers.BitsAndBytesConfig`].
95
+
96
+ > [!TIP]
97
+ > Use the [basic quantization](#basic-quantization) method above if you don't want to manage these distinct imports or aren't sure where each pipeline component comes from.
98
+
99
+ ```py
100
+ import torch
101
+ from diffusers import DiffusionPipeline
102
+ from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig
103
+ from diffusers.quantizers import PipelineQuantizationConfig
104
+ from transformers import BitsAndBytesConfig as TransformersBitsAndBytesConfig
105
+
106
+ pipeline_quant_config = PipelineQuantizationConfig(
107
+ quant_mapping={
108
+ "transformer": DiffusersBitsAndBytesConfig(load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16),
109
+ "text_encoder_2": TransformersBitsAndBytesConfig(
110
+ load_in_4bit=True, compute_dtype=torch.bfloat16
111
+ ),
112
+ }
113
+ )
114
+ ```
115
+
116
+ Pass the `pipeline_quant_config` to [`~DiffusionPipeline.from_pretrained`] to quantize the pipeline.
117
+
118
+ ```py
119
+ pipe = DiffusionPipeline.from_pretrained(
120
+ "black-forest-labs/FLUX.1-dev",
121
+ quantization_config=pipeline_quant_config,
122
+ torch_dtype=torch.bfloat16,
123
+ ).to("cuda")
124
+
125
+ image = pipe("photo of a cute dog").images[0]
126
+ ```
127
+
128
+ ## Resources
129
+
130
+ Check out the resources below to learn more about quantization.
131
+
132
+ - If you are new to quantization, we recommend checking out the following beginner-friendly courses in collaboration with DeepLearning.AI.
133
+
134
+ - [Quantization Fundamentals with Hugging Face](https://www.deeplearning.ai/short-courses/quantization-fundamentals-with-hugging-face/)
135
+ - [Quantization in Depth](https://www.deeplearning.ai/short-courses/quantization-in-depth/)
136
+
137
+ - Refer to the [Contribute new quantization method guide](https://huggingface.co/docs/transformers/main/en/quantization/contribute) if you're interested in adding a new quantization method.
138
+
139
+ - The Transformers quantization [Overview](https://huggingface.co/docs/transformers/quantization/overview#when-to-use-what) provides an overview of the pros and cons of different quantization backends.
140
+
141
+ - Read the [Exploring Quantization Backends in Diffusers](https://huggingface.co/blog/diffusers-quantization) blog post for a brief introduction to each quantization backend, how to choose a backend, and combining quantization with other memory optimizations.
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/quantization/quanto.md ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
14
+ # Quanto
15
+
16
+ [Quanto](https://github.com/huggingface/optimum-quanto) is a PyTorch quantization backend for [Optimum](https://huggingface.co/docs/optimum/en/index). It has been designed with versatility and simplicity in mind:
17
+
18
+ - All features are available in eager mode (works with non-traceable models)
19
+ - Supports quantization aware training
20
+ - Quantized models are compatible with `torch.compile`
21
+ - Quantized models are Device agnostic (e.g CUDA,XPU,MPS,CPU)
22
+
23
+ In order to use the Quanto backend, you will first need to install `optimum-quanto>=0.2.6` and `accelerate`
24
+
25
+ ```shell
26
+ pip install optimum-quanto accelerate
27
+ ```
28
+
29
+ Now you can quantize a model by passing the `QuantoConfig` object to the `from_pretrained()` method. Although the Quanto library does allow quantizing `nn.Conv2d` and `nn.LayerNorm` modules, currently, Diffusers only supports quantizing the weights in the `nn.Linear` layers of a model. The following snippet demonstrates how to apply `float8` quantization with Quanto.
30
+
31
+ ```python
32
+ import torch
33
+ from diffusers import FluxTransformer2DModel, QuantoConfig
34
+
35
+ model_id = "black-forest-labs/FLUX.1-dev"
36
+ quantization_config = QuantoConfig(weights_dtype="float8")
37
+ transformer = FluxTransformer2DModel.from_pretrained(
38
+ model_id,
39
+ subfolder="transformer",
40
+ quantization_config=quantization_config,
41
+ torch_dtype=torch.bfloat16,
42
+ )
43
+
44
+ pipe = FluxPipeline.from_pretrained(model_id, transformer=transformer, torch_dtype=torch_dtype)
45
+ pipe.to("cuda")
46
+
47
+ prompt = "A cat holding a sign that says hello world"
48
+ image = pipe(
49
+ prompt, num_inference_steps=50, guidance_scale=4.5, max_sequence_length=512
50
+ ).images[0]
51
+ image.save("output.png")
52
+ ```
53
+
54
+ ## Skipping Quantization on specific modules
55
+
56
+ It is possible to skip applying quantization on certain modules using the `modules_to_not_convert` argument in the `QuantoConfig`. Please ensure that the modules passed in to this argument match the keys of the modules in the `state_dict`
57
+
58
+ ```python
59
+ import torch
60
+ from diffusers import FluxTransformer2DModel, QuantoConfig
61
+
62
+ model_id = "black-forest-labs/FLUX.1-dev"
63
+ quantization_config = QuantoConfig(weights_dtype="float8", modules_to_not_convert=["proj_out"])
64
+ transformer = FluxTransformer2DModel.from_pretrained(
65
+ model_id,
66
+ subfolder="transformer",
67
+ quantization_config=quantization_config,
68
+ torch_dtype=torch.bfloat16,
69
+ )
70
+ ```
71
+
72
+ ## Using `from_single_file` with the Quanto Backend
73
+
74
+ `QuantoConfig` is compatible with `~FromOriginalModelMixin.from_single_file`.
75
+
76
+ ```python
77
+ import torch
78
+ from diffusers import FluxTransformer2DModel, QuantoConfig
79
+
80
+ ckpt_path = "https://huggingface.co/black-forest-labs/FLUX.1-dev/blob/main/flux1-dev.safetensors"
81
+ quantization_config = QuantoConfig(weights_dtype="float8")
82
+ transformer = FluxTransformer2DModel.from_single_file(ckpt_path, quantization_config=quantization_config, torch_dtype=torch.bfloat16)
83
+ ```
84
+
85
+ ## Saving Quantized models
86
+
87
+ Diffusers supports serializing Quanto models using the `~ModelMixin.save_pretrained` method.
88
+
89
+ The serialization and loading requirements are different for models quantized directly with the Quanto library and models quantized
90
+ with Diffusers using Quanto as the backend. It is currently not possible to load models quantized directly with Quanto into Diffusers using `~ModelMixin.from_pretrained`
91
+
92
+ ```python
93
+ import torch
94
+ from diffusers import FluxTransformer2DModel, QuantoConfig
95
+
96
+ model_id = "black-forest-labs/FLUX.1-dev"
97
+ quantization_config = QuantoConfig(weights_dtype="float8")
98
+ transformer = FluxTransformer2DModel.from_pretrained(
99
+ model_id,
100
+ subfolder="transformer",
101
+ quantization_config=quantization_config,
102
+ torch_dtype=torch.bfloat16,
103
+ )
104
+ # save quantized model to reuse
105
+ transformer.save_pretrained("<your quantized model save path>")
106
+
107
+ # you can reload your quantized model with
108
+ model = FluxTransformer2DModel.from_pretrained("<your quantized model save path>")
109
+ ```
110
+
111
+ ## Using `torch.compile` with Quanto
112
+
113
+ Currently the Quanto backend supports `torch.compile` for the following quantization types:
114
+
115
+ - `int8` weights
116
+
117
+ ```python
118
+ import torch
119
+ from diffusers import FluxPipeline, FluxTransformer2DModel, QuantoConfig
120
+
121
+ model_id = "black-forest-labs/FLUX.1-dev"
122
+ quantization_config = QuantoConfig(weights_dtype="int8")
123
+ transformer = FluxTransformer2DModel.from_pretrained(
124
+ model_id,
125
+ subfolder="transformer",
126
+ quantization_config=quantization_config,
127
+ torch_dtype=torch.bfloat16,
128
+ )
129
+ transformer = torch.compile(transformer, mode="max-autotune", fullgraph=True)
130
+
131
+ pipe = FluxPipeline.from_pretrained(
132
+ model_id, transformer=transformer, torch_dtype=torch_dtype
133
+ )
134
+ pipe.to("cuda")
135
+ images = pipe("A cat holding a sign that says hello").images[0]
136
+ images.save("flux-quanto-compile.png")
137
+ ```
138
+
139
+ ## Supported Quantization Types
140
+
141
+ ### Weights
142
+
143
+ - float8
144
+ - int8
145
+ - int4
146
+ - int2
147
+
148
+
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/quantization/torchao.md ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # torchao
13
+
14
+ [torchao](https://github.com/pytorch/ao) provides high-performance dtypes and optimizations based on quantization and sparsity for inference and training PyTorch models. It is supported for any model in any modality, as long as it supports loading with [Accelerate](https://hf.co/docs/accelerate/index) and contains `torch.nn.Linear` layers.
15
+
16
+ Make sure Pytorch 2.5+ and torchao are installed with the command below.
17
+
18
+ ```bash
19
+ uv pip install -U torch torchao
20
+ ```
21
+
22
+ Each quantization dtype is available as a separate instance of a [AOBaseConfig](https://docs.pytorch.org/ao/main/api_ref_quantization.html#inference-apis-for-quantize) class. This provides more flexible configuration options by exposing more available arguments.
23
+
24
+ Pass the `AOBaseConfig` of a quantization dtype, like [Int4WeightOnlyConfig](https://docs.pytorch.org/ao/main/generated/torchao.quantization.Int4WeightOnlyConfig) to [`TorchAoConfig`] in [`~ModelMixin.from_pretrained`].
25
+
26
+ ```py
27
+ import torch
28
+ from diffusers import DiffusionPipeline, PipelineQuantizationConfig, TorchAoConfig
29
+ from torchao.quantization import Int8WeightOnlyConfig
30
+
31
+ pipeline_quant_config = PipelineQuantizationConfig(
32
+ quant_mapping={"transformer": TorchAoConfig(Int8WeightOnlyConfig(group_size=128)))}
33
+ )
34
+ pipeline = DiffusionPipeline.from_pretrained(
35
+ "black-forest-labs/FLUX.1-dev",
36
+ quantzation_config=pipeline_quant_config,
37
+ torch_dtype=torch.bfloat16,
38
+ device_map="cuda"
39
+ )
40
+ ```
41
+
42
+ For simple use cases, you could also provide a string identifier in [`TorchAo`] as shown below.
43
+
44
+ ```py
45
+ import torch
46
+ from diffusers import DiffusionPipeline, PipelineQuantizationConfig, TorchAoConfig
47
+
48
+ pipeline_quant_config = PipelineQuantizationConfig(
49
+ quant_mapping={"transformer": TorchAoConfig("int8wo")}
50
+ )
51
+ pipeline = DiffusionPipeline.from_pretrained(
52
+ "black-forest-labs/FLUX.1-dev",
53
+ quantzation_config=pipeline_quant_config,
54
+ torch_dtype=torch.bfloat16,
55
+ device_map="cuda"
56
+ )
57
+ ```
58
+
59
+ ## torch.compile
60
+
61
+ torchao supports [torch.compile](../optimization/fp16#torchcompile) which can speed up inference with one line of code.
62
+
63
+ ```python
64
+ import torch
65
+ from diffusers import DiffusionPipeline, PipelineQuantizationConfig, TorchAoConfig
66
+ from torchao.quantization import Int4WeightOnlyConfig
67
+
68
+ pipeline_quant_config = PipelineQuantizationConfig(
69
+ quant_mapping={"transformer": TorchAoConfig(Int4WeightOnlyConfig(group_size=128)))}
70
+ )
71
+ pipeline = DiffusionPipeline.from_pretrained(
72
+ "black-forest-labs/FLUX.1-dev",
73
+ quantzation_config=pipeline_quant_config,
74
+ torch_dtype=torch.bfloat16,
75
+ device_map="cuda"
76
+ )
77
+
78
+ pipeline.transformer.compile(transformer, mode="max-autotune", fullgraph=True)
79
+ ```
80
+
81
+ Refer to this [table](https://github.com/huggingface/diffusers/pull/10009#issue-2688781450) for inference speed and memory usage benchmarks with Flux and CogVideoX. More benchmarks on various hardware are also available in the torchao [repository](https://github.com/pytorch/ao/tree/main/torchao/quantization#benchmarks).
82
+
83
+ > [!TIP]
84
+ > The FP8 post-training quantization schemes in torchao are effective for GPUs with compute capability of at least 8.9 (RTX-4090, Hopper, etc.). FP8 often provides the best speed, memory, and quality trade-off when generating images and videos. We recommend combining FP8 and torch.compile if your GPU is compatible.
85
+
86
+ ## autoquant
87
+
88
+ torchao provides [autoquant](https://docs.pytorch.org/ao/stable/generated/torchao.quantization.autoquant.html#torchao.quantization.autoquant) an automatic quantization API. Autoquantization chooses the best quantization strategy by comparing the performance of each strategy on chosen input types and shapes. This is only supported in Diffusers for individual models at the moment.
89
+
90
+ ```py
91
+ import torch
92
+ from diffusers import DiffusionPipeline
93
+ from torchao.quantization import autoquant
94
+
95
+ # Load the pipeline
96
+ pipeline = DiffusionPipeline.from_pretrained(
97
+ "black-forest-labs/FLUX.1-schnell",
98
+ torch_dtype=torch.bfloat16,
99
+ device_map="cuda"
100
+ )
101
+
102
+ transformer = autoquant(pipeline.transformer)
103
+ ```
104
+
105
+ ## Supported quantization types
106
+
107
+ torchao supports weight-only quantization and weight and dynamic-activation quantization for int8, float3-float8, and uint1-uint7.
108
+
109
+ Weight-only quantization stores the model weights in a specific low-bit data type but performs computation with a higher-precision data type, like `bfloat16`. This lowers the memory requirements from model weights but retains the memory peaks for activation computation.
110
+
111
+ Dynamic activation quantization stores the model weights in a low-bit dtype, while also quantizing the activations on-the-fly to save additional memory. This lowers the memory requirements from model weights, while also lowering the memory overhead from activation computations. However, this may come at a quality tradeoff at times, so it is recommended to test different models thoroughly.
112
+
113
+ The quantization methods supported are as follows:
114
+
115
+ | **Category** | **Full Function Names** | **Shorthands** |
116
+ |--------------|-------------------------|----------------|
117
+ | **Integer quantization** | `int4_weight_only`, `int8_dynamic_activation_int4_weight`, `int8_weight_only`, `int8_dynamic_activation_int8_weight` | `int4wo`, `int4dq`, `int8wo`, `int8dq` |
118
+ | **Floating point 8-bit quantization** | `float8_weight_only`, `float8_dynamic_activation_float8_weight`, `float8_static_activation_float8_weight` | `float8wo`, `float8wo_e5m2`, `float8wo_e4m3`, `float8dq`, `float8dq_e4m3`, `float8dq_e4m3_tensor`, `float8dq_e4m3_row` |
119
+ | **Floating point X-bit quantization** | `fpx_weight_only` | `fpX_eAwB` where `X` is the number of bits (1-7), `A` is exponent bits, and `B` is mantissa bits. Constraint: `X == A + B + 1` |
120
+ | **Unsigned Integer quantization** | `uintx_weight_only` | `uint1wo`, `uint2wo`, `uint3wo`, `uint4wo`, `uint5wo`, `uint6wo`, `uint7wo` |
121
+
122
+ Some quantization methods are aliases (for example, `int8wo` is the commonly used shorthand for `int8_weight_only`). This allows using the quantization methods described in the torchao docs as-is, while also making it convenient to remember their shorthand notations.
123
+
124
+ Refer to the [official torchao documentation](https://docs.pytorch.org/ao/stable/index.html) for a better understanding of the available quantization methods and the exhaustive list of configuration options available.
125
+
126
+ ## Serializing and Deserializing quantized models
127
+
128
+ To serialize a quantized model in a given dtype, first load the model with the desired quantization dtype and then save it using the [`~ModelMixin.save_pretrained`] method.
129
+
130
+ ```python
131
+ import torch
132
+ from diffusers import AutoModel, TorchAoConfig
133
+
134
+ quantization_config = TorchAoConfig("int8wo")
135
+ transformer = AutoModel.from_pretrained(
136
+ "black-forest-labs/Flux.1-Dev",
137
+ subfolder="transformer",
138
+ quantization_config=quantization_config,
139
+ torch_dtype=torch.bfloat16,
140
+ )
141
+ transformer.save_pretrained("/path/to/flux_int8wo", safe_serialization=False)
142
+ ```
143
+
144
+ To load a serialized quantized model, use the [`~ModelMixin.from_pretrained`] method.
145
+
146
+ ```python
147
+ import torch
148
+ from diffusers import FluxPipeline, AutoModel
149
+
150
+ transformer = AutoModel.from_pretrained("/path/to/flux_int8wo", torch_dtype=torch.bfloat16, use_safetensors=False)
151
+ pipe = FluxPipeline.from_pretrained("black-forest-labs/Flux.1-Dev", transformer=transformer, torch_dtype=torch.bfloat16)
152
+ pipe.to("cuda")
153
+
154
+ prompt = "A cat holding a sign that says hello world"
155
+ image = pipe(prompt, num_inference_steps=30, guidance_scale=7.0).images[0]
156
+ image.save("output.png")
157
+ ```
158
+
159
+ If you are using `torch<=2.6.0`, some quantization methods, such as `uint4wo`, cannot be loaded directly and may result in an `UnpicklingError` when trying to load the models, but work as expected when saving them. In order to work around this, one can load the state dict manually into the model. Note, however, that this requires using `weights_only=False` in `torch.load`, so it should be run only if the weights were obtained from a trustable source.
160
+
161
+ ```python
162
+ import torch
163
+ from accelerate import init_empty_weights
164
+ from diffusers import FluxPipeline, AutoModel, TorchAoConfig
165
+
166
+ # Serialize the model
167
+ transformer = AutoModel.from_pretrained(
168
+ "black-forest-labs/Flux.1-Dev",
169
+ subfolder="transformer",
170
+ quantization_config=TorchAoConfig("uint4wo"),
171
+ torch_dtype=torch.bfloat16,
172
+ )
173
+ transformer.save_pretrained("/path/to/flux_uint4wo", safe_serialization=False, max_shard_size="50GB")
174
+ # ...
175
+
176
+ # Load the model
177
+ state_dict = torch.load("/path/to/flux_uint4wo/diffusion_pytorch_model.bin", weights_only=False, map_location="cpu")
178
+ with init_empty_weights():
179
+ transformer = AutoModel.from_config("/path/to/flux_uint4wo/config.json")
180
+ transformer.load_state_dict(state_dict, strict=True, assign=True)
181
+ ```
182
+
183
+ > [!TIP]
184
+ > The [`AutoModel`] API is supported for PyTorch >= 2.6 as shown in the examples below.
185
+
186
+ ## Resources
187
+
188
+ - [TorchAO Quantization API](https://docs.pytorch.org/ao/stable/index.html)
189
+ - [Diffusers-TorchAO examples](https://github.com/sayakpaul/diffusers-torchao)
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/quicktour.md ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Quickstart
14
+
15
+ Diffusers is a library for developers and researchers that provides an easy inference API for generating images, videos and audio, as well as the building blocks for implementing new workflows.
16
+
17
+ Diffusers provides many optimizations out-of-the-box that makes it possible to load and run large models on setups with limited memory or to accelerate inference.
18
+
19
+ This Quickstart will give you an overview of Diffusers and get you up and generating quickly.
20
+
21
+ > [!TIP]
22
+ > Before you begin, make sure you have a Hugging Face [account](https://huggingface.co/join) in order to use gated models like [Flux](https://huggingface.co/black-forest-labs/FLUX.1-dev).
23
+
24
+ Follow the [Installation](./installation) guide to install Diffusers if it's not already installed.
25
+
26
+ ## DiffusionPipeline
27
+
28
+ A diffusion model combines multiple components to generate outputs in any modality based on an input, such as a text description, image or both.
29
+
30
+ For a standard text-to-image model:
31
+
32
+ 1. A text encoder turns a prompt into embeddings that guide the denoising process. Some models have more than one text encoder.
33
+ 2. A scheduler contains the algorithmic specifics for gradually denoising initial random noise into clean outputs. Different schedulers affect generation speed and quality.
34
+ 3. A UNet or diffusion transformer (DiT) is the workhorse of a diffusion model.
35
+
36
+ At each step, it performs the denoising predictions, such as how much noise to remove or the general direction in which to steer the noise to generate better quality outputs.
37
+
38
+ The UNet or DiT repeats this loop for a set amount of steps to generate the final output.
39
+
40
+ 4. A variational autoencoder (VAE) encodes and decodes pixels to a spatially compressed latent-space. *Latents* are compressed representations of an image and are more efficient to work with. The UNet or DiT operates on latents, and the clean latents at the end are decoded back into images.
41
+
42
+ The [`DiffusionPipeline`] packages all these components into a single class for inference. There are several arguments in [`~DiffusionPipeline.__call__`] you can change, such as `num_inference_steps`, that affect the diffusion process. Try different values and arguments to see how they change generation quality or speed.
43
+
44
+ Load a model with [`~DiffusionPipeline.from_pretrained`] and describe what you'd like to generate. The example below uses the default argument values.
45
+
46
+ <hfoptions id="diffusionpipeline">
47
+ <hfoption id="text-to-image">
48
+
49
+ Use `.images[0]` to access the generated image output.
50
+
51
+ ```py
52
+ import torch
53
+ from diffusers import DiffusionPipeline
54
+
55
+ pipeline = DiffusionPipeline.from_pretrained(
56
+ "Qwen/Qwen-Image", torch_dtype=torch.bfloat16, device_map="cuda"
57
+ )
58
+
59
+ prompt = """
60
+ cinematic film still of a cat sipping a margarita in a pool in Palm Springs, California
61
+ highly detailed, high budget hollywood movie, cinemascope, moody, epic, gorgeous, film grain
62
+ """
63
+ pipeline(prompt).images[0]
64
+ ```
65
+
66
+ </hfoption>
67
+ <hfoption id="text-to-video">
68
+
69
+ Use `.frames[0]` to access the generated video output and [`~utils.export_to_video`] to save the video.
70
+
71
+ ```py
72
+ import torch
73
+ from diffusers import AutoencoderKLWan, DiffusionPipeline
74
+ from diffusers.quantizers import PipelineQuantizationConfig
75
+ from diffusers.utils import export_to_video
76
+
77
+ vae = AutoencoderKLWan.from_pretrained(
78
+ "Wan-AI/Wan2.2-T2V-A14B-Diffusers",
79
+ subfolder="vae",
80
+ torch_dtype=torch.float32
81
+ )
82
+ pipeline = DiffusionPipeline.from_pretrained(
83
+ "Wan-AI/Wan2.2-T2V-A14B-Diffusers",
84
+ vae=vae
85
+ torch_dtype=torch.bfloat16,
86
+ device_map="cuda"
87
+ )
88
+
89
+ prompt = """
90
+ Cinematic video of a sleek cat lounging on a colorful inflatable in a crystal-clear turquoise pool in Palm Springs,
91
+ sipping a salt-rimmed margarita through a straw. Golden-hour sunlight glows over mid-century modern homes and swaying palms.
92
+ Shot in rich Sony a7S III: with moody, glamorous color grading, subtle lens flares, and soft vintage film grain.
93
+ Ripples shimmer as a warm desert breeze stirs the water, blending luxury and playful charm in an epic, gorgeously composed frame.
94
+ """
95
+ video = pipeline(prompt=prompt, num_frames=81, num_inference_steps=40).frames[0]
96
+ export_to_video(video, "output.mp4", fps=16)
97
+ ```
98
+
99
+ </hfoption>
100
+ </hfoptions>
101
+
102
+ ## LoRA
103
+
104
+ Adapters insert a small number of trainable parameters to the original base model. Only the inserted parameters are fine-tuned while the rest of the model weights remain frozen. This makes it fast and cheap to fine-tune a model on a new style. Among adapters, [LoRA's](./tutorials/using_peft_for_inference) are the most popular.
105
+
106
+ Add a LoRA to a pipeline with the [`~loaders.QwenImageLoraLoaderMixin.load_lora_weights`] method. Some LoRA's require a special word to trigger it, such as `Realism`, in the example below. Check a LoRA's model card to see if it requires a trigger word.
107
+
108
+ ```py
109
+ import torch
110
+ from diffusers import DiffusionPipeline
111
+
112
+ pipeline = DiffusionPipeline.from_pretrained(
113
+ "Qwen/Qwen-Image", torch_dtype=torch.bfloat16, device_map="cuda"
114
+ )
115
+ pipeline.load_lora_weights(
116
+ "flymy-ai/qwen-image-realism-lora",
117
+ )
118
+
119
+ prompt = """
120
+ super Realism cinematic film still of a cat sipping a margarita in a pool in Palm Springs in the style of umempart, California
121
+ highly detailed, high budget hollywood movie, cinemascope, moody, epic, gorgeous, film grain
122
+ """
123
+ pipeline(prompt).images[0]
124
+ ```
125
+
126
+ Check out the [LoRA](./tutorials/using_peft_for_inference) docs or Adapters section to learn more.
127
+
128
+ ## Quantization
129
+
130
+ [Quantization](./quantization/overview) stores data in fewer bits to reduce memory usage. It may also speed up inference because it takes less time to perform calculations with fewer bits.
131
+
132
+ Diffusers provides several quantization backends and picking one depends on your use case. For example, [bitsandbytes](./quantization/bitsandbytes) and [torchao](./quantization/torchao) are both simple and easy to use for inference, but torchao supports more [quantization types](./quantization/torchao#supported-quantization-types) like fp8.
133
+
134
+ Configure [`PipelineQuantizationConfig`] with the backend to use, the specific arguments (refer to the [API](./api/quantization) reference for available arguments) for that backend, and which components to quantize. The example below quantizes the model to 4-bits and only uses 14.93GB of memory.
135
+
136
+ ```py
137
+ import torch
138
+ from diffusers import DiffusionPipeline
139
+ from diffusers.quantizers import PipelineQuantizationConfig
140
+
141
+ quant_config = PipelineQuantizationConfig(
142
+ quant_backend="bitsandbytes_4bit",
143
+ quant_kwargs={"load_in_4bit": True, "bnb_4bit_quant_type": "nf4", "bnb_4bit_compute_dtype": torch.bfloat16},
144
+ components_to_quantize=["transformer", "text_encoder"],
145
+ )
146
+ pipeline = DiffusionPipeline.from_pretrained(
147
+ "Qwen/Qwen-Image",
148
+ torch_dtype=torch.bfloat16,
149
+ quantization_config=quant_config,
150
+ device_map="cuda"
151
+ )
152
+
153
+ prompt = """
154
+ cinematic film still of a cat sipping a margarita in a pool in Palm Springs, California
155
+ highly detailed, high budget hollywood movie, cinemascope, moody, epic, gorgeous, film grain
156
+ """
157
+ pipeline(prompt).images[0]
158
+ print(f"Max memory reserved: {torch.cuda.max_memory_allocated() / 1024**3:.2f} GB")
159
+ ```
160
+
161
+ Take a look at the [Quantization](./quantization/overview) section for more details.
162
+
163
+ ## Optimizations
164
+
165
+ > [!TIP]
166
+ > Optimization is dependent on hardware specs such as memory. Use this [Space](https://huggingface.co/spaces/diffusers/optimized-diffusers-code) to generate code examples that include all of Diffusers' available memory and speed optimization techniques for any model you're using.
167
+
168
+ Modern diffusion models are very large and have billions of parameters. The iterative denoising process is also computationally intensive and slow. Diffusers provides techniques for reducing memory usage and boosting inference speed. These techniques can be combined with quantization to optimize for both memory usage and inference speed.
169
+
170
+ ### Memory usage
171
+
172
+ The text encoders and UNet or DiT can use up as much as ~30GB of memory, exceeding the amount available on many free-tier or consumer GPUs.
173
+
174
+ Offloading stores weights that aren't currently used on the CPU and only moves them to the GPU when they're needed. There are a few offloading types and the example below uses [model offloading](./optimization/memory#model-offloading). This moves an entire model, like a text encoder or transformer, to the CPU when it isn't actively being used.
175
+
176
+ Call [`~DiffusionPipeline.enable_model_cpu_offload`] to activate it. By combining quantization and offloading, the following example only requires ~12.54GB of memory.
177
+
178
+ ```py
179
+ import torch
180
+ from diffusers import DiffusionPipeline
181
+ from diffusers.quantizers import PipelineQuantizationConfig
182
+
183
+ quant_config = PipelineQuantizationConfig(
184
+ quant_backend="bitsandbytes_4bit",
185
+ quant_kwargs={"load_in_4bit": True, "bnb_4bit_quant_type": "nf4", "bnb_4bit_compute_dtype": torch.bfloat16},
186
+ components_to_quantize=["transformer", "text_encoder"],
187
+ )
188
+ pipeline = DiffusionPipeline.from_pretrained(
189
+ "Qwen/Qwen-Image",
190
+ torch_dtype=torch.bfloat16,
191
+ quantization_config=quant_config,
192
+ device_map="cuda"
193
+ )
194
+ pipeline.enable_model_cpu_offload()
195
+
196
+ prompt = """
197
+ cinematic film still of a cat sipping a margarita in a pool in Palm Springs, California
198
+ highly detailed, high budget hollywood movie, cinemascope, moody, epic, gorgeous, film grain
199
+ """
200
+ pipeline(prompt).images[0]
201
+ print(f"Max memory reserved: {torch.cuda.max_memory_allocated() / 1024**3:.2f} GB")
202
+ ```
203
+
204
+ Refer to the [Reduce memory usage](./optimization/memory) docs to learn more about other memory reducing techniques.
205
+
206
+ ### Inference speed
207
+
208
+ The denoising loop performs a lot of computations and can be slow. Methods like [torch.compile](./optimization/fp16#torchcompile) increases inference speed by compiling the computations into an optimized kernel. Compilation is slow for the first generation but successive generations should be much faster.
209
+
210
+ The example below uses [regional compilation](./optimization/fp16#regional-compilation) to only compile small regions of a model. It reduces cold-start latency while also providing a runtime speed up.
211
+
212
+ Call [`~ModelMixin.compile_repeated_blocks`] on the model to activate it.
213
+
214
+ ```py
215
+ import torch
216
+ from diffusers import DiffusionPipeline
217
+
218
+ pipeline = DiffusionPipeline.from_pretrained(
219
+ "Qwen/Qwen-Image", torch_dtype=torch.bfloat16, device_map="cuda"
220
+ )
221
+
222
+ pipeline.transformer.compile_repeated_blocks(
223
+ fullgraph=True,
224
+ )
225
+ prompt = """
226
+ cinematic film still of a cat sipping a margarita in a pool in Palm Springs, California
227
+ highly detailed, high budget hollywood movie, cinemascope, moody, epic, gorgeous, film grain
228
+ """
229
+ pipeline(prompt).images[0]
230
+ ```
231
+
232
+ Check out the [Accelerate inference](./optimization/fp16) or [Caching](./optimization/cache) docs for more methods that speed up inference.
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/stable_diffusion.md ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Basic performance
16
+
17
+ Diffusion is a random process that is computationally demanding. You may need to run the [`DiffusionPipeline`] several times before getting a desired output. That's why it's important to carefully balance generation speed and memory usage in order to iterate faster,
18
+
19
+ This guide recommends some basic performance tips for using the [`DiffusionPipeline`]. Refer to the Inference Optimization section docs such as [Accelerate inference](./optimization/fp16) or [Reduce memory usage](./optimization/memory) for more detailed performance guides.
20
+
21
+ ## Memory usage
22
+
23
+ Reducing the amount of memory used indirectly speeds up generation and can help a model fit on device.
24
+
25
+ The [`~DiffusionPipeline.enable_model_cpu_offload`] method moves a model to the CPU when it is not in use to save GPU memory.
26
+
27
+ ```py
28
+ import torch
29
+ from diffusers import DiffusionPipeline
30
+
31
+ pipeline = DiffusionPipeline.from_pretrained(
32
+ "stabilityai/stable-diffusion-xl-base-1.0",
33
+ torch_dtype=torch.bfloat16,
34
+ device_map="cuda"
35
+ )
36
+ pipeline.enable_model_cpu_offload()
37
+
38
+ prompt = """
39
+ cinematic film still of a cat sipping a margarita in a pool in Palm Springs, California
40
+ highly detailed, high budget hollywood movie, cinemascope, moody, epic, gorgeous, film grain
41
+ """
42
+ pipeline(prompt).images[0]
43
+ print(f"Max memory reserved: {torch.cuda.max_memory_allocated() / 1024**3:.2f} GB")
44
+ ```
45
+
46
+ ## Inference speed
47
+
48
+ Denoising is the most computationally demanding process during diffusion. Methods that optimizes this process accelerates inference speed. Try the following methods for a speed up.
49
+
50
+ - Add `device_map="cuda"` to place the pipeline on a GPU. Placing a model on an accelerator, like a GPU, increases speed because it performs computations in parallel.
51
+ - Set `torch_dtype=torch.bfloat16` to execute the pipeline in half-precision. Reducing the data type precision increases speed because it takes less time to perform computations in a lower precision.
52
+
53
+ ```py
54
+ import torch
55
+ import time
56
+ from diffusers import DiffusionPipeline, DPMSolverMultistepScheduler
57
+
58
+ pipeline = DiffusionPipeline.from_pretrained(
59
+ "stabilityai/stable-diffusion-xl-base-1.0",
60
+ torch_dtype=torch.bfloat16,
61
+ device_map="cuda
62
+ )
63
+ ```
64
+
65
+ - Use a faster scheduler, such as [`DPMSolverMultistepScheduler`], which only requires ~20-25 steps.
66
+ - Set `num_inference_steps` to a lower value. Reducing the number of inference steps reduces the overall number of computations. However, this can result in lower generation quality.
67
+
68
+ ```py
69
+ pipeline.scheduler = DPMSolverMultistepScheduler.from_config(pipeline.scheduler.config)
70
+
71
+ prompt = """
72
+ cinematic film still of a cat sipping a margarita in a pool in Palm Springs, California
73
+ highly detailed, high budget hollywood movie, cinemascope, moody, epic, gorgeous, film grain
74
+ """
75
+
76
+ start_time = time.perf_counter()
77
+ image = pipeline(prompt).images[0]
78
+ end_time = time.perf_counter()
79
+
80
+ print(f"Image generation took {end_time - start_time:.3f} seconds")
81
+ ```
82
+
83
+ ## Generation quality
84
+
85
+ Many modern diffusion models deliver high-quality images out-of-the-box. However, you can still improve generation quality by trying the following.
86
+
87
+ - Try a more detailed and descriptive prompt. Include details such as the image medium, subject, style, and aesthetic. A negative prompt may also help by guiding a model away from undesirable features by using words like low quality or blurry.
88
+
89
+ ```py
90
+ import torch
91
+ from diffusers import DiffusionPipeline
92
+
93
+ pipeline = DiffusionPipeline.from_pretrained(
94
+ "stabilityai/stable-diffusion-xl-base-1.0",
95
+ torch_dtype=torch.bfloat16,
96
+ device_map="cuda"
97
+ )
98
+
99
+ prompt = """
100
+ cinematic film still of a cat sipping a margarita in a pool in Palm Springs, California
101
+ highly detailed, high budget hollywood movie, cinemascope, moody, epic, gorgeous, film grain
102
+ """
103
+ negative_prompt = "low quality, blurry, ugly, poor details"
104
+ pipeline(prompt, negative_prompt=negative_prompt).images[0]
105
+ ```
106
+
107
+ For more details about creating better prompts, take a look at the [Prompt techniques](./using-diffusers/weighted_prompts) doc.
108
+
109
+ - Try a different scheduler, like [`HeunDiscreteScheduler`] or [`LMSDiscreteScheduler`], that gives up generation speed for quality.
110
+
111
+ ```py
112
+ import torch
113
+ from diffusers import DiffusionPipeline, HeunDiscreteScheduler
114
+
115
+ pipeline = DiffusionPipeline.from_pretrained(
116
+ "stabilityai/stable-diffusion-xl-base-1.0",
117
+ torch_dtype=torch.bfloat16,
118
+ device_map="cuda"
119
+ )
120
+ pipeline.scheduler = HeunDiscreteScheduler.from_config(pipeline.scheduler.config)
121
+
122
+ prompt = """
123
+ cinematic film still of a cat sipping a margarita in a pool in Palm Springs, California
124
+ highly detailed, high budget hollywood movie, cinemascope, moody, epic, gorgeous, film grain
125
+ """
126
+ negative_prompt = "low quality, blurry, ugly, poor details"
127
+ pipeline(prompt, negative_prompt=negative_prompt).images[0]
128
+ ```
129
+
130
+ ## Next steps
131
+
132
+ Diffusers offers more advanced and powerful optimizations such as [group-offloading](./optimization/memory#group-offloading) and [regional compilation](./optimization/fp16#regional-compilation). To learn more about how to maximize performance, take a look at the Inference Optimization section.
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/training/adapt_a_model.md ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adapt a model to a new task
2
+
3
+ Many diffusion systems share the same components, allowing you to adapt a pretrained model for one task to an entirely different task.
4
+
5
+ This guide will show you how to adapt a pretrained text-to-image model for inpainting by initializing and modifying the architecture of a pretrained [`UNet2DConditionModel`].
6
+
7
+ ## Configure UNet2DConditionModel parameters
8
+
9
+ A [`UNet2DConditionModel`] by default accepts 4 channels in the [input sample](https://huggingface.co/docs/diffusers/v0.16.0/en/api/models#diffusers.UNet2DConditionModel.in_channels). For example, load a pretrained text-to-image model like [`stable-diffusion-v1-5/stable-diffusion-v1-5`](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5) and take a look at the number of `in_channels`:
10
+
11
+ ```py
12
+ from diffusers import StableDiffusionPipeline
13
+
14
+ pipeline = StableDiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", use_safetensors=True)
15
+ pipeline.unet.config["in_channels"]
16
+ 4
17
+ ```
18
+
19
+ Inpainting requires 9 channels in the input sample. You can check this value in a pretrained inpainting model like [`stable-diffusion-v1-5/stable-diffusion-inpainting`](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-inpainting):
20
+
21
+ ```py
22
+ from diffusers import StableDiffusionPipeline
23
+
24
+ pipeline = StableDiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-inpainting", use_safetensors=True)
25
+ pipeline.unet.config["in_channels"]
26
+ 9
27
+ ```
28
+
29
+ To adapt your text-to-image model for inpainting, you'll need to change the number of `in_channels` from 4 to 9.
30
+
31
+ Initialize a [`UNet2DConditionModel`] with the pretrained text-to-image model weights, and change `in_channels` to 9. Changing the number of `in_channels` means you need to set `ignore_mismatched_sizes=True` and `low_cpu_mem_usage=False` to avoid a size mismatch error because the shape is different now.
32
+
33
+ ```py
34
+ from diffusers import AutoModel
35
+
36
+ model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
37
+ unet = AutoModel.from_pretrained(
38
+ model_id,
39
+ subfolder="unet",
40
+ in_channels=9,
41
+ low_cpu_mem_usage=False,
42
+ ignore_mismatched_sizes=True,
43
+ use_safetensors=True,
44
+ )
45
+ ```
46
+
47
+ The pretrained weights of the other components from the text-to-image model are initialized from their checkpoints, but the input channel weights (`conv_in.weight`) of the `unet` are randomly initialized. It is important to finetune the model for inpainting because otherwise the model returns noise.
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/training/cogvideox.md ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # CogVideoX
13
+
14
+ CogVideoX is a text-to-video generation model focused on creating more coherent videos aligned with a prompt. It achieves this using several methods.
15
+
16
+ - a 3D variational autoencoder that compresses videos spatially and temporally, improving compression rate and video accuracy.
17
+
18
+ - an expert transformer block to help align text and video, and a 3D full attention module for capturing and creating spatially and temporally accurate videos.
19
+
20
+ The actual test of the video instruction dimension found that CogVideoX has good effects on consistent theme, dynamic information, consistent background, object information, smooth motion, color, scene, appearance style, and temporal style but cannot achieve good results with human action, spatial relationship, and multiple objects.
21
+
22
+ Finetuning with Diffusers can help make up for these poor results.
23
+
24
+ ## Data Preparation
25
+
26
+ The training scripts accepts data in two formats.
27
+
28
+ The first format is suited for small-scale training, and the second format uses a CSV format, which is more appropriate for streaming data for large-scale training. In the future, Diffusers will support the `<Video>` tag.
29
+
30
+ ### Small format
31
+
32
+ Two files where one file contains line-separated prompts and another file contains line-separated paths to video data (the path to video files must be relative to the path you pass when specifying `--instance_data_root`). Let's take a look at an example to understand this better!
33
+
34
+ Assume you've specified `--instance_data_root` as `/dataset`, and that this directory contains the files: `prompts.txt` and `videos.txt`.
35
+
36
+ The `prompts.txt` file should contain line-separated prompts:
37
+
38
+ ```
39
+ A black and white animated sequence featuring a rabbit, named Rabbity Ribfried, and an anthropomorphic goat in a musical, playful environment, showcasing their evolving interaction.
40
+ A black and white animated sequence on a ship's deck features a bulldog character, named Bully Bulldoger, showcasing exaggerated facial expressions and body language. The character progresses from confident to focused, then to strained and distressed, displaying a range of emotions as it navigates challenges. The ship's interior remains static in the background, with minimalistic details such as a bell and open door. The character's dynamic movements and changing expressions drive the narrative, with no camera movement to distract from its evolving reactions and physical gestures.
41
+ ...
42
+ ```
43
+
44
+ The `videos.txt` file should contain line-separate paths to video files. Note that the path should be _relative_ to the `--instance_data_root` directory.
45
+
46
+ ```
47
+ videos/00000.mp4
48
+ videos/00001.mp4
49
+ ...
50
+ ```
51
+
52
+ Overall, this is how your dataset would look like if you ran the `tree` command on the dataset root directory:
53
+
54
+ ```
55
+ /dataset
56
+ ├── prompts.txt
57
+ ├── videos.txt
58
+ ├── videos
59
+ ├── videos/00000.mp4
60
+ ├── videos/00001.mp4
61
+ ├── ...
62
+ ```
63
+
64
+ When using this format, the `--caption_column` must be `prompts.txt` and `--video_column` must be `videos.txt`.
65
+
66
+ ### Stream format
67
+
68
+ You could use a single CSV file. For the sake of this example, assume you have a `metadata.csv` file. The expected format is:
69
+
70
+ ```
71
+ <CAPTION_COLUMN>,<PATH_TO_VIDEO_COLUMN>
72
+ """A black and white animated sequence featuring a rabbit, named Rabbity Ribfried, and an anthropomorphic goat in a musical, playful environment, showcasing their evolving interaction.""","""00000.mp4"""
73
+ """A black and white animated sequence on a ship's deck features a bulldog character, named Bully Bulldoger, showcasing exaggerated facial expressions and body language. The character progresses from confident to focused, then to strained and distressed, displaying a range of emotions as it navigates challenges. The ship's interior remains static in the background, with minimalistic details such as a bell and open door. The character's dynamic movements and changing expressions drive the narrative, with no camera movement to distract from its evolving reactions and physical gestures.""","""00001.mp4"""
74
+ ...
75
+ ```
76
+
77
+ In this case, the `--instance_data_root` should be the location where the videos are stored and `--dataset_name` should be either a path to local folder or a [`~datasets.load_dataset`] compatible dataset hosted on the Hub. Assuming you have videos of Minecraft gameplay at `https://huggingface.co/datasets/my-awesome-username/minecraft-videos`, you would have to specify `my-awesome-username/minecraft-videos`.
78
+
79
+ When using this format, the `--caption_column` must be `<CAPTION_COLUMN>` and `--video_column` must be `<PATH_TO_VIDEO_COLUMN>`.
80
+
81
+ You are not strictly restricted to the CSV format. Any format works as long as the `load_dataset` method supports the file format to load a basic `<PATH_TO_VIDEO_COLUMN>` and `<CAPTION_COLUMN>`. The reason for going through these dataset organization gymnastics for loading video data is because `load_dataset` does not fully support all kinds of video formats.
82
+
83
+ > [!NOTE]
84
+ > CogVideoX works best with long and descriptive LLM-augmented prompts for video generation. We recommend pre-processing your videos by first generating a summary using a VLM and then augmenting the prompts with an LLM. To generate the above captions, we use [MiniCPM-V-26](https://huggingface.co/openbmb/MiniCPM-V-2_6) and [Llama-3.1-8B-Instruct](https://huggingface.co/meta-llama/Meta-Llama-3.1-8B-Instruct). A very barebones and no-frills example for this is available [here](https://gist.github.com/a-r-r-o-w/4dee20250e82f4e44690a02351324a4a). The official recommendation for augmenting prompts is [ChatGLM](https://huggingface.co/THUDM?search_models=chatglm) and a length of 50-100 words is considered good.
85
+
86
+ >![NOTE]
87
+ > It is expected that your dataset is already pre-processed. If not, some basic pre-processing can be done by playing with the following parameters:
88
+ > `--height`, `--width`, `--fps`, `--max_num_frames`, `--skip_frames_start` and `--skip_frames_end`.
89
+ > Presently, all videos in your dataset should contain the same number of video frames when using a training batch size > 1.
90
+
91
+ <!-- TODO: Implement frame packing in future to address above issue. -->
92
+
93
+ ## Training
94
+
95
+ You need to setup your development environment by installing the necessary requirements. The following packages are required:
96
+ - Torch 2.0 or above based on the training features you are utilizing (might require latest or nightly versions for quantized/deepspeed training)
97
+ - `pip install diffusers transformers accelerate peft huggingface_hub` for all things modeling and training related
98
+ - `pip install datasets decord` for loading video training data
99
+ - `pip install bitsandbytes` for using 8-bit Adam or AdamW optimizers for memory-optimized training
100
+ - `pip install wandb` optionally for monitoring training logs
101
+ - `pip install deepspeed` optionally for [DeepSpeed](https://github.com/microsoft/DeepSpeed) training
102
+ - `pip install prodigyopt` optionally if you would like to use the Prodigy optimizer for training
103
+
104
+ To make sure you can successfully run the latest versions of the example scripts, we highly recommend **installing from source** and keeping the install up to date as we update the example scripts frequently and install some example-specific requirements. To do this, execute the following steps in a new virtual environment:
105
+
106
+ Before running the script, make sure you install the library from source:
107
+ ```bash
108
+ git clone https://github.com/huggingface/diffusers
109
+ cd diffusers
110
+ pip install -e .
111
+ ```
112
+
113
+
114
+
115
+ Then navigate to the example folder containing the training script and install the required dependencies for the script you're using:
116
+
117
+ - PyTorch
118
+
119
+ ```bash
120
+ cd examples/cogvideo
121
+ pip install -r requirements.txt
122
+ ```
123
+
124
+ And initialize an [🤗 Accelerate](https://github.com/huggingface/accelerate/) environment with:
125
+
126
+ ```bash
127
+ accelerate config
128
+ ```
129
+
130
+ Or for a default accelerate configuration without answering questions about your environment
131
+
132
+ ```bash
133
+ accelerate config default
134
+ ```
135
+
136
+ Or if your environment doesn't support an interactive shell (e.g., a notebook)
137
+
138
+ ```python
139
+ from accelerate.utils import write_basic_config
140
+ write_basic_config()
141
+ ```
142
+
143
+ When running `accelerate config`, if you use torch.compile, there can be dramatic speedups. The PEFT library is used as a backend for LoRA training, so make sure to have `peft>=0.6.0` installed in your environment.
144
+
145
+ If you would like to push your model to the Hub after training is completed with a neat model card, make sure you're logged in:
146
+
147
+ ```bash
148
+ hf auth login
149
+
150
+ # Alternatively, you could upload your model manually using:
151
+ # hf upload my-cool-account-name/my-cool-lora-name /path/to/awesome/lora
152
+ ```
153
+
154
+ Make sure your data is prepared as described in [Data Preparation](#data-preparation). When ready, you can begin training!
155
+
156
+ Assuming you are training on 50 videos of a similar concept, we have found 1500-2000 steps to work well. The official recommendation, however, is 100 videos with a total of 4000 steps. Assuming you are training on a single GPU with a `--train_batch_size` of `1`:
157
+ - 1500 steps on 50 videos would correspond to `30` training epochs
158
+ - 4000 steps on 100 videos would correspond to `40` training epochs
159
+
160
+ ```bash
161
+ #!/bin/bash
162
+
163
+ GPU_IDS="0"
164
+
165
+ accelerate launch --gpu_ids $GPU_IDS examples/cogvideo/train_cogvideox_lora.py \
166
+ --pretrained_model_name_or_path THUDM/CogVideoX-2b \
167
+ --cache_dir <CACHE_DIR> \
168
+ --instance_data_root <PATH_TO_WHERE_VIDEO_FILES_ARE_STORED> \
169
+ --dataset_name my-awesome-name/my-awesome-dataset \
170
+ --caption_column <CAPTION_COLUMN> \
171
+ --video_column <PATH_TO_VIDEO_COLUMN> \
172
+ --id_token <ID_TOKEN> \
173
+ --validation_prompt "<ID_TOKEN> Spiderman swinging over buildings:::A panda, dressed in a small, red jacket and a tiny hat, sits on a wooden stool in a serene bamboo forest. The panda's fluffy paws strum a miniature acoustic guitar, producing soft, melodic tunes. Nearby, a few other pandas gather, watching curiously and some clapping in rhythm. Sunlight filters through the tall bamboo, casting a gentle glow on the scene. The panda's face is expressive, showing concentration and joy as it plays. The background includes a small, flowing stream and vibrant green foliage, enhancing the peaceful and magical atmosphere of this unique musical performance" \
174
+ --validation_prompt_separator ::: \
175
+ --num_validation_videos 1 \
176
+ --validation_epochs 10 \
177
+ --seed 42 \
178
+ --rank 64 \
179
+ --lora_alpha 64 \
180
+ --mixed_precision fp16 \
181
+ --output_dir /raid/aryan/cogvideox-lora \
182
+ --height 480 --width 720 --fps 8 --max_num_frames 49 --skip_frames_start 0 --skip_frames_end 0 \
183
+ --train_batch_size 1 \
184
+ --num_train_epochs 30 \
185
+ --checkpointing_steps 1000 \
186
+ --gradient_accumulation_steps 1 \
187
+ --learning_rate 1e-3 \
188
+ --lr_scheduler cosine_with_restarts \
189
+ --lr_warmup_steps 200 \
190
+ --lr_num_cycles 1 \
191
+ --enable_slicing \
192
+ --enable_tiling \
193
+ --optimizer Adam \
194
+ --adam_beta1 0.9 \
195
+ --adam_beta2 0.95 \
196
+ --max_grad_norm 1.0 \
197
+ --report_to wandb
198
+ ```
199
+
200
+ To better track our training experiments, we're using the following flags in the command above:
201
+ * `--report_to wandb` will ensure the training runs are tracked on Weights and Biases. To use it, be sure to install `wandb` with `pip install wandb`.
202
+ * `validation_prompt` and `validation_epochs` to allow the script to do a few validation inference runs. This allows us to qualitatively check if the training is progressing as expected.
203
+
204
+ Setting the `<ID_TOKEN>` is not necessary. From some limited experimentation, we found it works better (as it resembles [Dreambooth](https://huggingface.co/docs/diffusers/en/training/dreambooth) training) than without. When provided, the `<ID_TOKEN>` is appended to the beginning of each prompt. So, if your `<ID_TOKEN>` was `"DISNEY"` and your prompt was `"Spiderman swinging over buildings"`, the effective prompt used in training would be `"DISNEY Spiderman swinging over buildings"`. When not provided, you would either be training without any additional token or could augment your dataset to apply the token where you wish before starting the training.
205
+
206
+ > [!NOTE]
207
+ > You can pass `--use_8bit_adam` to reduce the memory requirements of training.
208
+
209
+ > [!IMPORTANT]
210
+ > The following settings have been tested at the time of adding CogVideoX LoRA training support:
211
+ > - Our testing was primarily done on CogVideoX-2b. We will work on CogVideoX-5b and CogVideoX-5b-I2V soon
212
+ > - One dataset comprised of 70 training videos of resolutions `200 x 480 x 720` (F x H x W). From this, by using frame skipping in data preprocessing, we created two smaller 49-frame and 16-frame datasets for faster experimentation and because the maximum limit recommended by the CogVideoX team is 49 frames. Out of the 70 videos, we created three groups of 10, 25 and 50 videos. All videos were similar in nature of the concept being trained.
213
+ > - 25+ videos worked best for training new concepts and styles.
214
+ > - We found that it is better to train with an identifier token that can be specified as `--id_token`. This is similar to Dreambooth-like training but normal finetuning without such a token works too.
215
+ > - Trained concept seemed to work decently well when combined with completely unrelated prompts. We expect even better results if CogVideoX-5B is finetuned.
216
+ > - The original repository uses a `lora_alpha` of `1`. We found this not suitable in many runs, possibly due to difference in modeling backends and training settings. Our recommendation is to set to the `lora_alpha` to either `rank` or `rank // 2`.
217
+ > - If you're training on data whose captions generate bad results with the original model, a `rank` of 64 and above is good and also the recommendation by the team behind CogVideoX. If the generations are already moderately good on your training captions, a `rank` of 16/32 should work. We found that setting the rank too low, say `4`, is not ideal and doesn't produce promising results.
218
+ > - The authors of CogVideoX recommend 4000 training steps and 100 training videos overall to achieve the best result. While that might yield the best results, we found from our limited experimentation that 2000 steps and 25 videos could also be sufficient.
219
+ > - When using the Prodigy optimizer for training, one can follow the recommendations from [this](https://huggingface.co/blog/sdxl_lora_advanced_script) blog. Prodigy tends to overfit quickly. From my very limited testing, I found a learning rate of `0.5` to be suitable in addition to `--prodigy_use_bias_correction`, `prodigy_safeguard_warmup` and `--prodigy_decouple`.
220
+ > - The recommended learning rate by the CogVideoX authors and from our experimentation with Adam/AdamW is between `1e-3` and `1e-4` for a dataset of 25+ videos.
221
+ >
222
+ > Note that our testing is not exhaustive due to limited time for exploration. Our recommendation would be to play around with the different knobs and dials to find the best settings for your data.
223
+
224
+ <!-- TODO: Test finetuning with CogVideoX-5b and CogVideoX-5b-I2V and update scripts accordingly -->
225
+
226
+ ## Inference
227
+
228
+ Once you have trained a lora model, the inference can be done simply loading the lora weights into the `CogVideoXPipeline`.
229
+
230
+ ```python
231
+ import torch
232
+ from diffusers import CogVideoXPipeline
233
+ from diffusers.utils import export_to_video
234
+
235
+ pipe = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-2b", torch_dtype=torch.float16)
236
+ # pipe.load_lora_weights("/path/to/lora/weights", adapter_name="cogvideox-lora") # Or,
237
+ pipe.load_lora_weights("my-awesome-hf-username/my-awesome-lora-name", adapter_name="cogvideox-lora") # If loading from the HF Hub
238
+ pipe.to("cuda")
239
+
240
+ # Assuming lora_alpha=32 and rank=64 for training. If different, set accordingly
241
+ pipe.set_adapters(["cogvideox-lora"], [32 / 64])
242
+
243
+ prompt = "A vast, shimmering ocean flows gracefully under a twilight sky, its waves undulating in a mesmerizing dance of blues and greens. The surface glints with the last rays of the setting sun, casting golden highlights that ripple across the water. Seagulls soar above, their cries blending with the gentle roar of the waves. The horizon stretches infinitely, where the ocean meets the sky in a seamless blend of hues. Close-ups reveal the intricate patterns of the waves, capturing the fluidity and dynamic beauty of the sea in motion."
244
+ frames = pipe(prompt, guidance_scale=6, use_dynamic_cfg=True).frames[0]
245
+ export_to_video(frames, "output.mp4", fps=8)
246
+ ```
247
+
248
+
249
+ ## Reduce memory usage
250
+
251
+ While testing using the diffusers library, all optimizations included in the diffusers library were enabled. This
252
+ scheme has not been tested for actual memory usage on devices outside of **NVIDIA A100 / H100** architectures.
253
+ Generally, this scheme can be adapted to all **NVIDIA Ampere architecture** and above devices. If optimizations are
254
+ disabled, memory consumption will multiply, with peak memory usage being about 3 times the value in the table.
255
+ However, speed will increase by about 3-4 times. You can selectively disable some optimizations, including:
256
+
257
+ ```
258
+ pipe.enable_sequential_cpu_offload()
259
+ pipe.vae.enable_slicing()
260
+ pipe.vae.enable_tiling()
261
+ ```
262
+
263
+ + For multi-GPU inference, the `enable_sequential_cpu_offload()` optimization needs to be disabled.
264
+ + Using INT8 models will slow down inference, which is done to accommodate lower-memory GPUs while maintaining minimal
265
+ video quality loss, though inference speed will significantly decrease.
266
+ + The CogVideoX-2B model was trained in `FP16` precision, and all CogVideoX-5B models were trained in `BF16` precision.
267
+ We recommend using the precision in which the model was trained for inference.
268
+ + [PytorchAO](https://github.com/pytorch/ao) and [Optimum-quanto](https://github.com/huggingface/optimum-quanto/) can be
269
+ used to quantize the text encoder, transformer, and VAE modules to reduce the memory requirements of CogVideoX. This
270
+ allows the model to run on free T4 Colabs or GPUs with smaller memory! Also, note that TorchAO quantization is fully
271
+ compatible with `torch.compile`, which can significantly improve inference speed. FP8 precision must be used on
272
+ devices with NVIDIA H100 and above, requiring source installation of `torch`, `torchao`, `diffusers`, and `accelerate`
273
+ Python packages. CUDA 12.4 is recommended.
274
+ + The inference speed tests also used the above memory optimization scheme. Without memory optimization, inference speed
275
+ increases by about 10%. Only the `diffusers` version of the model supports quantization.
276
+ + The model only supports English input; other languages can be translated into English for use via large model
277
+ refinement.
278
+ + The memory usage of model fine-tuning is tested in an `8 * H100` environment, and the program automatically
279
+ uses `Zero 2` optimization. If a specific number of GPUs is marked in the table, that number or more GPUs must be used
280
+ for fine-tuning.
281
+
282
+
283
+ | **Attribute** | **CogVideoX-2B** | **CogVideoX-5B** |
284
+ | ------------------------------------ | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- |
285
+ | **Model Name** | CogVideoX-2B | CogVideoX-5B |
286
+ | **Inference Precision** | FP16* (Recommended), BF16, FP32, FP8*, INT8, Not supported INT4 | BF16 (Recommended), FP16, FP32, FP8*, INT8, Not supported INT4 |
287
+ | **Single GPU Inference VRAM** | FP16: Using diffusers 12.5GB* INT8: Using diffusers with torchao 7.8GB* | BF16: Using diffusers 20.7GB* INT8: Using diffusers with torchao 11.4GB* |
288
+ | **Multi GPU Inference VRAM** | FP16: Using diffusers 10GB* | BF16: Using diffusers 15GB* |
289
+ | **Inference Speed** | Single A100: ~90 seconds, Single H100: ~45 seconds | Single A100: ~180 seconds, Single H100: ~90 seconds |
290
+ | **Fine-tuning Precision** | FP16 | BF16 |
291
+ | **Fine-tuning VRAM Consumption** | 47 GB (bs=1, LORA) 61 GB (bs=2, LORA) 62GB (bs=1, SFT) | 63 GB (bs=1, LORA) 80 GB (bs=2, LORA) 75GB (bs=1, SFT) |
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/training/controlnet.md ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # ControlNet
14
+
15
+ [ControlNet](https://hf.co/papers/2302.05543) models are adapters trained on top of another pretrained model. It allows for a greater degree of control over image generation by conditioning the model with an additional input image. The input image can be a canny edge, depth map, human pose, and many more.
16
+
17
+ If you're training on a GPU with limited vRAM, you should try enabling the `gradient_checkpointing`, `gradient_accumulation_steps`, and `mixed_precision` parameters in the training command. You can also reduce your memory footprint by using memory-efficient attention with [xFormers](../optimization/xformers).
18
+
19
+ This guide will explore the [train_controlnet.py](https://github.com/huggingface/diffusers/blob/main/examples/controlnet/train_controlnet.py) training script to help you become familiar with it, and how you can adapt it for your own use-case.
20
+
21
+ Before running the script, make sure you install the library from source:
22
+
23
+ ```bash
24
+ git clone https://github.com/huggingface/diffusers
25
+ cd diffusers
26
+ pip install .
27
+ ```
28
+
29
+ Then navigate to the example folder containing the training script and install the required dependencies for the script you're using:
30
+
31
+ ```bash
32
+ cd examples/controlnet
33
+ pip install -r requirements.txt
34
+ ```
35
+
36
+ > [!TIP]
37
+ > 🤗 Accelerate is a library for helping you train on multiple GPUs/TPUs or with mixed-precision. It'll automatically configure your training setup based on your hardware and environment. Take a look at the 🤗 Accelerate [Quick tour](https://huggingface.co/docs/accelerate/quicktour) to learn more.
38
+
39
+ Initialize an 🤗 Accelerate environment:
40
+
41
+ ```bash
42
+ accelerate config
43
+ ```
44
+
45
+ To setup a default 🤗 Accelerate environment without choosing any configurations:
46
+
47
+ ```bash
48
+ accelerate config default
49
+ ```
50
+
51
+ Or if your environment doesn't support an interactive shell, like a notebook, you can use:
52
+
53
+ ```py
54
+ from accelerate.utils import write_basic_config
55
+
56
+ write_basic_config()
57
+ ```
58
+
59
+ Lastly, if you want to train a model on your own dataset, take a look at the [Create a dataset for training](create_dataset) guide to learn how to create a dataset that works with the training script.
60
+
61
+ > [!TIP]
62
+ > The following sections highlight parts of the training script that are important for understanding how to modify it, but it doesn't cover every aspect of the script in detail. If you're interested in learning more, feel free to read through the [script](https://github.com/huggingface/diffusers/blob/main/examples/controlnet/train_controlnet.py) and let us know if you have any questions or concerns.
63
+
64
+ ## Script parameters
65
+
66
+ The training script provides many parameters to help you customize your training run. All of the parameters and their descriptions are found in the [`parse_args()`](https://github.com/huggingface/diffusers/blob/64603389da01082055a901f2883c4810d1144edb/examples/controlnet/train_controlnet.py#L231) function. This function provides default values for each parameter, such as the training batch size and learning rate, but you can also set your own values in the training command if you'd like.
67
+
68
+ For example, to speedup training with mixed precision using the fp16 format, add the `--mixed_precision` parameter to the training command:
69
+
70
+ ```bash
71
+ accelerate launch train_controlnet.py \
72
+ --mixed_precision="fp16"
73
+ ```
74
+
75
+ Many of the basic and important parameters are described in the [Text-to-image](text2image#script-parameters) training guide, so this guide just focuses on the relevant parameters for ControlNet:
76
+
77
+ - `--max_train_samples`: the number of training samples; this can be lowered for faster training, but if you want to stream really large datasets, you'll need to include this parameter and the `--streaming` parameter in your training command
78
+ - `--gradient_accumulation_steps`: number of update steps to accumulate before the backward pass; this allows you to train with a bigger batch size than your GPU memory can typically handle
79
+
80
+ ### Min-SNR weighting
81
+
82
+ The [Min-SNR](https://huggingface.co/papers/2303.09556) weighting strategy can help with training by rebalancing the loss to achieve faster convergence. The training script supports predicting `epsilon` (noise) or `v_prediction`, but Min-SNR is compatible with both prediction types. This weighting strategy is only supported by PyTorch.
83
+
84
+ Add the `--snr_gamma` parameter and set it to the recommended value of 5.0:
85
+
86
+ ```bash
87
+ accelerate launch train_controlnet.py \
88
+ --snr_gamma=5.0
89
+ ```
90
+
91
+ ## Training script
92
+
93
+ As with the script parameters, a general walkthrough of the training script is provided in the [Text-to-image](text2image#training-script) training guide. Instead, this guide takes a look at the relevant parts of the ControlNet script.
94
+
95
+ The training script has a [`make_train_dataset`](https://github.com/huggingface/diffusers/blob/64603389da01082055a901f2883c4810d1144edb/examples/controlnet/train_controlnet.py#L582) function for preprocessing the dataset with image transforms and caption tokenization. You'll see that in addition to the usual caption tokenization and image transforms, the script also includes transforms for the conditioning image.
96
+
97
+ > [!TIP]
98
+ > If you're streaming a dataset on a TPU, performance may be bottlenecked by the 🤗 Datasets library which is not optimized for images. To ensure maximum throughput, you're encouraged to explore other dataset formats like [WebDataset](https://webdataset.github.io/webdataset/), [TorchData](https://github.com/pytorch/data), and [TensorFlow Datasets](https://www.tensorflow.org/datasets/tfless_tfds).
99
+
100
+ ```py
101
+ conditioning_image_transforms = transforms.Compose(
102
+ [
103
+ transforms.Resize(args.resolution, interpolation=transforms.InterpolationMode.BILINEAR),
104
+ transforms.CenterCrop(args.resolution),
105
+ transforms.ToTensor(),
106
+ ]
107
+ )
108
+ ```
109
+
110
+ Within the [`main()`](https://github.com/huggingface/diffusers/blob/64603389da01082055a901f2883c4810d1144edb/examples/controlnet/train_controlnet.py#L713) function, you'll find the code for loading the tokenizer, text encoder, scheduler and models. This is also where the ControlNet model is loaded either from existing weights or randomly initialized from a UNet:
111
+
112
+ ```py
113
+ if args.controlnet_model_name_or_path:
114
+ logger.info("Loading existing controlnet weights")
115
+ controlnet = ControlNetModel.from_pretrained(args.controlnet_model_name_or_path)
116
+ else:
117
+ logger.info("Initializing controlnet weights from unet")
118
+ controlnet = ControlNetModel.from_unet(unet)
119
+ ```
120
+
121
+ The [optimizer](https://github.com/huggingface/diffusers/blob/64603389da01082055a901f2883c4810d1144edb/examples/controlnet/train_controlnet.py#L871) is set up to update the ControlNet parameters:
122
+
123
+ ```py
124
+ params_to_optimize = controlnet.parameters()
125
+ optimizer = optimizer_class(
126
+ params_to_optimize,
127
+ lr=args.learning_rate,
128
+ betas=(args.adam_beta1, args.adam_beta2),
129
+ weight_decay=args.adam_weight_decay,
130
+ eps=args.adam_epsilon,
131
+ )
132
+ ```
133
+
134
+ Finally, in the [training loop](https://github.com/huggingface/diffusers/blob/64603389da01082055a901f2883c4810d1144edb/examples/controlnet/train_controlnet.py#L943), the conditioning text embeddings and image are passed to the down and mid-blocks of the ControlNet model:
135
+
136
+ ```py
137
+ encoder_hidden_states = text_encoder(batch["input_ids"])[0]
138
+ controlnet_image = batch["conditioning_pixel_values"].to(dtype=weight_dtype)
139
+
140
+ down_block_res_samples, mid_block_res_sample = controlnet(
141
+ noisy_latents,
142
+ timesteps,
143
+ encoder_hidden_states=encoder_hidden_states,
144
+ controlnet_cond=controlnet_image,
145
+ return_dict=False,
146
+ )
147
+ ```
148
+
149
+ If you want to learn more about how the training loop works, check out the [Understanding pipelines, models and schedulers](../using-diffusers/write_own_pipeline) tutorial which breaks down the basic pattern of the denoising process.
150
+
151
+ ## Launch the script
152
+
153
+ Now you're ready to launch the training script! 🚀
154
+
155
+ This guide uses the [fusing/fill50k](https://huggingface.co/datasets/fusing/fill50k) dataset, but remember, you can create and use your own dataset if you want (see the [Create a dataset for training](create_dataset) guide).
156
+
157
+ Set the environment variable `MODEL_NAME` to a model id on the Hub or a path to a local model and `OUTPUT_DIR` to where you want to save the model.
158
+
159
+ Download the following images to condition your training with:
160
+
161
+ ```bash
162
+ wget https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/controlnet_training/conditioning_image_1.png
163
+ wget https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/controlnet_training/conditioning_image_2.png
164
+ ```
165
+
166
+ One more thing before you launch the script! Depending on the GPU you have, you may need to enable certain optimizations to train a ControlNet. The default configuration in this script requires ~38GB of vRAM. If you're training on more than one GPU, add the `--multi_gpu` parameter to the `accelerate launch` command.
167
+
168
+ <hfoptions id="gpu-select">
169
+ <hfoption id="16GB">
170
+
171
+ On a 16GB GPU, you can use bitsandbytes 8-bit optimizer and gradient checkpointing to optimize your training run. Install bitsandbytes:
172
+
173
+ ```py
174
+ pip install bitsandbytes
175
+ ```
176
+
177
+ Then, add the following parameter to your training command:
178
+
179
+ ```bash
180
+ accelerate launch train_controlnet.py \
181
+ --gradient_checkpointing \
182
+ --use_8bit_adam \
183
+ ```
184
+
185
+ </hfoption>
186
+ <hfoption id="12GB">
187
+
188
+ On a 12GB GPU, you'll need bitsandbytes 8-bit optimizer, gradient checkpointing, xFormers, and set the gradients to `None` instead of zero to reduce your memory-usage.
189
+
190
+ ```bash
191
+ accelerate launch train_controlnet.py \
192
+ --use_8bit_adam \
193
+ --gradient_checkpointing \
194
+ --enable_xformers_memory_efficient_attention \
195
+ --set_grads_to_none \
196
+ ```
197
+
198
+ </hfoption>
199
+ <hfoption id="8GB">
200
+
201
+ On a 8GB GPU, you'll need to use [DeepSpeed](https://www.deepspeed.ai/) to offload some of the tensors from the vRAM to either the CPU or NVME to allow training with less GPU memory.
202
+
203
+ Run the following command to configure your 🤗 Accelerate environment:
204
+
205
+ ```bash
206
+ accelerate config
207
+ ```
208
+
209
+ During configuration, confirm that you want to use DeepSpeed stage 2. Now it should be possible to train on under 8GB vRAM by combining DeepSpeed stage 2, fp16 mixed precision, and offloading the model parameters and the optimizer state to the CPU. The drawback is that this requires more system RAM (~25 GB). See the [DeepSpeed documentation](https://huggingface.co/docs/accelerate/usage_guides/deepspeed) for more configuration options. Your configuration file should look something like:
210
+
211
+ ```bash
212
+ compute_environment: LOCAL_MACHINE
213
+ deepspeed_config:
214
+ gradient_accumulation_steps: 4
215
+ offload_optimizer_device: cpu
216
+ offload_param_device: cpu
217
+ zero3_init_flag: false
218
+ zero_stage: 2
219
+ distributed_type: DEEPSPEED
220
+ ```
221
+
222
+ You should also change the default Adam optimizer to DeepSpeed’s optimized version of Adam [`deepspeed.ops.adam.DeepSpeedCPUAdam`](https://deepspeed.readthedocs.io/en/latest/optimizers.html#adam-cpu) for a substantial speedup. Enabling `DeepSpeedCPUAdam` requires your system’s CUDA toolchain version to be the same as the one installed with PyTorch.
223
+
224
+ bitsandbytes 8-bit optimizers don’t seem to be compatible with DeepSpeed at the moment.
225
+
226
+ That's it! You don't need to add any additional parameters to your training command.
227
+
228
+ </hfoption>
229
+ </hfoptions>
230
+
231
+ ```bash
232
+ export MODEL_DIR="stable-diffusion-v1-5/stable-diffusion-v1-5"
233
+ export OUTPUT_DIR="path/to/save/model"
234
+
235
+ accelerate launch train_controlnet.py \
236
+ --pretrained_model_name_or_path=$MODEL_DIR \
237
+ --output_dir=$OUTPUT_DIR \
238
+ --dataset_name=fusing/fill50k \
239
+ --resolution=512 \
240
+ --learning_rate=1e-5 \
241
+ --validation_image "./conditioning_image_1.png" "./conditioning_image_2.png" \
242
+ --validation_prompt "red circle with blue background" "cyan circle with brown floral background" \
243
+ --train_batch_size=1 \
244
+ --gradient_accumulation_steps=4 \
245
+ --push_to_hub
246
+ ```
247
+
248
+ Once training is complete, you can use your newly trained model for inference!
249
+
250
+ ```py
251
+ from diffusers import StableDiffusionControlNetPipeline, ControlNetModel
252
+ from diffusers.utils import load_image
253
+ import torch
254
+
255
+ controlnet = ControlNetModel.from_pretrained("path/to/controlnet", torch_dtype=torch.float16)
256
+ pipeline = StableDiffusionControlNetPipeline.from_pretrained(
257
+ "path/to/base/model", controlnet=controlnet, torch_dtype=torch.float16
258
+ ).to("cuda")
259
+
260
+ control_image = load_image("./conditioning_image_1.png")
261
+ prompt = "pale golden rod circle with old lace background"
262
+
263
+ generator = torch.manual_seed(0)
264
+ image = pipeline(prompt, num_inference_steps=20, generator=generator, image=control_image).images[0]
265
+ image.save("./output.png")
266
+ ```
267
+
268
+ ## Stable Diffusion XL
269
+
270
+ Stable Diffusion XL (SDXL) is a powerful text-to-image model that generates high-resolution images, and it adds a second text-encoder to its architecture. Use the [`train_controlnet_sdxl.py`](https://github.com/huggingface/diffusers/blob/main/examples/controlnet/train_controlnet_sdxl.py) script to train a ControlNet adapter for the SDXL model.
271
+
272
+ The SDXL training script is discussed in more detail in the [SDXL training](sdxl) guide.
273
+
274
+ ## Next steps
275
+
276
+ Congratulations on training your own ControlNet! To learn more about how to use your new model, the following guides may be helpful:
277
+
278
+ - Learn how to [use a ControlNet](../using-diffusers/controlnet) for inference on a variety of tasks.
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/training/create_dataset.md ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Create a dataset for training
2
+
3
+ There are many datasets on the [Hub](https://huggingface.co/datasets?task_categories=task_categories:text-to-image&sort=downloads) to train a model on, but if you can't find one you're interested in or want to use your own, you can create a dataset with the 🤗 [Datasets](https://huggingface.co/docs/datasets) library. The dataset structure depends on the task you want to train your model on. The most basic dataset structure is a directory of images for tasks like unconditional image generation. Another dataset structure may be a directory of images and a text file containing their corresponding text captions for tasks like text-to-image generation.
4
+
5
+ This guide will show you two ways to create a dataset to finetune on:
6
+
7
+ - provide a folder of images to the `--train_data_dir` argument
8
+ - upload a dataset to the Hub and pass the dataset repository id to the `--dataset_name` argument
9
+
10
+ > [!TIP]
11
+ > 💡 Learn more about how to create an image dataset for training in the [Create an image dataset](https://huggingface.co/docs/datasets/image_dataset) guide.
12
+
13
+ ## Provide a dataset as a folder
14
+
15
+ For unconditional generation, you can provide your own dataset as a folder of images. The training script uses the [`ImageFolder`](https://huggingface.co/docs/datasets/en/image_dataset#imagefolder) builder from 🤗 Datasets to automatically build a dataset from the folder. Your directory structure should look like:
16
+
17
+ ```bash
18
+ data_dir/xxx.png
19
+ data_dir/xxy.png
20
+ data_dir/[...]/xxz.png
21
+ ```
22
+
23
+ Pass the path to the dataset directory to the `--train_data_dir` argument, and then you can start training:
24
+
25
+ ```bash
26
+ accelerate launch train_unconditional.py \
27
+ --train_data_dir <path-to-train-directory> \
28
+ <other-arguments>
29
+ ```
30
+
31
+ ## Upload your data to the Hub
32
+
33
+ > [!TIP]
34
+ > 💡 For more details and context about creating and uploading a dataset to the Hub, take a look at the [Image search with 🤗 Datasets](https://huggingface.co/blog/image-search-datasets) post.
35
+
36
+ Start by creating a dataset with the [`ImageFolder`](https://huggingface.co/docs/datasets/image_load#imagefolder) feature, which creates an `image` column containing the PIL-encoded images.
37
+
38
+ You can use the `data_dir` or `data_files` parameters to specify the location of the dataset. The `data_files` parameter supports mapping specific files to dataset splits like `train` or `test`:
39
+
40
+ ```python
41
+ from datasets import load_dataset
42
+
43
+ # example 1: local folder
44
+ dataset = load_dataset("imagefolder", data_dir="path_to_your_folder")
45
+
46
+ # example 2: local files (supported formats are tar, gzip, zip, xz, rar, zstd)
47
+ dataset = load_dataset("imagefolder", data_files="path_to_zip_file")
48
+
49
+ # example 3: remote files (supported formats are tar, gzip, zip, xz, rar, zstd)
50
+ dataset = load_dataset(
51
+ "imagefolder",
52
+ data_files="https://download.microsoft.com/download/3/E/1/3E1C3F21-ECDB-4869-8368-6DEBA77B919F/kagglecatsanddogs_3367a.zip",
53
+ )
54
+
55
+ # example 4: providing several splits
56
+ dataset = load_dataset(
57
+ "imagefolder", data_files={"train": ["path/to/file1", "path/to/file2"], "test": ["path/to/file3", "path/to/file4"]}
58
+ )
59
+ ```
60
+
61
+ Then use the [`~datasets.Dataset.push_to_hub`] method to upload the dataset to the Hub:
62
+
63
+ ```python
64
+ # assuming you have ran the hf auth login command in a terminal
65
+ dataset.push_to_hub("name_of_your_dataset")
66
+
67
+ # if you want to push to a private repo, simply pass private=True:
68
+ dataset.push_to_hub("name_of_your_dataset", private=True)
69
+ ```
70
+
71
+ Now the dataset is available for training by passing the dataset name to the `--dataset_name` argument:
72
+
73
+ ```bash
74
+ accelerate launch --mixed_precision="fp16" train_text_to_image.py \
75
+ --pretrained_model_name_or_path="stable-diffusion-v1-5/stable-diffusion-v1-5" \
76
+ --dataset_name="name_of_your_dataset" \
77
+ <other-arguments>
78
+ ```
79
+
80
+ ## Next steps
81
+
82
+ Now that you've created a dataset, you can plug it into the `train_data_dir` (if your dataset is local) or `dataset_name` (if your dataset is on the Hub) arguments of a training script.
83
+
84
+ For your next steps, feel free to try and use your dataset to train a model for [unconditional generation](unconditional_training) or [text-to-image generation](text2image)!
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/training/custom_diffusion.md ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2025 Custom Diffusion authors 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
+ # Custom Diffusion
14
+
15
+ [Custom Diffusion](https://huggingface.co/papers/2212.04488) is a training technique for personalizing image generation models. Like Textual Inversion, DreamBooth, and LoRA, Custom Diffusion only requires a few (~4-5) example images. This technique works by only training weights in the cross-attention layers, and it uses a special word to represent the newly learned concept. Custom Diffusion is unique because it can also learn multiple concepts at the same time.
16
+
17
+ If you're training on a GPU with limited vRAM, you should try enabling xFormers with `--enable_xformers_memory_efficient_attention` for faster training with lower vRAM requirements (16GB). To save even more memory, add `--set_grads_to_none` in the training argument to set the gradients to `None` instead of zero (this option can cause some issues, so if you experience any, try removing this parameter).
18
+
19
+ This guide will explore the [train_custom_diffusion.py](https://github.com/huggingface/diffusers/blob/main/examples/custom_diffusion/train_custom_diffusion.py) script to help you become more familiar with it, and how you can adapt it for your own use-case.
20
+
21
+ Before running the script, make sure you install the library from source:
22
+
23
+ ```bash
24
+ git clone https://github.com/huggingface/diffusers
25
+ cd diffusers
26
+ pip install .
27
+ ```
28
+
29
+ Navigate to the example folder with the training script and install the required dependencies:
30
+
31
+ ```bash
32
+ cd examples/custom_diffusion
33
+ pip install -r requirements.txt
34
+ pip install clip-retrieval
35
+ ```
36
+
37
+ > [!TIP]
38
+ > 🤗 Accelerate is a library for helping you train on multiple GPUs/TPUs or with mixed-precision. It'll automatically configure your training setup based on your hardware and environment. Take a look at the 🤗 Accelerate [Quick tour](https://huggingface.co/docs/accelerate/quicktour) to learn more.
39
+
40
+ Initialize an 🤗 Accelerate environment:
41
+
42
+ ```bash
43
+ accelerate config
44
+ ```
45
+
46
+ To setup a default 🤗 Accelerate environment without choosing any configurations:
47
+
48
+ ```bash
49
+ accelerate config default
50
+ ```
51
+
52
+ Or if your environment doesn't support an interactive shell, like a notebook, you can use:
53
+
54
+ ```py
55
+ from accelerate.utils import write_basic_config
56
+
57
+ write_basic_config()
58
+ ```
59
+
60
+ Lastly, if you want to train a model on your own dataset, take a look at the [Create a dataset for training](create_dataset) guide to learn how to create a dataset that works with the training script.
61
+
62
+ > [!TIP]
63
+ > The following sections highlight parts of the training script that are important for understanding how to modify it, but it doesn't cover every aspect of the script in detail. If you're interested in learning more, feel free to read through the [script](https://github.com/huggingface/diffusers/blob/main/examples/custom_diffusion/train_custom_diffusion.py) and let us know if you have any questions or concerns.
64
+
65
+ ## Script parameters
66
+
67
+ The training script contains all the parameters to help you customize your training run. These are found in the [`parse_args()`](https://github.com/huggingface/diffusers/blob/64603389da01082055a901f2883c4810d1144edb/examples/custom_diffusion/train_custom_diffusion.py#L319) function. The function comes with default values, but you can also set your own values in the training command if you'd like.
68
+
69
+ For example, to change the resolution of the input image:
70
+
71
+ ```bash
72
+ accelerate launch train_custom_diffusion.py \
73
+ --resolution=256
74
+ ```
75
+
76
+ Many of the basic parameters are described in the [DreamBooth](dreambooth#script-parameters) training guide, so this guide focuses on the parameters unique to Custom Diffusion:
77
+
78
+ - `--freeze_model`: freezes the key and value parameters in the cross-attention layer; the default is `crossattn_kv`, but you can set it to `crossattn` to train all the parameters in the cross-attention layer
79
+ - `--concepts_list`: to learn multiple concepts, provide a path to a JSON file containing the concepts
80
+ - `--modifier_token`: a special word used to represent the learned concept
81
+ - `--initializer_token`: a special word used to initialize the embeddings of the `modifier_token`
82
+
83
+ ### Prior preservation loss
84
+
85
+ Prior preservation loss is a method that uses a model's own generated samples to help it learn how to generate more diverse images. Because these generated sample images belong to the same class as the images you provided, they help the model retain what it has learned about the class and how it can use what it already knows about the class to make new compositions.
86
+
87
+ Many of the parameters for prior preservation loss are described in the [DreamBooth](dreambooth#prior-preservation-loss) training guide.
88
+
89
+ ### Regularization
90
+
91
+ Custom Diffusion includes training the target images with a small set of real images to prevent overfitting. As you can imagine, this can be easy to do when you're only training on a few images! Download 200 real images with `clip_retrieval`. The `class_prompt` should be the same category as the target images. These images are stored in `class_data_dir`.
92
+
93
+ ```bash
94
+ python retrieve.py --class_prompt cat --class_data_dir real_reg/samples_cat --num_class_images 200
95
+ ```
96
+
97
+ To enable regularization, add the following parameters:
98
+
99
+ - `--with_prior_preservation`: whether to use prior preservation loss
100
+ - `--prior_loss_weight`: controls the influence of the prior preservation loss on the model
101
+ - `--real_prior`: whether to use a small set of real images to prevent overfitting
102
+
103
+ ```bash
104
+ accelerate launch train_custom_diffusion.py \
105
+ --with_prior_preservation \
106
+ --prior_loss_weight=1.0 \
107
+ --class_data_dir="./real_reg/samples_cat" \
108
+ --class_prompt="cat" \
109
+ --real_prior=True \
110
+ ```
111
+
112
+ ## Training script
113
+
114
+ > [!TIP]
115
+ > A lot of the code in the Custom Diffusion training script is similar to the [DreamBooth](dreambooth#training-script) script. This guide instead focuses on the code that is relevant to Custom Diffusion.
116
+
117
+ The Custom Diffusion training script has two dataset classes:
118
+
119
+ - [`CustomDiffusionDataset`](https://github.com/huggingface/diffusers/blob/64603389da01082055a901f2883c4810d1144edb/examples/custom_diffusion/train_custom_diffusion.py#L165): preprocesses the images, class images, and prompts for training
120
+ - [`PromptDataset`](https://github.com/huggingface/diffusers/blob/64603389da01082055a901f2883c4810d1144edb/examples/custom_diffusion/train_custom_diffusion.py#L148): prepares the prompts for generating class images
121
+
122
+ Next, the `modifier_token` is [added to the tokenizer](https://github.com/huggingface/diffusers/blob/64603389da01082055a901f2883c4810d1144edb/examples/custom_diffusion/train_custom_diffusion.py#L811), converted to token ids, and the token embeddings are resized to account for the new `modifier_token`. Then the `modifier_token` embeddings are initialized with the embeddings of the `initializer_token`. All parameters in the text encoder are frozen, except for the token embeddings since this is what the model is trying to learn to associate with the concepts.
123
+
124
+ ```py
125
+ params_to_freeze = itertools.chain(
126
+ text_encoder.text_model.encoder.parameters(),
127
+ text_encoder.text_model.final_layer_norm.parameters(),
128
+ text_encoder.text_model.embeddings.position_embedding.parameters(),
129
+ )
130
+ freeze_params(params_to_freeze)
131
+ ```
132
+
133
+ Now you'll need to add the [Custom Diffusion weights](https://github.com/huggingface/diffusers/blob/64603389da01082055a901f2883c4810d1144edb/examples/custom_diffusion/train_custom_diffusion.py#L911C3-L911C3) to the attention layers. This is a really important step for getting the shape and size of the attention weights correct, and for setting the appropriate number of attention processors in each UNet block.
134
+
135
+ ```py
136
+ st = unet.state_dict()
137
+ for name, _ in unet.attn_processors.items():
138
+ cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
139
+ if name.startswith("mid_block"):
140
+ hidden_size = unet.config.block_out_channels[-1]
141
+ elif name.startswith("up_blocks"):
142
+ block_id = int(name[len("up_blocks.")])
143
+ hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
144
+ elif name.startswith("down_blocks"):
145
+ block_id = int(name[len("down_blocks.")])
146
+ hidden_size = unet.config.block_out_channels[block_id]
147
+ layer_name = name.split(".processor")[0]
148
+ weights = {
149
+ "to_k_custom_diffusion.weight": st[layer_name + ".to_k.weight"],
150
+ "to_v_custom_diffusion.weight": st[layer_name + ".to_v.weight"],
151
+ }
152
+ if train_q_out:
153
+ weights["to_q_custom_diffusion.weight"] = st[layer_name + ".to_q.weight"]
154
+ weights["to_out_custom_diffusion.0.weight"] = st[layer_name + ".to_out.0.weight"]
155
+ weights["to_out_custom_diffusion.0.bias"] = st[layer_name + ".to_out.0.bias"]
156
+ if cross_attention_dim is not None:
157
+ custom_diffusion_attn_procs[name] = attention_class(
158
+ train_kv=train_kv,
159
+ train_q_out=train_q_out,
160
+ hidden_size=hidden_size,
161
+ cross_attention_dim=cross_attention_dim,
162
+ ).to(unet.device)
163
+ custom_diffusion_attn_procs[name].load_state_dict(weights)
164
+ else:
165
+ custom_diffusion_attn_procs[name] = attention_class(
166
+ train_kv=False,
167
+ train_q_out=False,
168
+ hidden_size=hidden_size,
169
+ cross_attention_dim=cross_attention_dim,
170
+ )
171
+ del st
172
+ unet.set_attn_processor(custom_diffusion_attn_procs)
173
+ custom_diffusion_layers = AttnProcsLayers(unet.attn_processors)
174
+ ```
175
+
176
+ The [optimizer](https://github.com/huggingface/diffusers/blob/84cd9e8d01adb47f046b1ee449fc76a0c32dc4e2/examples/custom_diffusion/train_custom_diffusion.py#L982) is initialized to update the cross-attention layer parameters:
177
+
178
+ ```py
179
+ optimizer = optimizer_class(
180
+ itertools.chain(text_encoder.get_input_embeddings().parameters(), custom_diffusion_layers.parameters())
181
+ if args.modifier_token is not None
182
+ else custom_diffusion_layers.parameters(),
183
+ lr=args.learning_rate,
184
+ betas=(args.adam_beta1, args.adam_beta2),
185
+ weight_decay=args.adam_weight_decay,
186
+ eps=args.adam_epsilon,
187
+ )
188
+ ```
189
+
190
+ In the [training loop](https://github.com/huggingface/diffusers/blob/84cd9e8d01adb47f046b1ee449fc76a0c32dc4e2/examples/custom_diffusion/train_custom_diffusion.py#L1048), it is important to only update the embeddings for the concept you're trying to learn. This means setting the gradients of all the other token embeddings to zero:
191
+
192
+ ```py
193
+ if args.modifier_token is not None:
194
+ if accelerator.num_processes > 1:
195
+ grads_text_encoder = text_encoder.module.get_input_embeddings().weight.grad
196
+ else:
197
+ grads_text_encoder = text_encoder.get_input_embeddings().weight.grad
198
+ index_grads_to_zero = torch.arange(len(tokenizer)) != modifier_token_id[0]
199
+ for i in range(len(modifier_token_id[1:])):
200
+ index_grads_to_zero = index_grads_to_zero & (
201
+ torch.arange(len(tokenizer)) != modifier_token_id[i]
202
+ )
203
+ grads_text_encoder.data[index_grads_to_zero, :] = grads_text_encoder.data[
204
+ index_grads_to_zero, :
205
+ ].fill_(0)
206
+ ```
207
+
208
+ ## Launch the script
209
+
210
+ Once you’ve made all your changes or you’re okay with the default configuration, you’re ready to launch the training script! 🚀
211
+
212
+ In this guide, you'll download and use these example [cat images](https://www.cs.cmu.edu/~custom-diffusion/assets/data.zip). You can also create and use your own dataset if you want (see the [Create a dataset for training](create_dataset) guide).
213
+
214
+ Set the environment variable `MODEL_NAME` to a model id on the Hub or a path to a local model, `INSTANCE_DIR` to the path where you just downloaded the cat images to, and `OUTPUT_DIR` to where you want to save the model. You'll use `<new1>` as the special word to tie the newly learned embeddings to. The script creates and saves model checkpoints and a pytorch_custom_diffusion_weights.bin file to your repository.
215
+
216
+ To monitor training progress with Weights and Biases, add the `--report_to=wandb` parameter to the training command and specify a validation prompt with `--validation_prompt`. This is useful for debugging and saving intermediate results.
217
+
218
+ > [!TIP]
219
+ > If you're training on human faces, the Custom Diffusion team has found the following parameters to work well:
220
+ >
221
+ > - `--learning_rate=5e-6`
222
+ > - `--max_train_steps` can be anywhere between 1000 and 2000
223
+ > - `--freeze_model=crossattn`
224
+ > - use at least 15-20 images to train with
225
+
226
+ <hfoptions id="training-inference">
227
+ <hfoption id="single concept">
228
+
229
+ ```bash
230
+ export MODEL_NAME="CompVis/stable-diffusion-v1-4"
231
+ export OUTPUT_DIR="path-to-save-model"
232
+ export INSTANCE_DIR="./data/cat"
233
+
234
+ accelerate launch train_custom_diffusion.py \
235
+ --pretrained_model_name_or_path=$MODEL_NAME \
236
+ --instance_data_dir=$INSTANCE_DIR \
237
+ --output_dir=$OUTPUT_DIR \
238
+ --class_data_dir=./real_reg/samples_cat/ \
239
+ --with_prior_preservation \
240
+ --real_prior \
241
+ --prior_loss_weight=1.0 \
242
+ --class_prompt="cat" \
243
+ --num_class_images=200 \
244
+ --instance_prompt="photo of a <new1> cat" \
245
+ --resolution=512 \
246
+ --train_batch_size=2 \
247
+ --learning_rate=1e-5 \
248
+ --lr_warmup_steps=0 \
249
+ --max_train_steps=250 \
250
+ --scale_lr \
251
+ --hflip \
252
+ --modifier_token "<new1>" \
253
+ --validation_prompt="<new1> cat sitting in a bucket" \
254
+ --report_to="wandb" \
255
+ --push_to_hub
256
+ ```
257
+
258
+ </hfoption>
259
+ <hfoption id="multiple concepts">
260
+
261
+ Custom Diffusion can also learn multiple concepts if you provide a [JSON](https://github.com/adobe-research/custom-diffusion/blob/main/assets/concept_list.json) file with some details about each concept it should learn.
262
+
263
+ Run clip-retrieval to collect some real images to use for regularization:
264
+
265
+ ```bash
266
+ pip install clip-retrieval
267
+ python retrieve.py --class_prompt {} --class_data_dir {} --num_class_images 200
268
+ ```
269
+
270
+ Then you can launch the script:
271
+
272
+ ```bash
273
+ export MODEL_NAME="CompVis/stable-diffusion-v1-4"
274
+ export OUTPUT_DIR="path-to-save-model"
275
+
276
+ accelerate launch train_custom_diffusion.py \
277
+ --pretrained_model_name_or_path=$MODEL_NAME \
278
+ --output_dir=$OUTPUT_DIR \
279
+ --concepts_list=./concept_list.json \
280
+ --with_prior_preservation \
281
+ --real_prior \
282
+ --prior_loss_weight=1.0 \
283
+ --resolution=512 \
284
+ --train_batch_size=2 \
285
+ --learning_rate=1e-5 \
286
+ --lr_warmup_steps=0 \
287
+ --max_train_steps=500 \
288
+ --num_class_images=200 \
289
+ --scale_lr \
290
+ --hflip \
291
+ --modifier_token "<new1>+<new2>" \
292
+ --push_to_hub
293
+ ```
294
+
295
+ </hfoption>
296
+ </hfoptions>
297
+
298
+ Once training is finished, you can use your new Custom Diffusion model for inference.
299
+
300
+ <hfoptions id="training-inference">
301
+ <hfoption id="single concept">
302
+
303
+ ```py
304
+ import torch
305
+ from diffusers import DiffusionPipeline
306
+
307
+ pipeline = DiffusionPipeline.from_pretrained(
308
+ "CompVis/stable-diffusion-v1-4", torch_dtype=torch.float16,
309
+ ).to("cuda")
310
+ pipeline.unet.load_attn_procs("path-to-save-model", weight_name="pytorch_custom_diffusion_weights.bin")
311
+ pipeline.load_textual_inversion("path-to-save-model", weight_name="<new1>.bin")
312
+
313
+ image = pipeline(
314
+ "<new1> cat sitting in a bucket",
315
+ num_inference_steps=100,
316
+ guidance_scale=6.0,
317
+ eta=1.0,
318
+ ).images[0]
319
+ image.save("cat.png")
320
+ ```
321
+
322
+ </hfoption>
323
+ <hfoption id="multiple concepts">
324
+
325
+ ```py
326
+ import torch
327
+ from huggingface_hub.repocard import RepoCard
328
+ from diffusers import DiffusionPipeline
329
+
330
+ pipeline = DiffusionPipeline.from_pretrained(
331
+ "CompVis/stable-diffusion-v1-4", torch_dtype=torch.float16,
332
+ ).to("cuda")
333
+ model_id = "sayakpaul/custom-diffusion-cat-wooden-pot"
334
+ pipeline.unet.load_attn_procs(model_id, weight_name="pytorch_custom_diffusion_weights.bin")
335
+ pipeline.load_textual_inversion(model_id, weight_name="<new1>.bin")
336
+ pipeline.load_textual_inversion(model_id, weight_name="<new2>.bin")
337
+
338
+ image = pipeline(
339
+ "the <new1> cat sculpture in the style of a <new2> wooden pot",
340
+ num_inference_steps=100,
341
+ guidance_scale=6.0,
342
+ eta=1.0,
343
+ ).images[0]
344
+ image.save("multi-subject.png")
345
+ ```
346
+
347
+ </hfoption>
348
+ </hfoptions>
349
+
350
+ ## Next steps
351
+
352
+ Congratulations on training a model with Custom Diffusion! 🎉 To learn more:
353
+
354
+ - Read the [Multi-Concept Customization of Text-to-Image Diffusion](https://www.cs.cmu.edu/~custom-diffusion/) blog post to learn more details about the experimental results from the Custom Diffusion team.
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/training/ddpo.md ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Reinforcement learning training with DDPO
14
+
15
+ You can fine-tune Stable Diffusion on a reward function via reinforcement learning with the 🤗 TRL library and 🤗 Diffusers. This is done with the Denoising Diffusion Policy Optimization (DDPO) algorithm introduced by Black et al. in [Training Diffusion Models with Reinforcement Learning](https://huggingface.co/papers/2305.13301), which is implemented in 🤗 TRL with the [`~trl.DDPOTrainer`].
16
+
17
+ For more information, check out the [`~trl.DDPOTrainer`] API reference and the [Finetune Stable Diffusion Models with DDPO via TRL](https://huggingface.co/blog/trl-ddpo) blog post.
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/training/distributed_inference.md ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Distributed inference
14
+
15
+ Distributed inference splits the workload across multiple GPUs. It a useful technique for fitting larger models in memory and can process multiple prompts for higher throughput.
16
+
17
+ This guide will show you how to use [Accelerate](https://huggingface.co/docs/accelerate/index) and [PyTorch Distributed](https://pytorch.org/tutorials/beginner/dist_overview.html) for distributed inference.
18
+
19
+ ## Accelerate
20
+
21
+ Accelerate is a library designed to simplify inference and training on multiple accelerators by handling the setup, allowing users to focus on their PyTorch code.
22
+
23
+ Install Accelerate with the following command.
24
+
25
+ ```bash
26
+ uv pip install accelerate
27
+ ```
28
+
29
+ Initialize a [`accelerate.PartialState`] class in a Python file to create a distributed environment. The [`accelerate.PartialState`] class manages process management, device control and distribution, and process coordination.
30
+
31
+ Move the [`DiffusionPipeline`] to [`accelerate.PartialState.device`] to assign a GPU to each process.
32
+
33
+ ```py
34
+ import torch
35
+ from accelerate import PartialState
36
+ from diffusers import DiffusionPipeline
37
+
38
+ pipeline = DiffusionPipeline.from_pretrained(
39
+ "Qwen/Qwen-Image", torch_dtype=torch.float16
40
+ )
41
+ distributed_state = PartialState()
42
+ pipeline.to(distributed_state.device)
43
+ ```
44
+
45
+ Use the [`~accelerate.PartialState.split_between_processes`] utility as a context manager to automatically distribute the prompts between the number of processes.
46
+
47
+ ```py
48
+ with distributed_state.split_between_processes(["a dog", "a cat"]) as prompt:
49
+ result = pipeline(prompt).images[0]
50
+ result.save(f"result_{distributed_state.process_index}.png")
51
+ ```
52
+
53
+ Call `accelerate launch` to run the script and use the `--num_processes` argument to set the number of GPUs to use.
54
+
55
+ ```bash
56
+ accelerate launch run_distributed.py --num_processes=2
57
+ ```
58
+
59
+ > [!TIP]
60
+ > Refer to this minimal example [script](https://gist.github.com/sayakpaul/cfaebd221820d7b43fae638b4dfa01ba) for running inference across multiple GPUs. To learn more, take a look at the [Distributed Inference with 🤗 Accelerate](https://huggingface.co/docs/accelerate/en/usage_guides/distributed_inference#distributed-inference-with-accelerate) guide.
61
+
62
+ ## PyTorch Distributed
63
+
64
+ PyTorch [DistributedDataParallel](https://pytorch.org/docs/stable/generated/torch.nn.parallel.DistributedDataParallel.html) enables [data parallelism](https://huggingface.co/spaces/nanotron/ultrascale-playbook?section=data_parallelism), which replicates the same model on each device, to process different batches of data in parallel.
65
+
66
+ Import `torch.distributed` and `torch.multiprocessing` into a Python file to set up the distributed process group and to spawn the processes for inference on each GPU.
67
+
68
+ ```py
69
+ import torch
70
+ import torch.distributed as dist
71
+ import torch.multiprocessing as mp
72
+
73
+ from diffusers import DiffusionPipeline
74
+
75
+ pipeline = DiffusionPipeline.from_pretrained(
76
+ "Qwen/Qwen-Image", torch_dtype=torch.float16,
77
+ )
78
+ ```
79
+
80
+ Create a function for inference with [init_process_group](https://pytorch.org/docs/stable/distributed.html?highlight=init_process_group#torch.distributed.init_process_group). This method creates a distributed environment with the backend type, the `rank` of the current process, and the `world_size` or number of processes participating (for example, 2 GPUs would be `world_size=2`).
81
+
82
+ Move the pipeline to `rank` and use `get_rank` to assign a GPU to each process. Each process handles a different prompt.
83
+
84
+ ```py
85
+ def run_inference(rank, world_size):
86
+ dist.init_process_group("nccl", rank=rank, world_size=world_size)
87
+
88
+ pipeline.to(rank)
89
+
90
+ if torch.distributed.get_rank() == 0:
91
+ prompt = "a dog"
92
+ elif torch.distributed.get_rank() == 1:
93
+ prompt = "a cat"
94
+
95
+ image = sd(prompt).images[0]
96
+ image.save(f"./{'_'.join(prompt)}.png")
97
+ ```
98
+
99
+ Use [mp.spawn](https://pytorch.org/docs/stable/multiprocessing.html#torch.multiprocessing.spawn) to create the number of processes defined in `world_size`.
100
+
101
+ ```py
102
+ def main():
103
+ world_size = 2
104
+ mp.spawn(run_inference, args=(world_size,), nprocs=world_size, join=True)
105
+
106
+
107
+ if __name__ == "__main__":
108
+ main()
109
+ ```
110
+
111
+ Call `torchrun` to run the inference script and use the `--nproc_per_node` argument to set the number of GPUs to use.
112
+
113
+ ```bash
114
+ torchrun run_distributed.py --nproc_per_node=2
115
+ ```
116
+
117
+ ## device_map
118
+
119
+ The `device_map` argument enables distributed inference by automatically placing model components on separate GPUs. This is especially useful when a model doesn't fit on a single GPU. You can use `device_map` to selectively load and unload the required model components at a given stage as shown in the example below (assumes two GPUs are available).
120
+
121
+ Set `device_map="balanced"` to evenly distributes the text encoders on all available GPUs. You can use the `max_memory` argument to allocate a maximum amount of memory for each text encoder. Don't load any other pipeline components to avoid memory usage.
122
+
123
+ ```py
124
+ from diffusers import FluxPipeline
125
+ import torch
126
+
127
+ prompt = """
128
+ cinematic film still of a cat sipping a margarita in a pool in Palm Springs, California
129
+ highly detailed, high budget hollywood movie, cinemascope, moody, epic, gorgeous, film grain
130
+ """
131
+
132
+ pipeline = FluxPipeline.from_pretrained(
133
+ "black-forest-labs/FLUX.1-dev",
134
+ transformer=None,
135
+ vae=None,
136
+ device_map="balanced",
137
+ max_memory={0: "16GB", 1: "16GB"},
138
+ torch_dtype=torch.bfloat16
139
+ )
140
+ with torch.no_grad():
141
+ print("Encoding prompts.")
142
+ prompt_embeds, pooled_prompt_embeds, text_ids = pipeline.encode_prompt(
143
+ prompt=prompt, prompt_2=None, max_sequence_length=512
144
+ )
145
+ ```
146
+
147
+ After the text embeddings are computed, remove them from the GPU to make space for the diffusion transformer.
148
+
149
+ ```py
150
+ import gc
151
+
152
+ def flush():
153
+ gc.collect()
154
+ torch.cuda.empty_cache()
155
+ torch.cuda.reset_max_memory_allocated()
156
+ torch.cuda.reset_peak_memory_stats()
157
+
158
+ del pipeline.text_encoder
159
+ del pipeline.text_encoder_2
160
+ del pipeline.tokenizer
161
+ del pipeline.tokenizer_2
162
+ del pipeline
163
+
164
+ flush()
165
+ ```
166
+
167
+ Set `device_map="auto"` to automatically distribute the model on the two GPUs. This strategy places a model on the fastest device first before placing a model on a slower device like a CPU or hard drive if needed. The trade-off of storing model parameters on slower devices is slower inference latency.
168
+
169
+ ```py
170
+ from diffusers import AutoModel
171
+ import torch
172
+
173
+ transformer = AutoModel.from_pretrained(
174
+ "black-forest-labs/FLUX.1-dev",
175
+ subfolder="transformer",
176
+ device_map="auto",
177
+ torch_dtype=torch.bfloat16
178
+ )
179
+ ```
180
+
181
+ > [!TIP]
182
+ > Run `pipeline.hf_device_map` to see how the various models are distributed across devices. This is useful for tracking model device placement. You can also call `hf_device_map` on the transformer model to see how it is distributed.
183
+
184
+ Add the transformer model to the pipeline and set the `output_type="latent"` to generate the latents.
185
+
186
+ ```py
187
+ pipeline = FluxPipeline.from_pretrained(
188
+ "black-forest-labs/FLUX.1-dev",
189
+ text_encoder=None,
190
+ text_encoder_2=None,
191
+ tokenizer=None,
192
+ tokenizer_2=None,
193
+ vae=None,
194
+ transformer=transformer,
195
+ torch_dtype=torch.bfloat16
196
+ )
197
+
198
+ print("Running denoising.")
199
+ height, width = 768, 1360
200
+ latents = pipeline(
201
+ prompt_embeds=prompt_embeds,
202
+ pooled_prompt_embeds=pooled_prompt_embeds,
203
+ num_inference_steps=50,
204
+ guidance_scale=3.5,
205
+ height=height,
206
+ width=width,
207
+ output_type="latent",
208
+ ).images
209
+ ```
210
+
211
+ Remove the pipeline and transformer from memory and load a VAE to decode the latents. The VAE is typically small enough to be loaded on a single device.
212
+
213
+ ```py
214
+ import torch
215
+ from diffusers import AutoencoderKL
216
+ from diffusers.image_processor import VaeImageProcessor
217
+
218
+ vae = AutoencoderKL.from_pretrained(ckpt_id, subfolder="vae", torch_dtype=torch.bfloat16).to("cuda")
219
+ vae_scale_factor = 2 ** (len(vae.config.block_out_channels) - 1)
220
+ image_processor = VaeImageProcessor(vae_scale_factor=vae_scale_factor)
221
+
222
+ with torch.no_grad():
223
+ print("Running decoding.")
224
+ latents = FluxPipeline._unpack_latents(latents, height, width, vae_scale_factor)
225
+ latents = (latents / vae.config.scaling_factor) + vae.config.shift_factor
226
+
227
+ image = vae.decode(latents, return_dict=False)[0]
228
+ image = image_processor.postprocess(image, output_type="pil")
229
+ image[0].save("split_transformer.png")
230
+ ```
231
+
232
+ By selectively loading and unloading the models you need at a given stage and sharding the largest models across multiple GPUs, it is possible to run inference with large models on consumer GPUs.
233
+
234
+ ## Context parallelism
235
+
236
+ [Context parallelism](https://huggingface.co/spaces/nanotron/ultrascale-playbook?section=context_parallelism) splits input sequences across multiple GPUs to reduce memory usage. Each GPU processes its own slice of the sequence.
237
+
238
+ Use [`~ModelMixin.set_attention_backend`] to switch to a more optimized attention backend. Refer to this [table](../optimization/attention_backends#available-backends) for a complete list of available backends.
239
+
240
+ ### Ring Attention
241
+
242
+ Key (K) and value (V) representations communicate between devices using [Ring Attention](https://huggingface.co/papers/2310.01889). This ensures each split sees every other token's K/V. Each GPU computes attention for its local K/V and passes it to the next GPU in the ring. No single GPU holds the full sequence, which reduces communication latency.
243
+
244
+ Pass a [`ContextParallelConfig`] to the `parallel_config` argument of the transformer model. The config supports the `ring_degree` argument that determines how many devices to use for Ring Attention.
245
+
246
+ ```py
247
+ import torch
248
+ from diffusers import AutoModel, QwenImagePipeline, ContextParallelConfig
249
+
250
+ try:
251
+ torch.distributed.init_process_group("nccl")
252
+ rank = torch.distributed.get_rank()
253
+ device = torch.device("cuda", rank % torch.cuda.device_count())
254
+ torch.cuda.set_device(device)
255
+
256
+ transformer = AutoModel.from_pretrained("Qwen/Qwen-Image", subfolder="transformer", torch_dtype=torch.bfloat16, parallel_config=ContextParallelConfig(ring_degree=2))
257
+ pipeline = QwenImagePipeline.from_pretrained("Qwen/Qwen-Image", transformer=transformer, torch_dtype=torch.bfloat16, device_map="cuda")
258
+ pipeline.transformer.set_attention_backend("flash")
259
+
260
+ prompt = """
261
+ cinematic film still of a cat sipping a margarita in a pool in Palm Springs, California
262
+ highly detailed, high budget hollywood movie, cinemascope, moody, epic, gorgeous, film grain
263
+ """
264
+
265
+ # Must specify generator so all ranks start with same latents (or pass your own)
266
+ generator = torch.Generator().manual_seed(42)
267
+ image = pipeline(prompt, num_inference_steps=50, generator=generator).images[0]
268
+
269
+ if rank == 0:
270
+ image.save("output.png")
271
+
272
+ except Exception as e:
273
+ print(f"An error occurred: {e}")
274
+ torch.distributed.breakpoint()
275
+ raise
276
+
277
+ finally:
278
+ if torch.distributed.is_initialized():
279
+ torch.distributed.destroy_process_group()
280
+ ```
281
+
282
+ ### Ulysses Attention
283
+
284
+ [Ulysses Attention](https://huggingface.co/papers/2309.14509) splits a sequence across GPUs and performs an *all-to-all* communication (every device sends/receives data to every other device). Each GPU ends up with all tokens for only a subset of attention heads. Each GPU computes attention locally on all tokens for its head, then performs another all-to-all to regroup results by tokens for the next layer.
285
+
286
+ [`ContextParallelConfig`] supports Ulysses Attention through the `ulysses_degree` argument. This determines how many devices to use for Ulysses Attention.
287
+
288
+ Pass the [`ContextParallelConfig`] to [`~ModelMixin.enable_parallelism`].
289
+
290
+ ```py
291
+ pipeline.transformer.enable_parallelism(config=ContextParallelConfig(ulysses_degree=2))
292
+ ```
tasks/tasksmith-83a0918520ec/tests/source/docs/source/en/training/dreambooth.md ADDED
@@ -0,0 +1,551 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # DreamBooth
14
+
15
+ [DreamBooth](https://huggingface.co/papers/2208.12242) is a training technique that updates the entire diffusion model by training on just a few images of a subject or style. It works by associating a special word in the prompt with the example images.
16
+
17
+ If you're training on a GPU with limited vRAM, you should try enabling the `gradient_checkpointing` and `mixed_precision` parameters in the training command. You can also reduce your memory footprint by using memory-efficient attention with [xFormers](../optimization/xformers).
18
+
19
+ This guide will explore the [train_dreambooth.py](https://github.com/huggingface/diffusers/blob/main/examples/dreambooth/train_dreambooth.py) script to help you become more familiar with it, and how you can adapt it for your own use-case.
20
+
21
+ Before running the script, make sure you install the library from source:
22
+
23
+ ```bash
24
+ git clone https://github.com/huggingface/diffusers
25
+ cd diffusers
26
+ pip install .
27
+ ```
28
+
29
+ Navigate to the example folder with the training script and install the required dependencies for the script you're using:
30
+
31
+ ```bash
32
+ cd examples/dreambooth
33
+ pip install -r requirements.txt
34
+ ```
35
+
36
+ > [!TIP]
37
+ > 🤗 Accelerate is a library for helping you train on multiple GPUs/TPUs or with mixed-precision. It'll automatically configure your training setup based on your hardware and environment. Take a look at the 🤗 Accelerate [Quick tour](https://huggingface.co/docs/accelerate/quicktour) to learn more.
38
+
39
+ Initialize an 🤗 Accelerate environment:
40
+
41
+ ```bash
42
+ accelerate config
43
+ ```
44
+
45
+ To setup a default 🤗 Accelerate environment without choosing any configurations:
46
+
47
+ ```bash
48
+ accelerate config default
49
+ ```
50
+
51
+ Or if your environment doesn't support an interactive shell, like a notebook, you can use:
52
+
53
+ ```py
54
+ from accelerate.utils import write_basic_config
55
+
56
+ write_basic_config()
57
+ ```
58
+
59
+ Lastly, if you want to train a model on your own dataset, take a look at the [Create a dataset for training](create_dataset) guide to learn how to create a dataset that works with the training script.
60
+
61
+ > [!TIP]
62
+ > The following sections highlight parts of the training script that are important for understanding how to modify it, but it doesn't cover every aspect of the script in detail. If you're interested in learning more, feel free to read through the [script](https://github.com/huggingface/diffusers/blob/main/examples/dreambooth/train_dreambooth.py) and let us know if you have any questions or concerns.
63
+
64
+ ## Script parameters
65
+
66
+ > [!WARNING]
67
+ > DreamBooth is very sensitive to training hyperparameters, and it is easy to overfit. Read the [Training Stable Diffusion with Dreambooth using 🧨 Diffusers](https://huggingface.co/blog/dreambooth) blog post for recommended settings for different subjects to help you choose the appropriate hyperparameters.
68
+
69
+ The training script offers many parameters for customizing your training run. All of the parameters and their descriptions are found in the [`parse_args()`](https://github.com/huggingface/diffusers/blob/072e00897a7cf4302c347a63ec917b4b8add16d4/examples/dreambooth/train_dreambooth.py#L228) function. The parameters are set with default values that should work pretty well out-of-the-box, but you can also set your own values in the training command if you'd like.
70
+
71
+ For example, to train in the bf16 format:
72
+
73
+ ```bash
74
+ accelerate launch train_dreambooth.py \
75
+ --mixed_precision="bf16"
76
+ ```
77
+
78
+ Some basic and important parameters to know and specify are:
79
+
80
+ - `--pretrained_model_name_or_path`: the name of the model on the Hub or a local path to the pretrained model
81
+ - `--instance_data_dir`: path to a folder containing the training dataset (example images)
82
+ - `--instance_prompt`: the text prompt that contains the special word for the example images
83
+ - `--train_text_encoder`: whether to also train the text encoder
84
+ - `--output_dir`: where to save the trained model
85
+ - `--push_to_hub`: whether to push the trained model to the Hub
86
+ - `--checkpointing_steps`: frequency of saving a checkpoint as the model trains; this is useful if for some reason training is interrupted, you can continue training from that checkpoint by adding `--resume_from_checkpoint` to your training command
87
+
88
+ ### Min-SNR weighting
89
+
90
+ The [Min-SNR](https://huggingface.co/papers/2303.09556) weighting strategy can help with training by rebalancing the loss to achieve faster convergence. The training script supports predicting `epsilon` (noise) or `v_prediction`, but Min-SNR is compatible with both prediction types. This weighting strategy is only supported by PyTorch.
91
+
92
+ Add the `--snr_gamma` parameter and set it to the recommended value of 5.0:
93
+
94
+ ```bash
95
+ accelerate launch train_dreambooth.py \
96
+ --snr_gamma=5.0
97
+ ```
98
+
99
+ ### Prior preservation loss
100
+
101
+ Prior preservation loss is a method that uses a model's own generated samples to help it learn how to generate more diverse images. Because these generated sample images belong to the same class as the images you provided, they help the model retain what it has learned about the class and how it can use what it already knows about the class to make new compositions.
102
+
103
+ - `--with_prior_preservation`: whether to use prior preservation loss
104
+ - `--prior_loss_weight`: controls the influence of the prior preservation loss on the model
105
+ - `--class_data_dir`: path to a folder containing the generated class sample images
106
+ - `--class_prompt`: the text prompt describing the class of the generated sample images
107
+
108
+ ```bash
109
+ accelerate launch train_dreambooth.py \
110
+ --with_prior_preservation \
111
+ --prior_loss_weight=1.0 \
112
+ --class_data_dir="path/to/class/images" \
113
+ --class_prompt="text prompt describing class"
114
+ ```
115
+
116
+ ### Train text encoder
117
+
118
+ To improve the quality of the generated outputs, you can also train the text encoder in addition to the UNet. This requires additional memory and you'll need a GPU with at least 24GB of vRAM. If you have the necessary hardware, then training the text encoder produces better results, especially when generating images of faces. Enable this option by:
119
+
120
+ ```bash
121
+ accelerate launch train_dreambooth.py \
122
+ --train_text_encoder
123
+ ```
124
+
125
+ ## Training script
126
+
127
+ DreamBooth comes with its own dataset classes:
128
+
129
+ - [`DreamBoothDataset`](https://github.com/huggingface/diffusers/blob/072e00897a7cf4302c347a63ec917b4b8add16d4/examples/dreambooth/train_dreambooth.py#L604): preprocesses the images and class images, and tokenizes the prompts for training
130
+ - [`PromptDataset`](https://github.com/huggingface/diffusers/blob/072e00897a7cf4302c347a63ec917b4b8add16d4/examples/dreambooth/train_dreambooth.py#L738): generates the prompt embeddings to generate the class images
131
+
132
+ If you enabled [prior preservation loss](https://github.com/huggingface/diffusers/blob/072e00897a7cf4302c347a63ec917b4b8add16d4/examples/dreambooth/train_dreambooth.py#L842), the class images are generated here:
133
+
134
+ ```py
135
+ sample_dataset = PromptDataset(args.class_prompt, num_new_images)
136
+ sample_dataloader = torch.utils.data.DataLoader(sample_dataset, batch_size=args.sample_batch_size)
137
+
138
+ sample_dataloader = accelerator.prepare(sample_dataloader)
139
+ pipeline.to(accelerator.device)
140
+
141
+ for example in tqdm(
142
+ sample_dataloader, desc="Generating class images", disable=not accelerator.is_local_main_process
143
+ ):
144
+ images = pipeline(example["prompt"]).images
145
+ ```
146
+
147
+ Next is the [`main()`](https://github.com/huggingface/diffusers/blob/072e00897a7cf4302c347a63ec917b4b8add16d4/examples/dreambooth/train_dreambooth.py#L799) function which handles setting up the dataset for training and the training loop itself. The script loads the [tokenizer](https://github.com/huggingface/diffusers/blob/072e00897a7cf4302c347a63ec917b4b8add16d4/examples/dreambooth/train_dreambooth.py#L898), [scheduler and models](https://github.com/huggingface/diffusers/blob/072e00897a7cf4302c347a63ec917b4b8add16d4/examples/dreambooth/train_dreambooth.py#L912C1-L912C1):
148
+
149
+ ```py
150
+ # Load the tokenizer
151
+ if args.tokenizer_name:
152
+ tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name, revision=args.revision, use_fast=False)
153
+ elif args.pretrained_model_name_or_path:
154
+ tokenizer = AutoTokenizer.from_pretrained(
155
+ args.pretrained_model_name_or_path,
156
+ subfolder="tokenizer",
157
+ revision=args.revision,
158
+ use_fast=False,
159
+ )
160
+
161
+ # Load scheduler and models
162
+ noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
163
+ text_encoder = text_encoder_cls.from_pretrained(
164
+ args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision
165
+ )
166
+
167
+ if model_has_vae(args):
168
+ vae = AutoencoderKL.from_pretrained(
169
+ args.pretrained_model_name_or_path, subfolder="vae", revision=args.revision
170
+ )
171
+ else:
172
+ vae = None
173
+
174
+ unet = UNet2DConditionModel.from_pretrained(
175
+ args.pretrained_model_name_or_path, subfolder="unet", revision=args.revision
176
+ )
177
+ ```
178
+
179
+ Then, it's time to [create the training dataset](https://github.com/huggingface/diffusers/blob/072e00897a7cf4302c347a63ec917b4b8add16d4/examples/dreambooth/train_dreambooth.py#L1073) and DataLoader from `DreamBoothDataset`:
180
+
181
+ ```py
182
+ train_dataset = DreamBoothDataset(
183
+ instance_data_root=args.instance_data_dir,
184
+ instance_prompt=args.instance_prompt,
185
+ class_data_root=args.class_data_dir if args.with_prior_preservation else None,
186
+ class_prompt=args.class_prompt,
187
+ class_num=args.num_class_images,
188
+ tokenizer=tokenizer,
189
+ size=args.resolution,
190
+ center_crop=args.center_crop,
191
+ encoder_hidden_states=pre_computed_encoder_hidden_states,
192
+ class_prompt_encoder_hidden_states=pre_computed_class_prompt_encoder_hidden_states,
193
+ tokenizer_max_length=args.tokenizer_max_length,
194
+ )
195
+
196
+ train_dataloader = torch.utils.data.DataLoader(
197
+ train_dataset,
198
+ batch_size=args.train_batch_size,
199
+ shuffle=True,
200
+ collate_fn=lambda examples: collate_fn(examples, args.with_prior_preservation),
201
+ num_workers=args.dataloader_num_workers,
202
+ )
203
+ ```
204
+
205
+ Lastly, the [training loop](https://github.com/huggingface/diffusers/blob/072e00897a7cf4302c347a63ec917b4b8add16d4/examples/dreambooth/train_dreambooth.py#L1151) takes care of the remaining steps such as converting images to latent space, adding noise to the input, predicting the noise residual, and calculating the loss.
206
+
207
+ If you want to learn more about how the training loop works, check out the [Understanding pipelines, models and schedulers](../using-diffusers/write_own_pipeline) tutorial which breaks down the basic pattern of the denoising process.
208
+
209
+ ## Launch the script
210
+
211
+ You're now ready to launch the training script! 🚀
212
+
213
+ For this guide, you'll download some images of a [dog](https://huggingface.co/datasets/diffusers/dog-example) and store them in a directory. But remember, you can create and use your own dataset if you want (see the [Create a dataset for training](create_dataset) guide).
214
+
215
+ ```py
216
+ from huggingface_hub import snapshot_download
217
+
218
+ local_dir = "./dog"
219
+ snapshot_download(
220
+ "diffusers/dog-example",
221
+ local_dir=local_dir,
222
+ repo_type="dataset",
223
+ ignore_patterns=".gitattributes",
224
+ )
225
+ ```
226
+
227
+ Set the environment variable `MODEL_NAME` to a model id on the Hub or a path to a local model, `INSTANCE_DIR` to the path where you just downloaded the dog images to, and `OUTPUT_DIR` to where you want to save the model. You'll use `sks` as the special word to tie the training to.
228
+
229
+ If you're interested in following along with the training process, you can periodically save generated images as training progresses. Add the following parameters to the training command:
230
+
231
+ ```bash
232
+ --validation_prompt="a photo of a sks dog"
233
+ --num_validation_images=4
234
+ --validation_steps=100
235
+ ```
236
+
237
+ One more thing before you launch the script! Depending on the GPU you have, you may need to enable certain optimizations to train DreamBooth.
238
+
239
+ <hfoptions id="gpu-select">
240
+ <hfoption id="16GB">
241
+
242
+ On a 16GB GPU, you can use bitsandbytes 8-bit optimizer and gradient checkpointing to help you train a DreamBooth model. Install bitsandbytes:
243
+
244
+ ```py
245
+ pip install bitsandbytes
246
+ ```
247
+
248
+ Then, add the following parameter to your training command:
249
+
250
+ ```bash
251
+ accelerate launch train_dreambooth.py \
252
+ --gradient_checkpointing \
253
+ --use_8bit_adam \
254
+ ```
255
+
256
+ </hfoption>
257
+ <hfoption id="12GB">
258
+
259
+ On a 12GB GPU, you'll need bitsandbytes 8-bit optimizer, gradient checkpointing, xFormers, and set the gradients to `None` instead of zero to reduce your memory-usage.
260
+
261
+ ```bash
262
+ accelerate launch train_dreambooth.py \
263
+ --use_8bit_adam \
264
+ --gradient_checkpointing \
265
+ --enable_xformers_memory_efficient_attention \
266
+ --set_grads_to_none \
267
+ ```
268
+
269
+ </hfoption>
270
+ <hfoption id="8GB">
271
+
272
+ On a 8GB GPU, you'll need [DeepSpeed](https://www.deepspeed.ai/) to offload some of the tensors from the vRAM to either the CPU or NVME to allow training with less GPU memory.
273
+
274
+ Run the following command to configure your 🤗 Accelerate environment:
275
+
276
+ ```bash
277
+ accelerate config
278
+ ```
279
+
280
+ During configuration, confirm that you want to use DeepSpeed. Now it should be possible to train on under 8GB vRAM by combining DeepSpeed stage 2, fp16 mixed precision, and offloading the model parameters and the optimizer state to the CPU. The drawback is that this requires more system RAM (~25 GB). See the [DeepSpeed documentation](https://huggingface.co/docs/accelerate/usage_guides/deepspeed) for more configuration options.
281
+
282
+ You should also change the default Adam optimizer to DeepSpeed’s optimized version of Adam [`deepspeed.ops.adam.DeepSpeedCPUAdam`](https://deepspeed.readthedocs.io/en/latest/optimizers.html#adam-cpu) for a substantial speedup. Enabling `DeepSpeedCPUAdam` requires your system’s CUDA toolchain version to be the same as the one installed with PyTorch.
283
+
284
+ bitsandbytes 8-bit optimizers don’t seem to be compatible with DeepSpeed at the moment.
285
+
286
+ That's it! You don't need to add any additional parameters to your training command.
287
+
288
+ </hfoption>
289
+ </hfoptions>
290
+
291
+ ```bash
292
+ export MODEL_NAME="stable-diffusion-v1-5/stable-diffusion-v1-5"
293
+ export INSTANCE_DIR="./dog"
294
+ export OUTPUT_DIR="path_to_saved_model"
295
+
296
+ accelerate launch train_dreambooth.py \
297
+ --pretrained_model_name_or_path=$MODEL_NAME \
298
+ --instance_data_dir=$INSTANCE_DIR \
299
+ --output_dir=$OUTPUT_DIR \
300
+ --instance_prompt="a photo of sks dog" \
301
+ --resolution=512 \
302
+ --train_batch_size=1 \
303
+ --gradient_accumulation_steps=1 \
304
+ --learning_rate=5e-6 \
305
+ --lr_scheduler="constant" \
306
+ --lr_warmup_steps=0 \
307
+ --max_train_steps=400 \
308
+ --push_to_hub
309
+ ```
310
+
311
+ Once training is complete, you can use your newly trained model for inference!
312
+
313
+ > [!TIP]
314
+ > Can't wait to try your model for inference before training is complete? 🤭 Make sure you have the latest version of 🤗 Accelerate installed.
315
+ >
316
+ > ```py
317
+ > from diffusers import DiffusionPipeline, UNet2DConditionModel
318
+ > from transformers import CLIPTextModel
319
+ > import torch
320
+ >
321
+ > unet = UNet2DConditionModel.from_pretrained("path/to/model/checkpoint-100/unet")
322
+ >
323
+ > # if you have trained with `--args.train_text_encoder` make sure to also load the text encoder
324
+ > text_encoder = CLIPTextModel.from_pretrained("path/to/model/checkpoint-100/checkpoint-100/text_encoder")
325
+ >
326
+ > pipeline = DiffusionPipeline.from_pretrained(
327
+ > "stable-diffusion-v1-5/stable-diffusion-v1-5", unet=unet, text_encoder=text_encoder, dtype=torch.float16,
328
+ > ).to("cuda")
329
+ >
330
+ > image = pipeline("A photo of sks dog in a bucket", num_inference_steps=50, guidance_scale=7.5).images[0]
331
+ > image.save("dog-bucket.png")
332
+ > ```
333
+
334
+ ```py
335
+ from diffusers import DiffusionPipeline
336
+ import torch
337
+
338
+ pipeline = DiffusionPipeline.from_pretrained("path_to_saved_model", torch_dtype=torch.float16, use_safetensors=True).to("cuda")
339
+ image = pipeline("A photo of sks dog in a bucket", num_inference_steps=50, guidance_scale=7.5).images[0]
340
+ image.save("dog-bucket.png")
341
+ ```
342
+
343
+ ## LoRA
344
+
345
+ LoRA is a training technique for significantly reducing the number of trainable parameters. As a result, training is faster and it is easier to store the resulting weights because they are a lot smaller (~100MBs). Use the [train_dreambooth_lora.py](https://github.com/huggingface/diffusers/blob/main/examples/dreambooth/train_dreambooth_lora.py) script to train with LoRA.
346
+
347
+ The LoRA training script is discussed in more detail in the [LoRA training](lora) guide.
348
+
349
+ ## Stable Diffusion XL
350
+
351
+ Stable Diffusion XL (SDXL) is a powerful text-to-image model that generates high-resolution images, and it adds a second text-encoder to its architecture. Use the [train_dreambooth_lora_sdxl.py](https://github.com/huggingface/diffusers/blob/main/examples/dreambooth/train_dreambooth_lora_sdxl.py) script to train a SDXL model with LoRA.
352
+
353
+ The SDXL training script is discussed in more detail in the [SDXL training](sdxl) guide.
354
+
355
+ ## DeepFloyd IF
356
+
357
+ DeepFloyd IF is a cascading pixel diffusion model with three stages. The first stage generates a base image and the second and third stages progressively upscales the base image into a high-resolution 1024x1024 image. Use the [train_dreambooth_lora.py](https://github.com/huggingface/diffusers/blob/main/examples/dreambooth/train_dreambooth_lora.py) or [train_dreambooth.py](https://github.com/huggingface/diffusers/blob/main/examples/dreambooth/train_dreambooth.py) scripts to train a DeepFloyd IF model with LoRA or the full model.
358
+
359
+ DeepFloyd IF uses predicted variance, but the Diffusers training scripts uses predicted error so the trained DeepFloyd IF models are switched to a fixed variance schedule. The training scripts will update the scheduler config of the fully trained model for you. However, when you load the saved LoRA weights you must also update the pipeline's scheduler config.
360
+
361
+ ```py
362
+ from diffusers import DiffusionPipeline
363
+
364
+ pipe = DiffusionPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", use_safetensors=True)
365
+
366
+ pipe.load_lora_weights("<lora weights path>")
367
+
368
+ # Update scheduler config to fixed variance schedule
369
+ pipe.scheduler = pipe.scheduler.__class__.from_config(pipe.scheduler.config, variance_type="fixed_small")
370
+ ```
371
+
372
+ The stage 2 model requires additional validation images to upscale. You can download and use a downsized version of the training images for this.
373
+
374
+ ```py
375
+ from huggingface_hub import snapshot_download
376
+
377
+ local_dir = "./dog_downsized"
378
+ snapshot_download(
379
+ "diffusers/dog-example-downsized",
380
+ local_dir=local_dir,
381
+ repo_type="dataset",
382
+ ignore_patterns=".gitattributes",
383
+ )
384
+ ```
385
+
386
+ The code samples below provide a brief overview of how to train a DeepFloyd IF model with a combination of DreamBooth and LoRA. Some important parameters to note are:
387
+
388
+ * `--resolution=64`, a much smaller resolution is required because DeepFloyd IF is a pixel diffusion model and to work on uncompressed pixels, the input images must be smaller
389
+ * `--pre_compute_text_embeddings`, compute the text embeddings ahead of time to save memory because the [`~transformers.T5Model`] can take up a lot of memory
390
+ * `--tokenizer_max_length=77`, you can use a longer default text length with T5 as the text encoder but the default model encoding procedure uses a shorter text length
391
+ * `--text_encoder_use_attention_mask`, to pass the attention mask to the text encoder
392
+
393
+ <hfoptions id="IF-DreamBooth">
394
+ <hfoption id="Stage 1 LoRA DreamBooth">
395
+
396
+ Training stage 1 of DeepFloyd IF with LoRA and DreamBooth requires ~28GB of memory.
397
+
398
+ ```bash
399
+ export MODEL_NAME="DeepFloyd/IF-I-XL-v1.0"
400
+ export INSTANCE_DIR="dog"
401
+ export OUTPUT_DIR="dreambooth_dog_lora"
402
+
403
+ accelerate launch train_dreambooth_lora.py \
404
+ --report_to wandb \
405
+ --pretrained_model_name_or_path=$MODEL_NAME \
406
+ --instance_data_dir=$INSTANCE_DIR \
407
+ --output_dir=$OUTPUT_DIR \
408
+ --instance_prompt="a sks dog" \
409
+ --resolution=64 \
410
+ --train_batch_size=4 \
411
+ --gradient_accumulation_steps=1 \
412
+ --learning_rate=5e-6 \
413
+ --scale_lr \
414
+ --max_train_steps=1200 \
415
+ --validation_prompt="a sks dog" \
416
+ --validation_epochs=25 \
417
+ --checkpointing_steps=100 \
418
+ --pre_compute_text_embeddings \
419
+ --tokenizer_max_length=77 \
420
+ --text_encoder_use_attention_mask
421
+ ```
422
+
423
+ </hfoption>
424
+ <hfoption id="Stage 2 LoRA DreamBooth">
425
+
426
+ For stage 2 of DeepFloyd IF with LoRA and DreamBooth, pay attention to these parameters:
427
+
428
+ * `--validation_images`, the images to upscale during validation
429
+ * `--class_labels_conditioning=timesteps`, to additionally conditional the UNet as needed in stage 2
430
+ * `--learning_rate=1e-6`, a lower learning rate is used compared to stage 1
431
+ * `--resolution=256`, the expected resolution for the upscaler
432
+
433
+ ```bash
434
+ export MODEL_NAME="DeepFloyd/IF-II-L-v1.0"
435
+ export INSTANCE_DIR="dog"
436
+ export OUTPUT_DIR="dreambooth_dog_upscale"
437
+ export VALIDATION_IMAGES="dog_downsized/image_1.png dog_downsized/image_2.png dog_downsized/image_3.png dog_downsized/image_4.png"
438
+
439
+ python train_dreambooth_lora.py \
440
+ --report_to wandb \
441
+ --pretrained_model_name_or_path=$MODEL_NAME \
442
+ --instance_data_dir=$INSTANCE_DIR \
443
+ --output_dir=$OUTPUT_DIR \
444
+ --instance_prompt="a sks dog" \
445
+ --resolution=256 \
446
+ --train_batch_size=4 \
447
+ --gradient_accumulation_steps=1 \
448
+ --learning_rate=1e-6 \
449
+ --max_train_steps=2000 \
450
+ --validation_prompt="a sks dog" \
451
+ --validation_epochs=100 \
452
+ --checkpointing_steps=500 \
453
+ --pre_compute_text_embeddings \
454
+ --tokenizer_max_length=77 \
455
+ --text_encoder_use_attention_mask \
456
+ --validation_images $VALIDATION_IMAGES \
457
+ --class_labels_conditioning=timesteps
458
+ ```
459
+
460
+ </hfoption>
461
+ <hfoption id="Stage 1 DreamBooth">
462
+
463
+ For stage 1 of DeepFloyd IF with DreamBooth, pay attention to these parameters:
464
+
465
+ * `--skip_save_text_encoder`, to skip saving the full T5 text encoder with the finetuned model
466
+ * `--use_8bit_adam`, to use 8-bit Adam optimizer to save memory due to the size of the optimizer state when training the full model
467
+ * `--learning_rate=1e-7`, a really low learning rate should be used for full model training otherwise the model quality is degraded (you can use a higher learning rate with a larger batch size)
468
+
469
+ Training with 8-bit Adam and a batch size of 4, the full model can be trained with ~48GB of memory.
470
+
471
+ ```bash
472
+ export MODEL_NAME="DeepFloyd/IF-I-XL-v1.0"
473
+ export INSTANCE_DIR="dog"
474
+ export OUTPUT_DIR="dreambooth_if"
475
+
476
+ accelerate launch train_dreambooth.py \
477
+ --pretrained_model_name_or_path=$MODEL_NAME \
478
+ --instance_data_dir=$INSTANCE_DIR \
479
+ --output_dir=$OUTPUT_DIR \
480
+ --instance_prompt="a photo of sks dog" \
481
+ --resolution=64 \
482
+ --train_batch_size=4 \
483
+ --gradient_accumulation_steps=1 \
484
+ --learning_rate=1e-7 \
485
+ --max_train_steps=150 \
486
+ --validation_prompt "a photo of sks dog" \
487
+ --validation_steps 25 \
488
+ --text_encoder_use_attention_mask \
489
+ --tokenizer_max_length 77 \
490
+ --pre_compute_text_embeddings \
491
+ --use_8bit_adam \
492
+ --set_grads_to_none \
493
+ --skip_save_text_encoder \
494
+ --push_to_hub
495
+ ```
496
+
497
+ </hfoption>
498
+ <hfoption id="Stage 2 DreamBooth">
499
+
500
+ For stage 2 of DeepFloyd IF with DreamBooth, pay attention to these parameters:
501
+
502
+ * `--learning_rate=5e-6`, use a lower learning rate with a smaller effective batch size
503
+ * `--resolution=256`, the expected resolution for the upscaler
504
+ * `--train_batch_size=2` and `--gradient_accumulation_steps=6`, to effectively train on images with faces requires larger batch sizes
505
+
506
+ ```bash
507
+ export MODEL_NAME="DeepFloyd/IF-II-L-v1.0"
508
+ export INSTANCE_DIR="dog"
509
+ export OUTPUT_DIR="dreambooth_dog_upscale"
510
+ export VALIDATION_IMAGES="dog_downsized/image_1.png dog_downsized/image_2.png dog_downsized/image_3.png dog_downsized/image_4.png"
511
+
512
+ accelerate launch train_dreambooth.py \
513
+ --report_to wandb \
514
+ --pretrained_model_name_or_path=$MODEL_NAME \
515
+ --instance_data_dir=$INSTANCE_DIR \
516
+ --output_dir=$OUTPUT_DIR \
517
+ --instance_prompt="a sks dog" \
518
+ --resolution=256 \
519
+ --train_batch_size=2 \
520
+ --gradient_accumulation_steps=6 \
521
+ --learning_rate=5e-6 \
522
+ --max_train_steps=2000 \
523
+ --validation_prompt="a sks dog" \
524
+ --validation_steps=150 \
525
+ --checkpointing_steps=500 \
526
+ --pre_compute_text_embeddings \
527
+ --tokenizer_max_length=77 \
528
+ --text_encoder_use_attention_mask \
529
+ --validation_images $VALIDATION_IMAGES \
530
+ --class_labels_conditioning timesteps \
531
+ --push_to_hub
532
+ ```
533
+
534
+ </hfoption>
535
+ </hfoptions>
536
+
537
+ ### Training tips
538
+
539
+ Training the DeepFloyd IF model can be challenging, but here are some tips that we've found helpful:
540
+
541
+ - LoRA is sufficient for training the stage 1 model because the model's low resolution makes representing finer details difficult regardless.
542
+ - For common or simple objects, you don't necessarily need to finetune the upscaler. Make sure the prompt passed to the upscaler is adjusted to remove the new token from the instance prompt. For example, if your stage 1 prompt is "a sks dog" then your stage 2 prompt should be "a dog".
543
+ - For finer details like faces, fully training the stage 2 upscaler is better than training the stage 2 model with LoRA. It also helps to use lower learning rates with larger batch sizes.
544
+ - Lower learning rates should be used to train the stage 2 model.
545
+ - The [`DDPMScheduler`] works better than the DPMSolver used in the training scripts.
546
+
547
+ ## Next steps
548
+
549
+ Congratulations on training your DreamBooth model! To learn more about how to use your new model, the following guide may be helpful:
550
+
551
+ - Learn how to [load a DreamBooth](../using-diffusers/dreambooth) model for inference if you trained your model with LoRA.