Stage Harbor release files 81001-81500
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/optimization/xformers.md +29 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/quantization/bitsandbytes.md +452 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/quantization/gguf.md +120 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/quantization/modelopt.md +141 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/quantization/overview.md +141 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/quantization/quanto.md +148 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/quantization/torchao.md +170 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/quicktour.md +232 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/stable_diffusion.md +132 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/training/adapt_a_model.md +47 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/training/cogvideox.md +291 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/training/controlnet.md +278 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/training/create_dataset.md +84 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/training/custom_diffusion.md +354 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/training/ddpo.md +17 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/training/distributed_inference.md +392 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/training/dreambooth.md +551 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/training/instructpix2pix.md +243 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/training/kandinsky.md +312 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/training/lcm_distill.md +249 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/training/lora.md +202 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/training/overview.md +63 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/training/sdxl.md +254 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/training/t2i_adapters.md +218 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/training/text2image.md +182 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/training/text_inversion.md +206 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/training/unconditional_training.md +198 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/training/wuerstchen.md +180 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/tutorials/autopipeline.md +67 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/tutorials/basic_training.md +395 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/tutorials/using_peft_for_inference.md +691 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/automodel.md +128 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/batched_inference.md +173 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/callback.md +136 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/conditional_image_generation.md +307 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/consisid.md +96 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/controlling_generation.md +177 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/controlnet.md +346 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/create_a_server.md +61 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/custom_pipeline_overview.md +172 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/depth2img.md +46 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/diffedit.md +282 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/dreambooth.md +35 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/guiders.md +161 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/helios.md +133 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/image_quality.md +140 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/img2img.md +596 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/inference_with_lcm.md +631 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/inference_with_tcd_lora.md +437 -0
- tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/inpaint.md +800 -0
tasks/tasksmith-deb681b2c96c/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 it with [`~ModelMixin.set_attention_backend`] as shown in the [Attention backends](./attention_backends) guide.
|
| 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-deb681b2c96c/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 |
+

|
| 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-deb681b2c96c/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-deb681b2c96c/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/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/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/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-deb681b2c96c/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-deb681b2c96c/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-deb681b2c96c/tests/source/docs/source/en/quantization/torchao.md
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
quantization_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 |
+
quantization_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 |
+
quantization_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 |
+
## Supported quantization types
|
| 87 |
+
|
| 88 |
+
torchao supports weight-only quantization and weight and dynamic-activation quantization for int8, float3-float8, and uint1-uint7.
|
| 89 |
+
|
| 90 |
+
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.
|
| 91 |
+
|
| 92 |
+
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.
|
| 93 |
+
|
| 94 |
+
The quantization methods supported are as follows:
|
| 95 |
+
|
| 96 |
+
| **Category** | **Full Function Names** | **Shorthands** |
|
| 97 |
+
|--------------|-------------------------|----------------|
|
| 98 |
+
| **Integer quantization** | `int4_weight_only`, `int8_dynamic_activation_int4_weight`, `int8_weight_only`, `int8_dynamic_activation_int8_weight` | `int4wo`, `int4dq`, `int8wo`, `int8dq` |
|
| 99 |
+
| **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` |
|
| 100 |
+
| **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` |
|
| 101 |
+
| **Unsigned Integer quantization** | `uintx_weight_only` | `uint1wo`, `uint2wo`, `uint3wo`, `uint4wo`, `uint5wo`, `uint6wo`, `uint7wo` |
|
| 102 |
+
|
| 103 |
+
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.
|
| 104 |
+
|
| 105 |
+
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.
|
| 106 |
+
|
| 107 |
+
## Serializing and Deserializing quantized models
|
| 108 |
+
|
| 109 |
+
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.
|
| 110 |
+
|
| 111 |
+
```python
|
| 112 |
+
import torch
|
| 113 |
+
from diffusers import AutoModel, TorchAoConfig
|
| 114 |
+
|
| 115 |
+
quantization_config = TorchAoConfig("int8wo")
|
| 116 |
+
transformer = AutoModel.from_pretrained(
|
| 117 |
+
"black-forest-labs/Flux.1-Dev",
|
| 118 |
+
subfolder="transformer",
|
| 119 |
+
quantization_config=quantization_config,
|
| 120 |
+
torch_dtype=torch.bfloat16,
|
| 121 |
+
)
|
| 122 |
+
transformer.save_pretrained("/path/to/flux_int8wo", safe_serialization=False)
|
| 123 |
+
```
|
| 124 |
+
|
| 125 |
+
To load a serialized quantized model, use the [`~ModelMixin.from_pretrained`] method.
|
| 126 |
+
|
| 127 |
+
```python
|
| 128 |
+
import torch
|
| 129 |
+
from diffusers import FluxPipeline, AutoModel
|
| 130 |
+
|
| 131 |
+
transformer = AutoModel.from_pretrained("/path/to/flux_int8wo", torch_dtype=torch.bfloat16, use_safetensors=False)
|
| 132 |
+
pipe = FluxPipeline.from_pretrained("black-forest-labs/Flux.1-Dev", transformer=transformer, torch_dtype=torch.bfloat16)
|
| 133 |
+
pipe.to("cuda")
|
| 134 |
+
|
| 135 |
+
prompt = "A cat holding a sign that says hello world"
|
| 136 |
+
image = pipe(prompt, num_inference_steps=30, guidance_scale=7.0).images[0]
|
| 137 |
+
image.save("output.png")
|
| 138 |
+
```
|
| 139 |
+
|
| 140 |
+
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.
|
| 141 |
+
|
| 142 |
+
```python
|
| 143 |
+
import torch
|
| 144 |
+
from accelerate import init_empty_weights
|
| 145 |
+
from diffusers import FluxPipeline, AutoModel, TorchAoConfig
|
| 146 |
+
|
| 147 |
+
# Serialize the model
|
| 148 |
+
transformer = AutoModel.from_pretrained(
|
| 149 |
+
"black-forest-labs/Flux.1-Dev",
|
| 150 |
+
subfolder="transformer",
|
| 151 |
+
quantization_config=TorchAoConfig("uint4wo"),
|
| 152 |
+
torch_dtype=torch.bfloat16,
|
| 153 |
+
)
|
| 154 |
+
transformer.save_pretrained("/path/to/flux_uint4wo", safe_serialization=False, max_shard_size="50GB")
|
| 155 |
+
# ...
|
| 156 |
+
|
| 157 |
+
# Load the model
|
| 158 |
+
state_dict = torch.load("/path/to/flux_uint4wo/diffusion_pytorch_model.bin", weights_only=False, map_location="cpu")
|
| 159 |
+
with init_empty_weights():
|
| 160 |
+
transformer = AutoModel.from_config("/path/to/flux_uint4wo/config.json")
|
| 161 |
+
transformer.load_state_dict(state_dict, strict=True, assign=True)
|
| 162 |
+
```
|
| 163 |
+
|
| 164 |
+
> [!TIP]
|
| 165 |
+
> The [`AutoModel`] API is supported for PyTorch >= 2.6 as shown in the examples below.
|
| 166 |
+
|
| 167 |
+
## Resources
|
| 168 |
+
|
| 169 |
+
- [TorchAO Quantization API](https://docs.pytorch.org/ao/stable/index.html)
|
| 170 |
+
- [Diffusers-TorchAO examples](https://github.com/sayakpaul/diffusers-torchao)
|
tasks/tasksmith-deb681b2c96c/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-deb681b2c96c/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-deb681b2c96c/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-deb681b2c96c/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-deb681b2c96c/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-deb681b2c96c/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-deb681b2c96c/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-deb681b2c96c/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-deb681b2c96c/tests/source/docs/source/en/training/distributed_inference.md
ADDED
|
@@ -0,0 +1,392 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 --nproc_per_node=2 run_distributed.py
|
| 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 |
+
Most attention backends are compatible with context parallelism. Open an [issue](https://github.com/huggingface/diffusers/issues/new) if a backend is not compatible.
|
| 241 |
+
|
| 242 |
+
### Ring Attention
|
| 243 |
+
|
| 244 |
+
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.
|
| 245 |
+
|
| 246 |
+
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.
|
| 247 |
+
|
| 248 |
+
```py
|
| 249 |
+
import torch
|
| 250 |
+
from torch import distributed as dist
|
| 251 |
+
from diffusers import DiffusionPipeline, ContextParallelConfig
|
| 252 |
+
|
| 253 |
+
def setup_distributed():
|
| 254 |
+
if not dist.is_initialized():
|
| 255 |
+
dist.init_process_group(backend="nccl")
|
| 256 |
+
rank = dist.get_rank()
|
| 257 |
+
device = torch.device(f"cuda:{rank}")
|
| 258 |
+
torch.cuda.set_device(device)
|
| 259 |
+
return device
|
| 260 |
+
|
| 261 |
+
def main():
|
| 262 |
+
device = setup_distributed()
|
| 263 |
+
world_size = dist.get_world_size()
|
| 264 |
+
|
| 265 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
| 266 |
+
"black-forest-labs/FLUX.1-dev", torch_dtype=torch.bfloat16
|
| 267 |
+
).to(device)
|
| 268 |
+
pipeline.transformer.set_attention_backend("_native_cudnn")
|
| 269 |
+
|
| 270 |
+
cp_config = ContextParallelConfig(ring_degree=world_size)
|
| 271 |
+
pipeline.transformer.enable_parallelism(config=cp_config)
|
| 272 |
+
|
| 273 |
+
prompt = """
|
| 274 |
+
cinematic film still of a cat sipping a margarita in a pool in Palm Springs, California
|
| 275 |
+
highly detailed, high budget hollywood movie, cinemascope, moody, epic, gorgeous, film grain
|
| 276 |
+
"""
|
| 277 |
+
|
| 278 |
+
# Must specify generator so all ranks start with same latents (or pass your own)
|
| 279 |
+
generator = torch.Generator().manual_seed(42)
|
| 280 |
+
image = pipeline(
|
| 281 |
+
prompt,
|
| 282 |
+
guidance_scale=3.5,
|
| 283 |
+
num_inference_steps=50,
|
| 284 |
+
generator=generator,
|
| 285 |
+
).images[0]
|
| 286 |
+
|
| 287 |
+
if dist.get_rank() == 0:
|
| 288 |
+
image.save(f"output.png")
|
| 289 |
+
|
| 290 |
+
if dist.is_initialized():
|
| 291 |
+
dist.destroy_process_group()
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
if __name__ == "__main__":
|
| 295 |
+
main()
|
| 296 |
+
```
|
| 297 |
+
|
| 298 |
+
The script above needs to be run with a distributed launcher, such as [torchrun](https://docs.pytorch.org/docs/stable/elastic/run.html), that is compatible with PyTorch. `--nproc-per-node` is set to the number of GPUs available.
|
| 299 |
+
|
| 300 |
+
```shell
|
| 301 |
+
torchrun --nproc-per-node 2 above_script.py
|
| 302 |
+
```
|
| 303 |
+
|
| 304 |
+
### Ulysses Attention
|
| 305 |
+
|
| 306 |
+
[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.
|
| 307 |
+
|
| 308 |
+
[`ContextParallelConfig`] supports Ulysses Attention through the `ulysses_degree` argument. This determines how many devices to use for Ulysses Attention.
|
| 309 |
+
|
| 310 |
+
Pass the [`ContextParallelConfig`] to [`~ModelMixin.enable_parallelism`].
|
| 311 |
+
|
| 312 |
+
```py
|
| 313 |
+
# Depending on the number of GPUs available.
|
| 314 |
+
pipeline.transformer.enable_parallelism(config=ContextParallelConfig(ulysses_degree=2))
|
| 315 |
+
```
|
| 316 |
+
|
| 317 |
+
### Unified Attention
|
| 318 |
+
|
| 319 |
+
[Unified Sequence Parallelism](https://huggingface.co/papers/2405.07719) combines Ring Attention and Ulysses Attention into a single approach for efficient long-sequence processing. It applies Ulysses's *all-to-all* communication first to redistribute heads and sequence tokens, then uses Ring Attention to process the redistributed data, and finally reverses the *all-to-all* to restore the original layout.
|
| 320 |
+
|
| 321 |
+
This hybrid approach leverages the strengths of both methods:
|
| 322 |
+
- **Ulysses Attention** efficiently parallelizes across attention heads
|
| 323 |
+
- **Ring Attention** handles very long sequences with minimal memory overhead
|
| 324 |
+
- Together, they enable 2D parallelization across both heads and sequence dimensions
|
| 325 |
+
|
| 326 |
+
[`ContextParallelConfig`] supports Unified Attention by specifying both `ulysses_degree` and `ring_degree`. The total number of devices used is `ulysses_degree * ring_degree`, arranged in a 2D grid where Ulysses and Ring groups are orthogonal (non-overlapping).
|
| 327 |
+
Pass the [`ContextParallelConfig`] with both `ulysses_degree` and `ring_degree` set to bigger than 1 to [`~ModelMixin.enable_parallelism`].
|
| 328 |
+
|
| 329 |
+
```py
|
| 330 |
+
pipeline.transformer.enable_parallelism(config=ContextParallelConfig(ulysses_degree=2, ring_degree=2))
|
| 331 |
+
```
|
| 332 |
+
|
| 333 |
+
> [!TIP]
|
| 334 |
+
> Unified Attention is to be used when there are enough devices to arrange in a 2D grid (at least 4 devices).
|
| 335 |
+
|
| 336 |
+
We ran a benchmark with Ulysess, Ring, and Unified Attention with [this script](https://github.com/huggingface/diffusers/pull/12693#issuecomment-3694727532) on a node of 4 H100 GPUs. The results are summarized as follows:
|
| 337 |
+
|
| 338 |
+
| CP Backend | Time / Iter (ms) | Steps / Sec | Peak Memory (GB) |
|
| 339 |
+
|--------------------|------------------|-------------|------------------|
|
| 340 |
+
| ulysses | 6670.789 | 7.50 | 33.85 |
|
| 341 |
+
| ring | 13076.492 | 3.82 | 56.02 |
|
| 342 |
+
| unified_balanced | 11068.705 | 4.52 | 33.85 |
|
| 343 |
+
|
| 344 |
+
From the above table, it's clear that Ulysses provides better throughput, but the number of devices it can use remains limited to the number of attention heads, a limitation that is solved by unified attention.
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
### Ulysses Anything Attention
|
| 348 |
+
|
| 349 |
+
The default Ulysses Attention mechanism requires that the sequence length of hidden states must be divisible by the number of devices. This imposes significant limitations on the practical application of Ulysses Attention. [Ulysses Anything Attention](https://github.com/huggingface/diffusers/pull/12996) is a variant of Ulysses Attention that supports arbitrary sequence lengths and arbitrary numbers of attention heads, thereby enhancing the versatility of Ulysses Attention in practical use.
|
| 350 |
+
|
| 351 |
+
[`ContextParallelConfig`] supports Ulysses Anything Attention by specifying both `ulysses_degree` and `ulysses_anything`. Please note that Ulysses Anything Attention is not currently supported by Unified Attention. Pass the [`ContextParallelConfig`] with both `ulysses_degree` set to bigger than 1 and `ulysses_anything=True` to [`~ModelMixin.enable_parallelism`].
|
| 352 |
+
|
| 353 |
+
```py
|
| 354 |
+
pipeline.transformer.enable_parallelism(config=ContextParallelConfig(ulysses_degree=2, ulysses_anything=True))
|
| 355 |
+
```
|
| 356 |
+
|
| 357 |
+
> [!TIP] To avoid multiple forced CUDA sync caused by H2D and D2H transfers, please add the **gloo** backend in `init_process_group`. This will significantly reduce communication latency.
|
| 358 |
+
|
| 359 |
+
We ran a benchmark for FLUX.1-dev with Ulysses, Ring, Unified Attention and Ulysses Anything Attention with [this script](https://github.com/huggingface/diffusers/pull/12996#issuecomment-3797695999) on a node of 4 L20 GPUs. The results are summarized as follows:
|
| 360 |
+
|
| 361 |
+
| CP Backend | Time / Iter (ms) | Steps / Sec | Peak Memory (GB) | Shape (HxW)|
|
| 362 |
+
|--------------------|------------------|-------------|------------------|------------|
|
| 363 |
+
| ulysses | 281.07 | 3.56 | 37.11 | 1024x1024 |
|
| 364 |
+
| ring | 351.34 | 2.85 | 37.01 | 1024x1024 |
|
| 365 |
+
| unified_balanced | 324.37 | 3.08 | 37.16 | 1024x1024 |
|
| 366 |
+
| ulysses_anything | 280.94 | 3.56 | 37.11 | 1024x1024 |
|
| 367 |
+
| ulysses | failed | failed | failed | 1008x1008 |
|
| 368 |
+
| ring | failed | failed | failed | 1008x1008 |
|
| 369 |
+
| unified_balanced | failed | failed | failed | 1008x1008 |
|
| 370 |
+
| ulysses_anything | 278.40 | 3.59 | 36.99 | 1008x1008 |
|
| 371 |
+
|
| 372 |
+
From the above table, it is clear that Ulysses Anything Attention offers better compatibility with arbitrary sequence lengths while maintaining the same performance as the standard Ulysses Attention.
|
| 373 |
+
|
| 374 |
+
### parallel_config
|
| 375 |
+
|
| 376 |
+
Pass `parallel_config` during model initialization to enable context parallelism.
|
| 377 |
+
|
| 378 |
+
```py
|
| 379 |
+
CKPT_ID = "black-forest-labs/FLUX.1-dev"
|
| 380 |
+
|
| 381 |
+
cp_config = ContextParallelConfig(ring_degree=2)
|
| 382 |
+
transformer = AutoModel.from_pretrained(
|
| 383 |
+
CKPT_ID,
|
| 384 |
+
subfolder="transformer",
|
| 385 |
+
torch_dtype=torch.bfloat16,
|
| 386 |
+
parallel_config=cp_config
|
| 387 |
+
)
|
| 388 |
+
|
| 389 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
| 390 |
+
CKPT_ID, transformer=transformer, torch_dtype=torch.bfloat16,
|
| 391 |
+
).to(device)
|
| 392 |
+
```
|
tasks/tasksmith-deb681b2c96c/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.
|
tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/training/instructpix2pix.md
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# InstructPix2Pix
|
| 14 |
+
|
| 15 |
+
[InstructPix2Pix](https://hf.co/papers/2211.09800) is a Stable Diffusion model trained to edit images from human-provided instructions. For example, your prompt can be "turn the clouds rainy" and the model will edit the input image accordingly. This model is conditioned on the text prompt (or editing instruction) and the input image.
|
| 16 |
+
|
| 17 |
+
This guide will explore the [train_instruct_pix2pix.py](https://github.com/huggingface/diffusers/blob/main/examples/instruct_pix2pix/train_instruct_pix2pix.py) training script to help you become familiar with it, and how you can adapt it for your own use case.
|
| 18 |
+
|
| 19 |
+
Before running the script, make sure you install the library from source:
|
| 20 |
+
|
| 21 |
+
```bash
|
| 22 |
+
git clone https://github.com/huggingface/diffusers
|
| 23 |
+
cd diffusers
|
| 24 |
+
pip install .
|
| 25 |
+
```
|
| 26 |
+
|
| 27 |
+
Then navigate to the example folder containing the training script and install the required dependencies for the script you're using:
|
| 28 |
+
|
| 29 |
+
```bash
|
| 30 |
+
cd examples/instruct_pix2pix
|
| 31 |
+
pip install -r requirements.txt
|
| 32 |
+
```
|
| 33 |
+
|
| 34 |
+
> [!TIP]
|
| 35 |
+
> 🤗 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.
|
| 36 |
+
|
| 37 |
+
Initialize an 🤗 Accelerate environment:
|
| 38 |
+
|
| 39 |
+
```bash
|
| 40 |
+
accelerate config
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
To setup a default 🤗 Accelerate environment without choosing any configurations:
|
| 44 |
+
|
| 45 |
+
```bash
|
| 46 |
+
accelerate config default
|
| 47 |
+
```
|
| 48 |
+
|
| 49 |
+
Or if your environment doesn't support an interactive shell, like a notebook, you can use:
|
| 50 |
+
|
| 51 |
+
```py
|
| 52 |
+
from accelerate.utils import write_basic_config
|
| 53 |
+
|
| 54 |
+
write_basic_config()
|
| 55 |
+
```
|
| 56 |
+
|
| 57 |
+
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.
|
| 58 |
+
|
| 59 |
+
> [!TIP]
|
| 60 |
+
> 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/instruct_pix2pix/train_instruct_pix2pix.py) and let us know if you have any questions or concerns.
|
| 61 |
+
|
| 62 |
+
## Script parameters
|
| 63 |
+
|
| 64 |
+
The training script has 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/instruct_pix2pix/train_instruct_pix2pix.py#L65) function. Default values are provided for most parameters that work pretty well, but you can also set your own values in the training command if you'd like.
|
| 65 |
+
|
| 66 |
+
For example, to increase the resolution of the input image:
|
| 67 |
+
|
| 68 |
+
```bash
|
| 69 |
+
accelerate launch train_instruct_pix2pix.py \
|
| 70 |
+
--resolution=512 \
|
| 71 |
+
```
|
| 72 |
+
|
| 73 |
+
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 InstructPix2Pix:
|
| 74 |
+
|
| 75 |
+
- `--original_image_column`: the original image before the edits are made
|
| 76 |
+
- `--edited_image_column`: the image after the edits are made
|
| 77 |
+
- `--edit_prompt_column`: the instructions to edit the image
|
| 78 |
+
- `--conditioning_dropout_prob`: the dropout probability for the edited image and edit prompts during training which enables classifier-free guidance (CFG) for one or both conditioning inputs
|
| 79 |
+
|
| 80 |
+
## Training script
|
| 81 |
+
|
| 82 |
+
The dataset preprocessing code and training loop are found in the [`main()`](https://github.com/huggingface/diffusers/blob/64603389da01082055a901f2883c4810d1144edb/examples/instruct_pix2pix/train_instruct_pix2pix.py#L374) function. This is where you'll make your changes to the training script to adapt it for your own use-case.
|
| 83 |
+
|
| 84 |
+
As with the script parameters, a 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 InstructPix2Pix relevant parts of the script.
|
| 85 |
+
|
| 86 |
+
The script begins by modifying the [number of input channels](https://github.com/huggingface/diffusers/blob/64603389da01082055a901f2883c4810d1144edb/examples/instruct_pix2pix/train_instruct_pix2pix.py#L445) in the first convolutional layer of the UNet to account for InstructPix2Pix's additional conditioning image:
|
| 87 |
+
|
| 88 |
+
```py
|
| 89 |
+
in_channels = 8
|
| 90 |
+
out_channels = unet.conv_in.out_channels
|
| 91 |
+
unet.register_to_config(in_channels=in_channels)
|
| 92 |
+
|
| 93 |
+
with torch.no_grad():
|
| 94 |
+
new_conv_in = nn.Conv2d(
|
| 95 |
+
in_channels, out_channels, unet.conv_in.kernel_size, unet.conv_in.stride, unet.conv_in.padding
|
| 96 |
+
)
|
| 97 |
+
new_conv_in.weight.zero_()
|
| 98 |
+
new_conv_in.weight[:, :4, :, :].copy_(unet.conv_in.weight)
|
| 99 |
+
unet.conv_in = new_conv_in
|
| 100 |
+
```
|
| 101 |
+
|
| 102 |
+
These UNet parameters are [updated](https://github.com/huggingface/diffusers/blob/64603389da01082055a901f2883c4810d1144edb/examples/instruct_pix2pix/train_instruct_pix2pix.py#L545C1-L551C6) by the optimizer:
|
| 103 |
+
|
| 104 |
+
```py
|
| 105 |
+
optimizer = optimizer_cls(
|
| 106 |
+
unet.parameters(),
|
| 107 |
+
lr=args.learning_rate,
|
| 108 |
+
betas=(args.adam_beta1, args.adam_beta2),
|
| 109 |
+
weight_decay=args.adam_weight_decay,
|
| 110 |
+
eps=args.adam_epsilon,
|
| 111 |
+
)
|
| 112 |
+
```
|
| 113 |
+
|
| 114 |
+
Next, the edited images and edit instructions are [preprocessed](https://github.com/huggingface/diffusers/blob/64603389da01082055a901f2883c4810d1144edb/examples/instruct_pix2pix/train_instruct_pix2pix.py#L624) and [tokenized](https://github.com/huggingface/diffusers/blob/64603389da01082055a901f2883c4810d1144edb/examples/instruct_pix2pix/train_instruct_pix2pix.py#L610C24-L610C24). It is important the same image transformations are applied to the original and edited images.
|
| 115 |
+
|
| 116 |
+
```py
|
| 117 |
+
def preprocess_train(examples):
|
| 118 |
+
preprocessed_images = preprocess_images(examples)
|
| 119 |
+
|
| 120 |
+
original_images, edited_images = preprocessed_images.chunk(2)
|
| 121 |
+
original_images = original_images.reshape(-1, 3, args.resolution, args.resolution)
|
| 122 |
+
edited_images = edited_images.reshape(-1, 3, args.resolution, args.resolution)
|
| 123 |
+
|
| 124 |
+
examples["original_pixel_values"] = original_images
|
| 125 |
+
examples["edited_pixel_values"] = edited_images
|
| 126 |
+
|
| 127 |
+
captions = list(examples[edit_prompt_column])
|
| 128 |
+
examples["input_ids"] = tokenize_captions(captions)
|
| 129 |
+
return examples
|
| 130 |
+
```
|
| 131 |
+
|
| 132 |
+
Finally, in the [training loop](https://github.com/huggingface/diffusers/blob/64603389da01082055a901f2883c4810d1144edb/examples/instruct_pix2pix/train_instruct_pix2pix.py#L730), it starts by encoding the edited images into latent space:
|
| 133 |
+
|
| 134 |
+
```py
|
| 135 |
+
latents = vae.encode(batch["edited_pixel_values"].to(weight_dtype)).latent_dist.sample()
|
| 136 |
+
latents = latents * vae.config.scaling_factor
|
| 137 |
+
```
|
| 138 |
+
|
| 139 |
+
Then, the script applies dropout to the original image and edit instruction embeddings to support CFG. This is what enables the model to modulate the influence of the edit instruction and original image on the edited image.
|
| 140 |
+
|
| 141 |
+
```py
|
| 142 |
+
encoder_hidden_states = text_encoder(batch["input_ids"])[0]
|
| 143 |
+
original_image_embeds = vae.encode(batch["original_pixel_values"].to(weight_dtype)).latent_dist.mode()
|
| 144 |
+
|
| 145 |
+
if args.conditioning_dropout_prob is not None:
|
| 146 |
+
random_p = torch.rand(bsz, device=latents.device, generator=generator)
|
| 147 |
+
prompt_mask = random_p < 2 * args.conditioning_dropout_prob
|
| 148 |
+
prompt_mask = prompt_mask.reshape(bsz, 1, 1)
|
| 149 |
+
null_conditioning = text_encoder(tokenize_captions([""]).to(accelerator.device))[0]
|
| 150 |
+
encoder_hidden_states = torch.where(prompt_mask, null_conditioning, encoder_hidden_states)
|
| 151 |
+
|
| 152 |
+
image_mask_dtype = original_image_embeds.dtype
|
| 153 |
+
image_mask = 1 - (
|
| 154 |
+
(random_p >= args.conditioning_dropout_prob).to(image_mask_dtype)
|
| 155 |
+
* (random_p < 3 * args.conditioning_dropout_prob).to(image_mask_dtype)
|
| 156 |
+
)
|
| 157 |
+
image_mask = image_mask.reshape(bsz, 1, 1, 1)
|
| 158 |
+
original_image_embeds = image_mask * original_image_embeds
|
| 159 |
+
```
|
| 160 |
+
|
| 161 |
+
That's pretty much it! Aside from the differences described here, the rest of the script is very similar to the [Text-to-image](text2image#training-script) training script, so feel free to check it out for more details. 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.
|
| 162 |
+
|
| 163 |
+
## Launch the script
|
| 164 |
+
|
| 165 |
+
Once you're happy with the changes to your script or if you're okay with the default configuration, you're ready to launch the training script! 🚀
|
| 166 |
+
|
| 167 |
+
This guide uses the [fusing/instructpix2pix-1000-samples](https://huggingface.co/datasets/fusing/instructpix2pix-1000-samples) dataset, which is a smaller version of the [original dataset](https://huggingface.co/datasets/timbrooks/instructpix2pix-clip-filtered). You can also create and use your own dataset if you'd like (see the [Create a dataset for training](create_dataset) guide).
|
| 168 |
+
|
| 169 |
+
Set the `MODEL_NAME` environment variable to the name of the model (can be a model id on the Hub or a path to a local model), and the `DATASET_ID` to the name of the dataset on the Hub. The script creates and saves all the components (feature extractor, scheduler, text encoder, UNet, etc.) to a subfolder in your repository.
|
| 170 |
+
|
| 171 |
+
> [!TIP]
|
| 172 |
+
> For better results, try longer training runs with a larger dataset. We've only tested this training script on a smaller-scale dataset.
|
| 173 |
+
>
|
| 174 |
+
> <br>
|
| 175 |
+
>
|
| 176 |
+
> To monitor training progress with Weights and Biases, add the `--report_to=wandb` parameter to the training command and specify a validation image with `--val_image_url` and a validation prompt with `--validation_prompt`. This can be really useful for debugging the model.
|
| 177 |
+
|
| 178 |
+
If you’re training on more than one GPU, add the `--multi_gpu` parameter to the `accelerate launch` command.
|
| 179 |
+
|
| 180 |
+
```bash
|
| 181 |
+
accelerate launch --mixed_precision="fp16" train_instruct_pix2pix.py \
|
| 182 |
+
--pretrained_model_name_or_path=$MODEL_NAME \
|
| 183 |
+
--dataset_name=$DATASET_ID \
|
| 184 |
+
--enable_xformers_memory_efficient_attention \
|
| 185 |
+
--resolution=256 \
|
| 186 |
+
--random_flip \
|
| 187 |
+
--train_batch_size=4 \
|
| 188 |
+
--gradient_accumulation_steps=4 \
|
| 189 |
+
--gradient_checkpointing \
|
| 190 |
+
--max_train_steps=15000 \
|
| 191 |
+
--checkpointing_steps=5000 \
|
| 192 |
+
--checkpoints_total_limit=1 \
|
| 193 |
+
--learning_rate=5e-05 \
|
| 194 |
+
--max_grad_norm=1 \
|
| 195 |
+
--lr_warmup_steps=0 \
|
| 196 |
+
--conditioning_dropout_prob=0.05 \
|
| 197 |
+
--mixed_precision=fp16 \
|
| 198 |
+
--seed=42 \
|
| 199 |
+
--push_to_hub
|
| 200 |
+
```
|
| 201 |
+
|
| 202 |
+
After training is finished, you can use your new InstructPix2Pix for inference:
|
| 203 |
+
|
| 204 |
+
```py
|
| 205 |
+
import PIL
|
| 206 |
+
import requests
|
| 207 |
+
import torch
|
| 208 |
+
from diffusers import StableDiffusionInstructPix2PixPipeline
|
| 209 |
+
from diffusers.utils import load_image
|
| 210 |
+
|
| 211 |
+
pipeline = StableDiffusionInstructPix2PixPipeline.from_pretrained("your_cool_model", torch_dtype=torch.float16).to("cuda")
|
| 212 |
+
generator = torch.Generator("cuda").manual_seed(0)
|
| 213 |
+
|
| 214 |
+
image = load_image("https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/test_pix2pix_4.png")
|
| 215 |
+
prompt = "add some ducks to the lake"
|
| 216 |
+
num_inference_steps = 20
|
| 217 |
+
image_guidance_scale = 1.5
|
| 218 |
+
guidance_scale = 10
|
| 219 |
+
|
| 220 |
+
edited_image = pipeline(
|
| 221 |
+
prompt,
|
| 222 |
+
image=image,
|
| 223 |
+
num_inference_steps=num_inference_steps,
|
| 224 |
+
image_guidance_scale=image_guidance_scale,
|
| 225 |
+
guidance_scale=guidance_scale,
|
| 226 |
+
generator=generator,
|
| 227 |
+
).images[0]
|
| 228 |
+
edited_image.save("edited_image.png")
|
| 229 |
+
```
|
| 230 |
+
|
| 231 |
+
You should experiment with different `num_inference_steps`, `image_guidance_scale`, and `guidance_scale` values to see how they affect inference speed and quality. The guidance scale parameters are especially impactful because they control how much the original image and edit instructions affect the edited image.
|
| 232 |
+
|
| 233 |
+
## Stable Diffusion XL
|
| 234 |
+
|
| 235 |
+
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_instruct_pix2pix_sdxl.py`](https://github.com/huggingface/diffusers/blob/main/examples/instruct_pix2pix/train_instruct_pix2pix_sdxl.py) script to train a SDXL model to follow image editing instructions.
|
| 236 |
+
|
| 237 |
+
The SDXL training script is discussed in more detail in the [SDXL training](sdxl) guide.
|
| 238 |
+
|
| 239 |
+
## Next steps
|
| 240 |
+
|
| 241 |
+
Congratulations on training your own InstructPix2Pix model! 🥳 To learn more about the model, it may be helpful to:
|
| 242 |
+
|
| 243 |
+
- Read the [Instruction-tuning Stable Diffusion with InstructPix2Pix](https://huggingface.co/blog/instruction-tuning-sd) blog post to learn more about some experiments we've done with InstructPix2Pix, dataset preparation, and results for different instructions.
|
tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/training/kandinsky.md
ADDED
|
@@ -0,0 +1,312 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# Kandinsky 2.2
|
| 14 |
+
|
| 15 |
+
> [!WARNING]
|
| 16 |
+
> This script is experimental, and it's easy to overfit and run into issues like catastrophic forgetting. Try exploring different hyperparameters to get the best results on your dataset.
|
| 17 |
+
|
| 18 |
+
Kandinsky 2.2 is a multilingual text-to-image model capable of producing more photorealistic images. The model includes an image prior model for creating image embeddings from text prompts, and a decoder model that generates images based on the prior model's embeddings. That's why you'll find two separate scripts in Diffusers for Kandinsky 2.2, one for training the prior model and one for training the decoder model. You can train both models separately, but to get the best results, you should train both the prior and decoder models.
|
| 19 |
+
|
| 20 |
+
Depending on your GPU, you may need to enable `gradient_checkpointing` (⚠️ not supported for the prior model!), `mixed_precision`, and `gradient_accumulation_steps` to help fit the model into memory and to speedup training. You can reduce your memory-usage even more by enabling memory-efficient attention with [xFormers](../optimization/xformers) (version [v0.0.16](https://github.com/huggingface/diffusers/issues/2234#issuecomment-1416931212) fails for training on some GPUs so you may need to install a development version instead).
|
| 21 |
+
|
| 22 |
+
This guide explores the [train_text_to_image_prior.py](https://github.com/huggingface/diffusers/blob/main/examples/kandinsky2_2/text_to_image/train_text_to_image_prior.py) and the [train_text_to_image_decoder.py](https://github.com/huggingface/diffusers/blob/main/examples/kandinsky2_2/text_to_image/train_text_to_image_decoder.py) scripts to help you become more familiar with it, and how you can adapt it for your own use-case.
|
| 23 |
+
|
| 24 |
+
Before running the scripts, make sure you install the library from source:
|
| 25 |
+
|
| 26 |
+
```bash
|
| 27 |
+
git clone https://github.com/huggingface/diffusers
|
| 28 |
+
cd diffusers
|
| 29 |
+
pip install .
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
Then navigate to the example folder containing the training script and install the required dependencies for the script you're using:
|
| 33 |
+
|
| 34 |
+
```bash
|
| 35 |
+
cd examples/kandinsky2_2/text_to_image
|
| 36 |
+
pip install -r requirements.txt
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
> [!TIP]
|
| 40 |
+
> 🤗 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.
|
| 41 |
+
|
| 42 |
+
Initialize an 🤗 Accelerate environment:
|
| 43 |
+
|
| 44 |
+
```bash
|
| 45 |
+
accelerate config
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
To setup a default 🤗 Accelerate environment without choosing any configurations:
|
| 49 |
+
|
| 50 |
+
```bash
|
| 51 |
+
accelerate config default
|
| 52 |
+
```
|
| 53 |
+
|
| 54 |
+
Or if your environment doesn't support an interactive shell, like a notebook, you can use:
|
| 55 |
+
|
| 56 |
+
```py
|
| 57 |
+
from accelerate.utils import write_basic_config
|
| 58 |
+
|
| 59 |
+
write_basic_config()
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
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.
|
| 63 |
+
|
| 64 |
+
> [!TIP]
|
| 65 |
+
> The following sections highlight parts of the training scripts that are important for understanding how to modify it, but it doesn't cover every aspect of the scripts in detail. If you're interested in learning more, feel free to read through the scripts and let us know if you have any questions or concerns.
|
| 66 |
+
|
| 67 |
+
## Script parameters
|
| 68 |
+
|
| 69 |
+
The training scripts 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/6e68c71503682c8693cb5b06a4da4911dfd655ee/examples/kandinsky2_2/text_to_image/train_text_to_image_prior.py#L190) function. The training scripts 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.
|
| 70 |
+
|
| 71 |
+
For example, to speedup training with mixed precision using the fp16 format, add the `--mixed_precision` parameter to the training command:
|
| 72 |
+
|
| 73 |
+
```bash
|
| 74 |
+
accelerate launch train_text_to_image_prior.py \
|
| 75 |
+
--mixed_precision="fp16"
|
| 76 |
+
```
|
| 77 |
+
|
| 78 |
+
Most of the parameters are identical to the parameters in the [Text-to-image](text2image#script-parameters) training guide, so let's get straight to a walkthrough of the Kandinsky training scripts!
|
| 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_text_to_image_prior.py \
|
| 88 |
+
--snr_gamma=5.0
|
| 89 |
+
```
|
| 90 |
+
|
| 91 |
+
## Training script
|
| 92 |
+
|
| 93 |
+
The training script is also similar to the [Text-to-image](text2image#training-script) training guide, but it's been modified to support training the prior and decoder models. This guide focuses on the code that is unique to the Kandinsky 2.2 training scripts.
|
| 94 |
+
|
| 95 |
+
<hfoptions id="script">
|
| 96 |
+
<hfoption id="prior model">
|
| 97 |
+
|
| 98 |
+
The [`main()`](https://github.com/huggingface/diffusers/blob/6e68c71503682c8693cb5b06a4da4911dfd655ee/examples/kandinsky2_2/text_to_image/train_text_to_image_prior.py#L441) function contains the code for preparing the dataset and training the model.
|
| 99 |
+
|
| 100 |
+
One of the main differences you'll notice right away is that the training script also loads a [`~transformers.CLIPImageProcessor`] - in addition to a scheduler and tokenizer - for preprocessing images and a [`~transformers.CLIPVisionModelWithProjection`] model for encoding the images:
|
| 101 |
+
|
| 102 |
+
```py
|
| 103 |
+
noise_scheduler = DDPMScheduler(beta_schedule="squaredcos_cap_v2", prediction_type="sample")
|
| 104 |
+
image_processor = CLIPImageProcessor.from_pretrained(
|
| 105 |
+
args.pretrained_prior_model_name_or_path, subfolder="image_processor"
|
| 106 |
+
)
|
| 107 |
+
tokenizer = CLIPTokenizer.from_pretrained(args.pretrained_prior_model_name_or_path, subfolder="tokenizer")
|
| 108 |
+
|
| 109 |
+
with ContextManagers(deepspeed_zero_init_disabled_context_manager()):
|
| 110 |
+
image_encoder = CLIPVisionModelWithProjection.from_pretrained(
|
| 111 |
+
args.pretrained_prior_model_name_or_path, subfolder="image_encoder", torch_dtype=weight_dtype
|
| 112 |
+
).eval()
|
| 113 |
+
text_encoder = CLIPTextModelWithProjection.from_pretrained(
|
| 114 |
+
args.pretrained_prior_model_name_or_path, subfolder="text_encoder", torch_dtype=weight_dtype
|
| 115 |
+
).eval()
|
| 116 |
+
```
|
| 117 |
+
|
| 118 |
+
Kandinsky uses a [`PriorTransformer`] to generate the image embeddings, so you'll want to setup the optimizer to learn the prior mode's parameters.
|
| 119 |
+
|
| 120 |
+
```py
|
| 121 |
+
prior = PriorTransformer.from_pretrained(args.pretrained_prior_model_name_or_path, subfolder="prior")
|
| 122 |
+
prior.train()
|
| 123 |
+
optimizer = optimizer_cls(
|
| 124 |
+
prior.parameters(),
|
| 125 |
+
lr=args.learning_rate,
|
| 126 |
+
betas=(args.adam_beta1, args.adam_beta2),
|
| 127 |
+
weight_decay=args.adam_weight_decay,
|
| 128 |
+
eps=args.adam_epsilon,
|
| 129 |
+
)
|
| 130 |
+
```
|
| 131 |
+
|
| 132 |
+
Next, the input captions are tokenized, and images are [preprocessed](https://github.com/huggingface/diffusers/blob/6e68c71503682c8693cb5b06a4da4911dfd655ee/examples/kandinsky2_2/text_to_image/train_text_to_image_prior.py#L632) by the [`~transformers.CLIPImageProcessor`]:
|
| 133 |
+
|
| 134 |
+
```py
|
| 135 |
+
def preprocess_train(examples):
|
| 136 |
+
images = [image.convert("RGB") for image in examples[image_column]]
|
| 137 |
+
examples["clip_pixel_values"] = image_processor(images, return_tensors="pt").pixel_values
|
| 138 |
+
examples["text_input_ids"], examples["text_mask"] = tokenize_captions(examples)
|
| 139 |
+
return examples
|
| 140 |
+
```
|
| 141 |
+
|
| 142 |
+
Finally, the [training loop](https://github.com/huggingface/diffusers/blob/6e68c71503682c8693cb5b06a4da4911dfd655ee/examples/kandinsky2_2/text_to_image/train_text_to_image_prior.py#L718) converts the input images into latents, adds noise to the image embeddings, and makes a prediction:
|
| 143 |
+
|
| 144 |
+
```py
|
| 145 |
+
model_pred = prior(
|
| 146 |
+
noisy_latents,
|
| 147 |
+
timestep=timesteps,
|
| 148 |
+
proj_embedding=prompt_embeds,
|
| 149 |
+
encoder_hidden_states=text_encoder_hidden_states,
|
| 150 |
+
attention_mask=text_mask,
|
| 151 |
+
).predicted_image_embedding
|
| 152 |
+
```
|
| 153 |
+
|
| 154 |
+
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.
|
| 155 |
+
|
| 156 |
+
</hfoption>
|
| 157 |
+
<hfoption id="decoder model">
|
| 158 |
+
|
| 159 |
+
The [`main()`](https://github.com/huggingface/diffusers/blob/6e68c71503682c8693cb5b06a4da4911dfd655ee/examples/kandinsky2_2/text_to_image/train_text_to_image_decoder.py#L440) function contains the code for preparing the dataset and training the model.
|
| 160 |
+
|
| 161 |
+
Unlike the prior model, the decoder initializes a [`VQModel`] to decode the latents into images and it uses a [`UNet2DConditionModel`]:
|
| 162 |
+
|
| 163 |
+
```py
|
| 164 |
+
with ContextManagers(deepspeed_zero_init_disabled_context_manager()):
|
| 165 |
+
vae = VQModel.from_pretrained(
|
| 166 |
+
args.pretrained_decoder_model_name_or_path, subfolder="movq", torch_dtype=weight_dtype
|
| 167 |
+
).eval()
|
| 168 |
+
image_encoder = CLIPVisionModelWithProjection.from_pretrained(
|
| 169 |
+
args.pretrained_prior_model_name_or_path, subfolder="image_encoder", torch_dtype=weight_dtype
|
| 170 |
+
).eval()
|
| 171 |
+
unet = UNet2DConditionModel.from_pretrained(args.pretrained_decoder_model_name_or_path, subfolder="unet")
|
| 172 |
+
```
|
| 173 |
+
|
| 174 |
+
Next, the script includes several image transforms and a [preprocessing](https://github.com/huggingface/diffusers/blob/6e68c71503682c8693cb5b06a4da4911dfd655ee/examples/kandinsky2_2/text_to_image/train_text_to_image_decoder.py#L622) function for applying the transforms to the images and returning the pixel values:
|
| 175 |
+
|
| 176 |
+
```py
|
| 177 |
+
def preprocess_train(examples):
|
| 178 |
+
images = [image.convert("RGB") for image in examples[image_column]]
|
| 179 |
+
examples["pixel_values"] = [train_transforms(image) for image in images]
|
| 180 |
+
examples["clip_pixel_values"] = image_processor(images, return_tensors="pt").pixel_values
|
| 181 |
+
return examples
|
| 182 |
+
```
|
| 183 |
+
|
| 184 |
+
Lastly, the [training loop](https://github.com/huggingface/diffusers/blob/6e68c71503682c8693cb5b06a4da4911dfd655ee/examples/kandinsky2_2/text_to_image/train_text_to_image_decoder.py#L706) handles converting the images to latents, adding noise, and predicting the noise residual.
|
| 185 |
+
|
| 186 |
+
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.
|
| 187 |
+
|
| 188 |
+
```py
|
| 189 |
+
model_pred = unet(noisy_latents, timesteps, None, added_cond_kwargs=added_cond_kwargs).sample[:, :4]
|
| 190 |
+
```
|
| 191 |
+
|
| 192 |
+
</hfoption>
|
| 193 |
+
</hfoptions>
|
| 194 |
+
|
| 195 |
+
## Launch the script
|
| 196 |
+
|
| 197 |
+
Once you’ve made all your changes or you’re okay with the default configuration, you’re ready to launch the training script! 🚀
|
| 198 |
+
|
| 199 |
+
You'll train on the [Naruto BLIP captions](https://huggingface.co/datasets/lambdalabs/naruto-blip-captions) dataset to generate your own Naruto characters, but you can also create and train on your own dataset by following the [Create a dataset for training](create_dataset) guide. Set the environment variable `DATASET_NAME` to the name of the dataset on the Hub or if you're training on your own files, set the environment variable `TRAIN_DIR` to a path to your dataset.
|
| 200 |
+
|
| 201 |
+
If you’re training on more than one GPU, add the `--multi_gpu` parameter to the `accelerate launch` command.
|
| 202 |
+
|
| 203 |
+
> [!TIP]
|
| 204 |
+
> To monitor training progress with Weights & Biases, add the `--report_to=wandb` parameter to the training command. You’ll also need to add the `--validation_prompt` to the training command to keep track of results. This can be really useful for debugging the model and viewing intermediate results.
|
| 205 |
+
|
| 206 |
+
<hfoptions id="training-inference">
|
| 207 |
+
<hfoption id="prior model">
|
| 208 |
+
|
| 209 |
+
```bash
|
| 210 |
+
export DATASET_NAME="lambdalabs/naruto-blip-captions"
|
| 211 |
+
|
| 212 |
+
accelerate launch --mixed_precision="fp16" train_text_to_image_prior.py \
|
| 213 |
+
--dataset_name=$DATASET_NAME \
|
| 214 |
+
--resolution=768 \
|
| 215 |
+
--train_batch_size=1 \
|
| 216 |
+
--gradient_accumulation_steps=4 \
|
| 217 |
+
--max_train_steps=15000 \
|
| 218 |
+
--learning_rate=1e-05 \
|
| 219 |
+
--max_grad_norm=1 \
|
| 220 |
+
--checkpoints_total_limit=3 \
|
| 221 |
+
--lr_scheduler="constant" \
|
| 222 |
+
--lr_warmup_steps=0 \
|
| 223 |
+
--validation_prompts="A robot naruto, 4k photo" \
|
| 224 |
+
--report_to="wandb" \
|
| 225 |
+
--push_to_hub \
|
| 226 |
+
--output_dir="kandi2-prior-naruto-model"
|
| 227 |
+
```
|
| 228 |
+
|
| 229 |
+
</hfoption>
|
| 230 |
+
<hfoption id="decoder model">
|
| 231 |
+
|
| 232 |
+
```bash
|
| 233 |
+
export DATASET_NAME="lambdalabs/naruto-blip-captions"
|
| 234 |
+
|
| 235 |
+
accelerate launch --mixed_precision="fp16" train_text_to_image_decoder.py \
|
| 236 |
+
--dataset_name=$DATASET_NAME \
|
| 237 |
+
--resolution=768 \
|
| 238 |
+
--train_batch_size=1 \
|
| 239 |
+
--gradient_accumulation_steps=4 \
|
| 240 |
+
--gradient_checkpointing \
|
| 241 |
+
--max_train_steps=15000 \
|
| 242 |
+
--learning_rate=1e-05 \
|
| 243 |
+
--max_grad_norm=1 \
|
| 244 |
+
--checkpoints_total_limit=3 \
|
| 245 |
+
--lr_scheduler="constant" \
|
| 246 |
+
--lr_warmup_steps=0 \
|
| 247 |
+
--validation_prompts="A robot naruto, 4k photo" \
|
| 248 |
+
--report_to="wandb" \
|
| 249 |
+
--push_to_hub \
|
| 250 |
+
--output_dir="kandi2-decoder-naruto-model"
|
| 251 |
+
```
|
| 252 |
+
|
| 253 |
+
</hfoption>
|
| 254 |
+
</hfoptions>
|
| 255 |
+
|
| 256 |
+
Once training is finished, you can use your newly trained model for inference!
|
| 257 |
+
|
| 258 |
+
<hfoptions id="training-inference">
|
| 259 |
+
<hfoption id="prior model">
|
| 260 |
+
|
| 261 |
+
```py
|
| 262 |
+
from diffusers import AutoPipelineForText2Image, DiffusionPipeline
|
| 263 |
+
import torch
|
| 264 |
+
|
| 265 |
+
prior_pipeline = DiffusionPipeline.from_pretrained(output_dir, torch_dtype=torch.float16)
|
| 266 |
+
prior_components = {"prior_" + k: v for k,v in prior_pipeline.components.items()}
|
| 267 |
+
pipeline = AutoPipelineForText2Image.from_pretrained("kandinsky-community/kandinsky-2-2-decoder", **prior_components, torch_dtype=torch.float16)
|
| 268 |
+
|
| 269 |
+
pipe.enable_model_cpu_offload()
|
| 270 |
+
prompt="A robot naruto, 4k photo"
|
| 271 |
+
image = pipeline(prompt=prompt, negative_prompt=negative_prompt).images[0]
|
| 272 |
+
```
|
| 273 |
+
|
| 274 |
+
> [!TIP]
|
| 275 |
+
> Feel free to replace `kandinsky-community/kandinsky-2-2-decoder` with your own trained decoder checkpoint!
|
| 276 |
+
|
| 277 |
+
</hfoption>
|
| 278 |
+
<hfoption id="decoder model">
|
| 279 |
+
|
| 280 |
+
```py
|
| 281 |
+
from diffusers import AutoPipelineForText2Image
|
| 282 |
+
import torch
|
| 283 |
+
|
| 284 |
+
pipeline = AutoPipelineForText2Image.from_pretrained("path/to/saved/model", torch_dtype=torch.float16)
|
| 285 |
+
pipeline.enable_model_cpu_offload()
|
| 286 |
+
|
| 287 |
+
prompt="A robot naruto, 4k photo"
|
| 288 |
+
image = pipeline(prompt=prompt).images[0]
|
| 289 |
+
```
|
| 290 |
+
|
| 291 |
+
For the decoder model, you can also perform inference from a saved checkpoint which can be useful for viewing intermediate results. In this case, load the checkpoint into the UNet:
|
| 292 |
+
|
| 293 |
+
```py
|
| 294 |
+
from diffusers import AutoPipelineForText2Image, UNet2DConditionModel
|
| 295 |
+
|
| 296 |
+
unet = UNet2DConditionModel.from_pretrained("path/to/saved/model" + "/checkpoint-<N>/unet")
|
| 297 |
+
|
| 298 |
+
pipeline = AutoPipelineForText2Image.from_pretrained("kandinsky-community/kandinsky-2-2-decoder", unet=unet, torch_dtype=torch.float16)
|
| 299 |
+
pipeline.enable_model_cpu_offload()
|
| 300 |
+
|
| 301 |
+
image = pipeline(prompt="A robot naruto, 4k photo").images[0]
|
| 302 |
+
```
|
| 303 |
+
|
| 304 |
+
</hfoption>
|
| 305 |
+
</hfoptions>
|
| 306 |
+
|
| 307 |
+
## Next steps
|
| 308 |
+
|
| 309 |
+
Congratulations on training a Kandinsky 2.2 model! To learn more about how to use your new model, the following guides may be helpful:
|
| 310 |
+
|
| 311 |
+
- Read the [Kandinsky](../using-diffusers/kandinsky) guide to learn how to use it for a variety of different tasks (text-to-image, image-to-image, inpainting, interpolation), and how it can be combined with a ControlNet.
|
| 312 |
+
- Check out the [DreamBooth](dreambooth) and [LoRA](lora) training guides to learn how to train a personalized Kandinsky model with just a few example images. These two training techniques can even be combined!
|
tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/training/lcm_distill.md
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# Latent Consistency Distillation
|
| 14 |
+
|
| 15 |
+
[Latent Consistency Models (LCMs)](https://hf.co/papers/2310.04378) are able to generate high-quality images in just a few steps, representing a big leap forward because many pipelines require at least 25+ steps. LCMs are produced by applying the latent consistency distillation method to any Stable Diffusion model. This method works by applying *one-stage guided distillation* to the latent space, and incorporating a *skipping-step* method to consistently skip timesteps to accelerate the distillation process (refer to section 4.1, 4.2, and 4.3 of the paper for more details).
|
| 16 |
+
|
| 17 |
+
If you're training on a GPU with limited vRAM, try enabling `gradient_checkpointing`, `gradient_accumulation_steps`, and `mixed_precision` to reduce memory-usage and speedup training. You can reduce your memory-usage even more by enabling memory-efficient attention with [xFormers](../optimization/xformers) and [bitsandbytes'](https://github.com/TimDettmers/bitsandbytes) 8-bit optimizer.
|
| 18 |
+
|
| 19 |
+
This guide will explore the [train_lcm_distill_sd_wds.py](https://github.com/huggingface/diffusers/blob/main/examples/consistency_distillation/train_lcm_distill_sd_wds.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 |
+
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/consistency_distillation
|
| 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 (try enabling `torch.compile` to significantly speedup training):
|
| 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 |
+
## Script parameters
|
| 62 |
+
|
| 63 |
+
> [!TIP]
|
| 64 |
+
> 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/consistency_distillation/train_lcm_distill_sd_wds.py) and let us know if you have any questions or concerns.
|
| 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/3b37488fa3280aed6a95de044d7a42ffdcb565ef/examples/consistency_distillation/train_lcm_distill_sd_wds.py#L419) 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_lcm_distill_sd_wds.py \
|
| 72 |
+
--mixed_precision="fp16"
|
| 73 |
+
```
|
| 74 |
+
|
| 75 |
+
Most of the parameters are identical to the parameters in the [Text-to-image](text2image#script-parameters) training guide, so you'll focus on the parameters that are relevant to latent consistency distillation in this guide.
|
| 76 |
+
|
| 77 |
+
- `--pretrained_teacher_model`: the path to a pretrained latent diffusion model to use as the teacher model
|
| 78 |
+
- `--pretrained_vae_model_name_or_path`: path to a pretrained VAE; the SDXL VAE is known to suffer from numerical instability, so this parameter allows you to specify an alternative VAE (like this [VAE](https://huggingface.co/madebyollin/sdxl-vae-fp16-fix)) by madebyollin which works in fp16)
|
| 79 |
+
- `--w_min` and `--w_max`: the minimum and maximum guidance scale values for guidance scale sampling
|
| 80 |
+
- `--num_ddim_timesteps`: the number of timesteps for DDIM sampling
|
| 81 |
+
- `--loss_type`: the type of loss (L2 or Huber) to calculate for latent consistency distillation; Huber loss is generally preferred because it's more robust to outliers
|
| 82 |
+
- `--huber_c`: the Huber loss parameter
|
| 83 |
+
|
| 84 |
+
## Training script
|
| 85 |
+
|
| 86 |
+
The training script starts by creating a dataset class - [`Text2ImageDataset`](https://github.com/huggingface/diffusers/blob/3b37488fa3280aed6a95de044d7a42ffdcb565ef/examples/consistency_distillation/train_lcm_distill_sd_wds.py#L141) - for preprocessing the images and creating a training dataset.
|
| 87 |
+
|
| 88 |
+
```py
|
| 89 |
+
def transform(example):
|
| 90 |
+
image = example["image"]
|
| 91 |
+
image = TF.resize(image, resolution, interpolation=transforms.InterpolationMode.BILINEAR)
|
| 92 |
+
|
| 93 |
+
c_top, c_left, _, _ = transforms.RandomCrop.get_params(image, output_size=(resolution, resolution))
|
| 94 |
+
image = TF.crop(image, c_top, c_left, resolution, resolution)
|
| 95 |
+
image = TF.to_tensor(image)
|
| 96 |
+
image = TF.normalize(image, [0.5], [0.5])
|
| 97 |
+
|
| 98 |
+
example["image"] = image
|
| 99 |
+
return example
|
| 100 |
+
```
|
| 101 |
+
|
| 102 |
+
For improved performance on reading and writing large datasets stored in the cloud, this script uses the [WebDataset](https://github.com/webdataset/webdataset) format to create a preprocessing pipeline to apply transforms and create a dataset and dataloader for training. Images are processed and fed to the training loop without having to download the full dataset first.
|
| 103 |
+
|
| 104 |
+
```py
|
| 105 |
+
processing_pipeline = [
|
| 106 |
+
wds.decode("pil", handler=wds.ignore_and_continue),
|
| 107 |
+
wds.rename(image="jpg;png;jpeg;webp", text="text;txt;caption", handler=wds.warn_and_continue),
|
| 108 |
+
wds.map(filter_keys({"image", "text"})),
|
| 109 |
+
wds.map(transform),
|
| 110 |
+
wds.to_tuple("image", "text"),
|
| 111 |
+
]
|
| 112 |
+
```
|
| 113 |
+
|
| 114 |
+
In the [`main()`](https://github.com/huggingface/diffusers/blob/3b37488fa3280aed6a95de044d7a42ffdcb565ef/examples/consistency_distillation/train_lcm_distill_sd_wds.py#L768) function, all the necessary components like the noise scheduler, tokenizers, text encoders, and VAE are loaded. The teacher UNet is also loaded here and then you can create a student UNet from the teacher UNet. The student UNet is updated by the optimizer during training.
|
| 115 |
+
|
| 116 |
+
```py
|
| 117 |
+
teacher_unet = UNet2DConditionModel.from_pretrained(
|
| 118 |
+
args.pretrained_teacher_model, subfolder="unet", revision=args.teacher_revision
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
unet = UNet2DConditionModel(**teacher_unet.config)
|
| 122 |
+
unet.load_state_dict(teacher_unet.state_dict(), strict=False)
|
| 123 |
+
unet.train()
|
| 124 |
+
```
|
| 125 |
+
|
| 126 |
+
Now you can create the [optimizer](https://github.com/huggingface/diffusers/blob/3b37488fa3280aed6a95de044d7a42ffdcb565ef/examples/consistency_distillation/train_lcm_distill_sd_wds.py#L979) to update the UNet parameters:
|
| 127 |
+
|
| 128 |
+
```py
|
| 129 |
+
optimizer = optimizer_class(
|
| 130 |
+
unet.parameters(),
|
| 131 |
+
lr=args.learning_rate,
|
| 132 |
+
betas=(args.adam_beta1, args.adam_beta2),
|
| 133 |
+
weight_decay=args.adam_weight_decay,
|
| 134 |
+
eps=args.adam_epsilon,
|
| 135 |
+
)
|
| 136 |
+
```
|
| 137 |
+
|
| 138 |
+
Create the [dataset](https://github.com/huggingface/diffusers/blob/3b37488fa3280aed6a95de044d7a42ffdcb565ef/examples/consistency_distillation/train_lcm_distill_sd_wds.py#L994):
|
| 139 |
+
|
| 140 |
+
```py
|
| 141 |
+
dataset = Text2ImageDataset(
|
| 142 |
+
train_shards_path_or_url=args.train_shards_path_or_url,
|
| 143 |
+
num_train_examples=args.max_train_samples,
|
| 144 |
+
per_gpu_batch_size=args.train_batch_size,
|
| 145 |
+
global_batch_size=args.train_batch_size * accelerator.num_processes,
|
| 146 |
+
num_workers=args.dataloader_num_workers,
|
| 147 |
+
resolution=args.resolution,
|
| 148 |
+
shuffle_buffer_size=1000,
|
| 149 |
+
pin_memory=True,
|
| 150 |
+
persistent_workers=True,
|
| 151 |
+
)
|
| 152 |
+
train_dataloader = dataset.train_dataloader
|
| 153 |
+
```
|
| 154 |
+
|
| 155 |
+
Next, you're ready to setup the [training loop](https://github.com/huggingface/diffusers/blob/3b37488fa3280aed6a95de044d7a42ffdcb565ef/examples/consistency_distillation/train_lcm_distill_sd_wds.py#L1049) and implement the latent consistency distillation method (see Algorithm 1 in the paper for more details). This section of the script takes care of adding noise to the latents, sampling and creating a guidance scale embedding, and predicting the original image from the noise.
|
| 156 |
+
|
| 157 |
+
```py
|
| 158 |
+
pred_x_0 = predicted_origin(
|
| 159 |
+
noise_pred,
|
| 160 |
+
start_timesteps,
|
| 161 |
+
noisy_model_input,
|
| 162 |
+
noise_scheduler.config.prediction_type,
|
| 163 |
+
alpha_schedule,
|
| 164 |
+
sigma_schedule,
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
model_pred = c_skip_start * noisy_model_input + c_out_start * pred_x_0
|
| 168 |
+
```
|
| 169 |
+
|
| 170 |
+
It gets the [teacher model predictions](https://github.com/huggingface/diffusers/blob/3b37488fa3280aed6a95de044d7a42ffdcb565ef/examples/consistency_distillation/train_lcm_distill_sd_wds.py#L1172) and the [LCM predictions](https://github.com/huggingface/diffusers/blob/3b37488fa3280aed6a95de044d7a42ffdcb565ef/examples/consistency_distillation/train_lcm_distill_sd_wds.py#L1209) next, calculates the loss, and then backpropagates it to the LCM.
|
| 171 |
+
|
| 172 |
+
```py
|
| 173 |
+
if args.loss_type == "l2":
|
| 174 |
+
loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
|
| 175 |
+
elif args.loss_type == "huber":
|
| 176 |
+
loss = torch.mean(
|
| 177 |
+
torch.sqrt((model_pred.float() - target.float()) ** 2 + args.huber_c**2) - args.huber_c
|
| 178 |
+
)
|
| 179 |
+
```
|
| 180 |
+
|
| 181 |
+
If you want to learn more about how the training loop works, check out the [Understanding pipelines, models and schedulers tutorial](../using-diffusers/write_own_pipeline) which breaks down the basic pattern of the denoising process.
|
| 182 |
+
|
| 183 |
+
## Launch the script
|
| 184 |
+
|
| 185 |
+
Now you're ready to launch the training script and start distilling!
|
| 186 |
+
|
| 187 |
+
For this guide, you'll use the `--train_shards_path_or_url` to specify the path to the [Conceptual Captions 12M](https://github.com/google-research-datasets/conceptual-12m) dataset stored on the Hub [here](https://huggingface.co/datasets/laion/conceptual-captions-12m-webdataset). Set the `MODEL_DIR` environment variable to the name of the teacher model and `OUTPUT_DIR` to where you want to save the model.
|
| 188 |
+
|
| 189 |
+
```bash
|
| 190 |
+
export MODEL_DIR="stable-diffusion-v1-5/stable-diffusion-v1-5"
|
| 191 |
+
export OUTPUT_DIR="path/to/saved/model"
|
| 192 |
+
|
| 193 |
+
accelerate launch train_lcm_distill_sd_wds.py \
|
| 194 |
+
--pretrained_teacher_model=$MODEL_DIR \
|
| 195 |
+
--output_dir=$OUTPUT_DIR \
|
| 196 |
+
--mixed_precision=fp16 \
|
| 197 |
+
--resolution=512 \
|
| 198 |
+
--learning_rate=1e-6 --loss_type="huber" --ema_decay=0.95 --adam_weight_decay=0.0 \
|
| 199 |
+
--max_train_steps=1000 \
|
| 200 |
+
--max_train_samples=4000000 \
|
| 201 |
+
--dataloader_num_workers=8 \
|
| 202 |
+
--train_shards_path_or_url="pipe:curl -L -s https://huggingface.co/datasets/laion/conceptual-captions-12m-webdataset/resolve/main/data/{00000..01099}.tar?download=true" \
|
| 203 |
+
--validation_steps=200 \
|
| 204 |
+
--checkpointing_steps=200 --checkpoints_total_limit=10 \
|
| 205 |
+
--train_batch_size=12 \
|
| 206 |
+
--gradient_checkpointing --enable_xformers_memory_efficient_attention \
|
| 207 |
+
--gradient_accumulation_steps=1 \
|
| 208 |
+
--use_8bit_adam \
|
| 209 |
+
--resume_from_checkpoint=latest \
|
| 210 |
+
--report_to=wandb \
|
| 211 |
+
--seed=453645634 \
|
| 212 |
+
--push_to_hub
|
| 213 |
+
```
|
| 214 |
+
|
| 215 |
+
Once training is complete, you can use your new LCM for inference.
|
| 216 |
+
|
| 217 |
+
```py
|
| 218 |
+
from diffusers import UNet2DConditionModel, DiffusionPipeline, LCMScheduler
|
| 219 |
+
import torch
|
| 220 |
+
|
| 221 |
+
unet = UNet2DConditionModel.from_pretrained("your-username/your-model", torch_dtype=torch.float16, variant="fp16")
|
| 222 |
+
pipeline = DiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", unet=unet, torch_dtype=torch.float16, variant="fp16")
|
| 223 |
+
|
| 224 |
+
pipeline.scheduler = LCMScheduler.from_config(pipe.scheduler.config)
|
| 225 |
+
pipeline.to("cuda")
|
| 226 |
+
|
| 227 |
+
prompt = "sushi rolls in the form of panda heads, sushi platter"
|
| 228 |
+
|
| 229 |
+
image = pipeline(prompt, num_inference_steps=4, guidance_scale=1.0).images[0]
|
| 230 |
+
```
|
| 231 |
+
|
| 232 |
+
## LoRA
|
| 233 |
+
|
| 234 |
+
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_lcm_distill_lora_sd_wds.py](https://github.com/huggingface/diffusers/blob/main/examples/consistency_distillation/train_lcm_distill_lora_sd_wds.py) or [train_lcm_distill_lora_sdxl.wds.py](https://github.com/huggingface/diffusers/blob/main/examples/consistency_distillation/train_lcm_distill_lora_sdxl_wds.py) script to train with LoRA.
|
| 235 |
+
|
| 236 |
+
The LoRA training script is discussed in more detail in the [LoRA training](lora) guide.
|
| 237 |
+
|
| 238 |
+
## Stable Diffusion XL
|
| 239 |
+
|
| 240 |
+
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_lcm_distill_sdxl_wds.py](https://github.com/huggingface/diffusers/blob/main/examples/consistency_distillation/train_lcm_distill_sdxl_wds.py) script to train a SDXL model with LoRA.
|
| 241 |
+
|
| 242 |
+
The SDXL training script is discussed in more detail in the [SDXL training](sdxl) guide.
|
| 243 |
+
|
| 244 |
+
## Next steps
|
| 245 |
+
|
| 246 |
+
Congratulations on distilling a LCM model! To learn more about LCM, the following may be helpful:
|
| 247 |
+
|
| 248 |
+
- Learn how to use [LCMs for inference](../using-diffusers/inference_with_lcm) for text-to-image, image-to-image, and with LoRA checkpoints.
|
| 249 |
+
- Read the [SDXL in 4 steps with Latent Consistency LoRAs](https://huggingface.co/blog/lcm_lora) blog post to learn more about SDXL LCM-LoRA's for super fast inference, quality comparisons, benchmarks, and more.
|
tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/training/lora.md
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# LoRA
|
| 14 |
+
|
| 15 |
+
> [!WARNING]
|
| 16 |
+
> This is experimental and the API may change in the future.
|
| 17 |
+
|
| 18 |
+
[LoRA (Low-Rank Adaptation of Large Language Models)](https://hf.co/papers/2106.09685) is a popular and lightweight training technique that significantly reduces the number of trainable parameters. It works by inserting a smaller number of new weights into the model and only these are trained. This makes training with LoRA much faster, memory-efficient, and produces smaller model weights (a few hundred MBs), which are easier to store and share. LoRA can also be combined with other training techniques like DreamBooth to speedup training.
|
| 19 |
+
|
| 20 |
+
> [!TIP]
|
| 21 |
+
> LoRA is very versatile and supported for [DreamBooth](https://github.com/huggingface/diffusers/blob/main/examples/dreambooth/train_dreambooth_lora.py), [Kandinsky 2.2](https://github.com/huggingface/diffusers/blob/main/examples/kandinsky2_2/text_to_image/train_text_to_image_lora_decoder.py), [Stable Diffusion XL](https://github.com/huggingface/diffusers/blob/main/examples/text_to_image/train_text_to_image_lora_sdxl.py), [text-to-image](https://github.com/huggingface/diffusers/blob/main/examples/text_to_image/train_text_to_image_lora.py), and [Wuerstchen](https://github.com/huggingface/diffusers/blob/main/examples/wuerstchen/text_to_image/train_text_to_image_lora_prior.py).
|
| 22 |
+
|
| 23 |
+
This guide will explore the [train_text_to_image_lora.py](https://github.com/huggingface/diffusers/blob/main/examples/text_to_image/train_text_to_image_lora.py) script to help you become more familiar with it, and how you can adapt it for your own use-case.
|
| 24 |
+
|
| 25 |
+
Before running the script, make sure you install the library from source:
|
| 26 |
+
|
| 27 |
+
```bash
|
| 28 |
+
git clone https://github.com/huggingface/diffusers
|
| 29 |
+
cd diffusers
|
| 30 |
+
pip install .
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
Navigate to the example folder with the training script and install the required dependencies for the script you're using:
|
| 34 |
+
|
| 35 |
+
```bash
|
| 36 |
+
cd examples/text_to_image
|
| 37 |
+
pip install -r requirements.txt
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
> [!TIP]
|
| 41 |
+
> 🤗 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.
|
| 42 |
+
|
| 43 |
+
Initialize an 🤗 Accelerate environment:
|
| 44 |
+
|
| 45 |
+
```bash
|
| 46 |
+
accelerate config
|
| 47 |
+
```
|
| 48 |
+
|
| 49 |
+
To setup a default 🤗 Accelerate environment without choosing any configurations:
|
| 50 |
+
|
| 51 |
+
```bash
|
| 52 |
+
accelerate config default
|
| 53 |
+
```
|
| 54 |
+
|
| 55 |
+
Or if your environment doesn't support an interactive shell, like a notebook, you can use:
|
| 56 |
+
|
| 57 |
+
```py
|
| 58 |
+
from accelerate.utils import write_basic_config
|
| 59 |
+
|
| 60 |
+
write_basic_config()
|
| 61 |
+
```
|
| 62 |
+
|
| 63 |
+
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.
|
| 64 |
+
|
| 65 |
+
> [!TIP]
|
| 66 |
+
> 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/text_to_image/train_text_to_image_lora.py) and let us know if you have any questions or concerns.
|
| 67 |
+
|
| 68 |
+
## Script parameters
|
| 69 |
+
|
| 70 |
+
The training script has 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/dd9a5caf61f04d11c0fa9f3947b69ab0010c9a0f/examples/text_to_image/train_text_to_image_lora.py#L85) function. Default values are provided for most parameters that work pretty well, but you can also set your own values in the training command if you'd like.
|
| 71 |
+
|
| 72 |
+
For example, to increase the number of epochs to train:
|
| 73 |
+
|
| 74 |
+
```bash
|
| 75 |
+
accelerate launch train_text_to_image_lora.py \
|
| 76 |
+
--num_train_epochs=150 \
|
| 77 |
+
```
|
| 78 |
+
|
| 79 |
+
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 LoRA relevant parameters:
|
| 80 |
+
|
| 81 |
+
- `--rank`: the inner dimension of the low-rank matrices to train; a higher rank means more trainable parameters
|
| 82 |
+
- `--learning_rate`: the default learning rate is 1e-4, but with LoRA, you can use a higher learning rate
|
| 83 |
+
|
| 84 |
+
## Training script
|
| 85 |
+
|
| 86 |
+
The dataset preprocessing code and training loop are found in the [`main()`](https://github.com/huggingface/diffusers/blob/dd9a5caf61f04d11c0fa9f3947b69ab0010c9a0f/examples/text_to_image/train_text_to_image_lora.py#L371) function, and if you need to adapt the training script, this is where you'll make your changes.
|
| 87 |
+
|
| 88 |
+
As with the script parameters, a 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 LoRA relevant parts of the script.
|
| 89 |
+
|
| 90 |
+
<hfoptions id="lora">
|
| 91 |
+
<hfoption id="UNet">
|
| 92 |
+
|
| 93 |
+
Diffusers uses [`~peft.LoraConfig`] from the [PEFT](https://hf.co/docs/peft) library to set up the parameters of the LoRA adapter such as the rank, alpha, and which modules to insert the LoRA weights into. The adapter is added to the UNet, and only the LoRA layers are filtered for optimization in `lora_layers`.
|
| 94 |
+
|
| 95 |
+
```py
|
| 96 |
+
unet_lora_config = LoraConfig(
|
| 97 |
+
r=args.rank,
|
| 98 |
+
lora_alpha=args.rank,
|
| 99 |
+
init_lora_weights="gaussian",
|
| 100 |
+
target_modules=["to_k", "to_q", "to_v", "to_out.0"],
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
unet.add_adapter(unet_lora_config)
|
| 104 |
+
lora_layers = filter(lambda p: p.requires_grad, unet.parameters())
|
| 105 |
+
```
|
| 106 |
+
|
| 107 |
+
</hfoption>
|
| 108 |
+
<hfoption id="text encoder">
|
| 109 |
+
|
| 110 |
+
Diffusers also supports finetuning the text encoder with LoRA from the [PEFT](https://hf.co/docs/peft) library when necessary such as finetuning Stable Diffusion XL (SDXL). The [`~peft.LoraConfig`] is used to configure the parameters of the LoRA adapter which are then added to the text encoder, and only the LoRA layers are filtered for training.
|
| 111 |
+
|
| 112 |
+
```py
|
| 113 |
+
text_lora_config = LoraConfig(
|
| 114 |
+
r=args.rank,
|
| 115 |
+
lora_alpha=args.rank,
|
| 116 |
+
init_lora_weights="gaussian",
|
| 117 |
+
target_modules=["q_proj", "k_proj", "v_proj", "out_proj"],
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
text_encoder_one.add_adapter(text_lora_config)
|
| 121 |
+
text_encoder_two.add_adapter(text_lora_config)
|
| 122 |
+
text_lora_parameters_one = list(filter(lambda p: p.requires_grad, text_encoder_one.parameters()))
|
| 123 |
+
text_lora_parameters_two = list(filter(lambda p: p.requires_grad, text_encoder_two.parameters()))
|
| 124 |
+
```
|
| 125 |
+
|
| 126 |
+
</hfoption>
|
| 127 |
+
</hfoptions>
|
| 128 |
+
|
| 129 |
+
The [optimizer](https://github.com/huggingface/diffusers/blob/e4b8f173b97731686e290b2eb98e7f5df2b1b322/examples/text_to_image/train_text_to_image_lora.py#L529) is initialized with the `lora_layers` because these are the only weights that'll be optimized:
|
| 130 |
+
|
| 131 |
+
```py
|
| 132 |
+
optimizer = optimizer_cls(
|
| 133 |
+
lora_layers,
|
| 134 |
+
lr=args.learning_rate,
|
| 135 |
+
betas=(args.adam_beta1, args.adam_beta2),
|
| 136 |
+
weight_decay=args.adam_weight_decay,
|
| 137 |
+
eps=args.adam_epsilon,
|
| 138 |
+
)
|
| 139 |
+
```
|
| 140 |
+
|
| 141 |
+
Aside from setting up the LoRA layers, the training script is more or less the same as train_text_to_image.py!
|
| 142 |
+
|
| 143 |
+
## Launch the script
|
| 144 |
+
|
| 145 |
+
Once you've made all your changes or you're okay with the default configuration, you're ready to launch the training script! 🚀
|
| 146 |
+
|
| 147 |
+
Let's train on the [Naruto BLIP captions](https://huggingface.co/datasets/lambdalabs/naruto-blip-captions) dataset to generate your own Naruto characters. Set the environment variables `MODEL_NAME` and `DATASET_NAME` to the model and dataset respectively. You should also specify where to save the model in `OUTPUT_DIR`, and the name of the model to save to on the Hub with `HUB_MODEL_ID`. The script creates and saves the following files to your repository:
|
| 148 |
+
|
| 149 |
+
- saved model checkpoints
|
| 150 |
+
- `pytorch_lora_weights.safetensors` (the trained LoRA weights)
|
| 151 |
+
|
| 152 |
+
If you're training on more than one GPU, add the `--multi_gpu` parameter to the `accelerate launch` command.
|
| 153 |
+
|
| 154 |
+
> [!WARNING]
|
| 155 |
+
> A full training run takes ~5 hours on a 2080 Ti GPU with 11GB of VRAM.
|
| 156 |
+
|
| 157 |
+
```bash
|
| 158 |
+
export MODEL_NAME="stable-diffusion-v1-5/stable-diffusion-v1-5"
|
| 159 |
+
export OUTPUT_DIR="/sddata/finetune/lora/naruto"
|
| 160 |
+
export HUB_MODEL_ID="naruto-lora"
|
| 161 |
+
export DATASET_NAME="lambdalabs/naruto-blip-captions"
|
| 162 |
+
|
| 163 |
+
accelerate launch --mixed_precision="fp16" train_text_to_image_lora.py \
|
| 164 |
+
--pretrained_model_name_or_path=$MODEL_NAME \
|
| 165 |
+
--dataset_name=$DATASET_NAME \
|
| 166 |
+
--dataloader_num_workers=8 \
|
| 167 |
+
--resolution=512 \
|
| 168 |
+
--center_crop \
|
| 169 |
+
--random_flip \
|
| 170 |
+
--train_batch_size=1 \
|
| 171 |
+
--gradient_accumulation_steps=4 \
|
| 172 |
+
--max_train_steps=15000 \
|
| 173 |
+
--learning_rate=1e-04 \
|
| 174 |
+
--max_grad_norm=1 \
|
| 175 |
+
--lr_scheduler="cosine" \
|
| 176 |
+
--lr_warmup_steps=0 \
|
| 177 |
+
--output_dir=${OUTPUT_DIR} \
|
| 178 |
+
--push_to_hub \
|
| 179 |
+
--hub_model_id=${HUB_MODEL_ID} \
|
| 180 |
+
--report_to=wandb \
|
| 181 |
+
--checkpointing_steps=500 \
|
| 182 |
+
--validation_prompt="A naruto with blue eyes." \
|
| 183 |
+
--seed=1337
|
| 184 |
+
```
|
| 185 |
+
|
| 186 |
+
Once training has been completed, you can use your model for inference:
|
| 187 |
+
|
| 188 |
+
```py
|
| 189 |
+
from diffusers import AutoPipelineForText2Image
|
| 190 |
+
import torch
|
| 191 |
+
|
| 192 |
+
pipeline = AutoPipelineForText2Image.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16).to("cuda")
|
| 193 |
+
pipeline.load_lora_weights("path/to/lora/model", weight_name="pytorch_lora_weights.safetensors")
|
| 194 |
+
image = pipeline("A naruto with blue eyes").images[0]
|
| 195 |
+
```
|
| 196 |
+
|
| 197 |
+
## Next steps
|
| 198 |
+
|
| 199 |
+
Congratulations on training a new model with LoRA! To learn more about how to use your new model, the following guides may be helpful:
|
| 200 |
+
|
| 201 |
+
- Learn how to [load different LoRA formats](../tutorials/using_peft_for_inference) trained using community trainers like Kohya and TheLastBen.
|
| 202 |
+
- Learn how to use and [combine multiple LoRA's](../tutorials/using_peft_for_inference) with PEFT for inference.
|
tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/training/overview.md
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
🤗 Diffusers provides a collection of training scripts for you to train your own diffusion models. You can find all of our training scripts in [diffusers/examples](https://github.com/huggingface/diffusers/tree/main/examples).
|
| 16 |
+
|
| 17 |
+
Each training script is:
|
| 18 |
+
|
| 19 |
+
- **Self-contained**: the training script does not depend on any local files, and all packages required to run the script are installed from the `requirements.txt` file.
|
| 20 |
+
- **Easy-to-tweak**: the training scripts are an example of how to train a diffusion model for a specific task and won't work out-of-the-box for every training scenario. You'll likely need to adapt the training script for your specific use-case. To help you with that, we've fully exposed the data preprocessing code and the training loop so you can modify it for your own use.
|
| 21 |
+
- **Beginner-friendly**: the training scripts are designed to be beginner-friendly and easy to understand, rather than including the latest state-of-the-art methods to get the best and most competitive results. Any training methods we consider too complex are purposefully left out.
|
| 22 |
+
- **Single-purpose**: each training script is expressly designed for only one task to keep it readable and understandable.
|
| 23 |
+
|
| 24 |
+
Our current collection of training scripts include:
|
| 25 |
+
|
| 26 |
+
| Training | SDXL-support | LoRA-support |
|
| 27 |
+
|---|---|---|
|
| 28 |
+
| [unconditional image generation](https://github.com/huggingface/diffusers/tree/main/examples/unconditional_image_generation) [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/training_example.ipynb) | | |
|
| 29 |
+
| [text-to-image](https://github.com/huggingface/diffusers/tree/main/examples/text_to_image) | 👍 | 👍 |
|
| 30 |
+
| [textual inversion](https://github.com/huggingface/diffusers/tree/main/examples/textual_inversion) [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/sd_textual_inversion_training.ipynb) | | |
|
| 31 |
+
| [DreamBooth](https://github.com/huggingface/diffusers/tree/main/examples/dreambooth) [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/sd_dreambooth_training.ipynb) | 👍 | 👍 |
|
| 32 |
+
| [ControlNet](https://github.com/huggingface/diffusers/tree/main/examples/controlnet) | 👍 | |
|
| 33 |
+
| [InstructPix2Pix](https://github.com/huggingface/diffusers/tree/main/examples/instruct_pix2pix) | 👍 | |
|
| 34 |
+
| [Custom Diffusion](https://github.com/huggingface/diffusers/tree/main/examples/custom_diffusion) | | |
|
| 35 |
+
| [T2I-Adapters](https://github.com/huggingface/diffusers/tree/main/examples/t2i_adapter) | 👍 | |
|
| 36 |
+
| [Kandinsky 2.2](https://github.com/huggingface/diffusers/tree/main/examples/kandinsky2_2/text_to_image) | | 👍 |
|
| 37 |
+
| [Wuerstchen](https://github.com/huggingface/diffusers/tree/main/examples/wuerstchen/text_to_image) | | 👍 |
|
| 38 |
+
|
| 39 |
+
These examples are **actively** maintained, so please feel free to open an issue if they aren't working as expected. If you feel like another training example should be included, you're more than welcome to start a [Feature Request](https://github.com/huggingface/diffusers/issues/new?assignees=&labels=&template=feature_request.md&title=) to discuss your feature idea with us and whether it meets our criteria of being self-contained, easy-to-tweak, beginner-friendly, and single-purpose.
|
| 40 |
+
|
| 41 |
+
## Install
|
| 42 |
+
|
| 43 |
+
Make sure you can successfully run the latest versions of the example scripts by installing the library from source in a new virtual environment:
|
| 44 |
+
|
| 45 |
+
```bash
|
| 46 |
+
git clone https://github.com/huggingface/diffusers
|
| 47 |
+
cd diffusers
|
| 48 |
+
pip install .
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
Then navigate to the folder of the training script (for example, [DreamBooth](https://github.com/huggingface/diffusers/tree/main/examples/dreambooth)) and install the `requirements.txt` file. Some training scripts have a specific requirement file for SDXL or LoRA. If you're using one of these scripts, make sure you install its corresponding requirements file.
|
| 52 |
+
|
| 53 |
+
```bash
|
| 54 |
+
cd examples/dreambooth
|
| 55 |
+
pip install -r requirements.txt
|
| 56 |
+
# to train SDXL with DreamBooth
|
| 57 |
+
pip install -r requirements_sdxl.txt
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
To speedup training and reduce memory-usage, we recommend:
|
| 61 |
+
|
| 62 |
+
- using PyTorch 2.0 or higher to automatically use [scaled dot product attention](../optimization/fp16#scaled-dot-product-attention) during training (you don't need to make any changes to the training code)
|
| 63 |
+
- installing [xFormers](../optimization/xformers) to enable memory-efficient attention
|
tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/training/sdxl.md
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# Stable Diffusion XL
|
| 14 |
+
|
| 15 |
+
> [!WARNING]
|
| 16 |
+
> This script is experimental, and it's easy to overfit and run into issues like catastrophic forgetting. Try exploring different hyperparameters to get the best results on your dataset.
|
| 17 |
+
|
| 18 |
+
[Stable Diffusion XL (SDXL)](https://hf.co/papers/2307.01952) is a larger and more powerful iteration of the Stable Diffusion model, capable of producing higher resolution images.
|
| 19 |
+
|
| 20 |
+
SDXL's UNet is 3x larger and the model adds a second text encoder to the architecture. Depending on the hardware available to you, this can be very computationally intensive and it may not run on a consumer GPU like a Tesla T4. To help fit this larger model into memory and to speedup training, try enabling `gradient_checkpointing`, `mixed_precision`, and `gradient_accumulation_steps`. You can reduce your memory-usage even more by enabling memory-efficient attention with [xFormers](../optimization/xformers) and using [bitsandbytes'](https://github.com/TimDettmers/bitsandbytes) 8-bit optimizer.
|
| 21 |
+
|
| 22 |
+
This guide will explore the [train_text_to_image_sdxl.py](https://github.com/huggingface/diffusers/blob/main/examples/text_to_image/train_text_to_image_sdxl.py) training script to help you become more familiar with it, and how you can adapt it for your own use-case.
|
| 23 |
+
|
| 24 |
+
Before running the script, make sure you install the library from source:
|
| 25 |
+
|
| 26 |
+
```bash
|
| 27 |
+
git clone https://github.com/huggingface/diffusers
|
| 28 |
+
cd diffusers
|
| 29 |
+
pip install .
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
Then navigate to the example folder containing the training script and install the required dependencies for the script you're using:
|
| 33 |
+
|
| 34 |
+
```bash
|
| 35 |
+
cd examples/text_to_image
|
| 36 |
+
pip install -r requirements_sdxl.txt
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
> [!TIP]
|
| 40 |
+
> 🤗 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.
|
| 41 |
+
|
| 42 |
+
Initialize an 🤗 Accelerate environment:
|
| 43 |
+
|
| 44 |
+
```bash
|
| 45 |
+
accelerate config
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
To setup a default 🤗 Accelerate environment without choosing any configurations:
|
| 49 |
+
|
| 50 |
+
```bash
|
| 51 |
+
accelerate config default
|
| 52 |
+
```
|
| 53 |
+
|
| 54 |
+
Or if your environment doesn't support an interactive shell, like a notebook, you can use:
|
| 55 |
+
|
| 56 |
+
```py
|
| 57 |
+
from accelerate.utils import write_basic_config
|
| 58 |
+
|
| 59 |
+
write_basic_config()
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
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.
|
| 63 |
+
|
| 64 |
+
## Script parameters
|
| 65 |
+
|
| 66 |
+
> [!TIP]
|
| 67 |
+
> 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/text_to_image/train_text_to_image_sdxl.py) and let us know if you have any questions or concerns.
|
| 68 |
+
|
| 69 |
+
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/aab6de22c33cc01fb7bc81c0807d6109e2c998c9/examples/text_to_image/train_text_to_image_sdxl.py#L129) 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.
|
| 70 |
+
|
| 71 |
+
For example, to speedup training with mixed precision using the bf16 format, add the `--mixed_precision` parameter to the training command:
|
| 72 |
+
|
| 73 |
+
```bash
|
| 74 |
+
accelerate launch train_text_to_image_sdxl.py \
|
| 75 |
+
--mixed_precision="bf16"
|
| 76 |
+
```
|
| 77 |
+
|
| 78 |
+
Most of the parameters are identical to the parameters in the [Text-to-image](text2image#script-parameters) training guide, so you'll focus on the parameters that are relevant to training SDXL in this guide.
|
| 79 |
+
|
| 80 |
+
- `--pretrained_vae_model_name_or_path`: path to a pretrained VAE; the SDXL VAE is known to suffer from numerical instability, so this parameter allows you to specify a better [VAE](https://huggingface.co/madebyollin/sdxl-vae-fp16-fix)
|
| 81 |
+
- `--proportion_empty_prompts`: the proportion of image prompts to replace with empty strings
|
| 82 |
+
- `--timestep_bias_strategy`: where (earlier vs. later) in the timestep to apply a bias, which can encourage the model to either learn low or high frequency details
|
| 83 |
+
- `--timestep_bias_multiplier`: the weight of the bias to apply to the timestep
|
| 84 |
+
- `--timestep_bias_begin`: the timestep to begin applying the bias
|
| 85 |
+
- `--timestep_bias_end`: the timestep to end applying the bias
|
| 86 |
+
- `--timestep_bias_portion`: the proportion of timesteps to apply the bias to
|
| 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 either `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_text_to_image_sdxl.py \
|
| 96 |
+
--snr_gamma=5.0
|
| 97 |
+
```
|
| 98 |
+
|
| 99 |
+
## Training script
|
| 100 |
+
|
| 101 |
+
The training script is also similar to the [Text-to-image](text2image#training-script) training guide, but it's been modified to support SDXL training. This guide will focus on the code that is unique to the SDXL training script.
|
| 102 |
+
|
| 103 |
+
It starts by creating functions to [tokenize the prompts](https://github.com/huggingface/diffusers/blob/aab6de22c33cc01fb7bc81c0807d6109e2c998c9/examples/text_to_image/train_text_to_image_sdxl.py#L478) to calculate the prompt embeddings, and to compute the image embeddings with the [VAE](https://github.com/huggingface/diffusers/blob/aab6de22c33cc01fb7bc81c0807d6109e2c998c9/examples/text_to_image/train_text_to_image_sdxl.py#L519). Next, you'll a function to [generate the timesteps weights](https://github.com/huggingface/diffusers/blob/aab6de22c33cc01fb7bc81c0807d6109e2c998c9/examples/text_to_image/train_text_to_image_sdxl.py#L531) depending on the number of timesteps and the timestep bias strategy to apply.
|
| 104 |
+
|
| 105 |
+
Within the [`main()`](https://github.com/huggingface/diffusers/blob/aab6de22c33cc01fb7bc81c0807d6109e2c998c9/examples/text_to_image/train_text_to_image_sdxl.py#L572) function, in addition to loading a tokenizer, the script loads a second tokenizer and text encoder because the SDXL architecture uses two of each:
|
| 106 |
+
|
| 107 |
+
```py
|
| 108 |
+
tokenizer_one = AutoTokenizer.from_pretrained(
|
| 109 |
+
args.pretrained_model_name_or_path, subfolder="tokenizer", revision=args.revision, use_fast=False
|
| 110 |
+
)
|
| 111 |
+
tokenizer_two = AutoTokenizer.from_pretrained(
|
| 112 |
+
args.pretrained_model_name_or_path, subfolder="tokenizer_2", revision=args.revision, use_fast=False
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
text_encoder_cls_one = import_model_class_from_model_name_or_path(
|
| 116 |
+
args.pretrained_model_name_or_path, args.revision
|
| 117 |
+
)
|
| 118 |
+
text_encoder_cls_two = import_model_class_from_model_name_or_path(
|
| 119 |
+
args.pretrained_model_name_or_path, args.revision, subfolder="text_encoder_2"
|
| 120 |
+
)
|
| 121 |
+
```
|
| 122 |
+
|
| 123 |
+
The [prompt and image embeddings](https://github.com/huggingface/diffusers/blob/aab6de22c33cc01fb7bc81c0807d6109e2c998c9/examples/text_to_image/train_text_to_image_sdxl.py#L857) are computed first and kept in memory, which isn't typically an issue for a smaller dataset, but for larger datasets it can lead to memory problems. If this is the case, you should save the pre-computed embeddings to disk separately and load them into memory during the training process (see this [PR](https://github.com/huggingface/diffusers/pull/4505) for more discussion about this topic).
|
| 124 |
+
|
| 125 |
+
```py
|
| 126 |
+
text_encoders = [text_encoder_one, text_encoder_two]
|
| 127 |
+
tokenizers = [tokenizer_one, tokenizer_two]
|
| 128 |
+
compute_embeddings_fn = functools.partial(
|
| 129 |
+
encode_prompt,
|
| 130 |
+
text_encoders=text_encoders,
|
| 131 |
+
tokenizers=tokenizers,
|
| 132 |
+
proportion_empty_prompts=args.proportion_empty_prompts,
|
| 133 |
+
caption_column=args.caption_column,
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
train_dataset = train_dataset.map(compute_embeddings_fn, batched=True, new_fingerprint=new_fingerprint)
|
| 137 |
+
train_dataset = train_dataset.map(
|
| 138 |
+
compute_vae_encodings_fn,
|
| 139 |
+
batched=True,
|
| 140 |
+
batch_size=args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps,
|
| 141 |
+
new_fingerprint=new_fingerprint_for_vae,
|
| 142 |
+
)
|
| 143 |
+
```
|
| 144 |
+
|
| 145 |
+
After calculating the embeddings, the text encoder, VAE, and tokenizer are deleted to free up some memory:
|
| 146 |
+
|
| 147 |
+
```py
|
| 148 |
+
del text_encoders, tokenizers, vae
|
| 149 |
+
gc.collect()
|
| 150 |
+
torch.cuda.empty_cache()
|
| 151 |
+
```
|
| 152 |
+
|
| 153 |
+
Finally, the [training loop](https://github.com/huggingface/diffusers/blob/aab6de22c33cc01fb7bc81c0807d6109e2c998c9/examples/text_to_image/train_text_to_image_sdxl.py#L943) takes care of the rest. If you chose to apply a timestep bias strategy, you'll see the timestep weights are calculated and added as noise:
|
| 154 |
+
|
| 155 |
+
```py
|
| 156 |
+
weights = generate_timestep_weights(args, noise_scheduler.config.num_train_timesteps).to(
|
| 157 |
+
model_input.device
|
| 158 |
+
)
|
| 159 |
+
timesteps = torch.multinomial(weights, bsz, replacement=True).long()
|
| 160 |
+
|
| 161 |
+
noisy_model_input = noise_scheduler.add_noise(model_input, noise, timesteps)
|
| 162 |
+
```
|
| 163 |
+
|
| 164 |
+
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.
|
| 165 |
+
|
| 166 |
+
## Launch the script
|
| 167 |
+
|
| 168 |
+
Once you’ve made all your changes or you’re okay with the default configuration, you’re ready to launch the training script! 🚀
|
| 169 |
+
|
| 170 |
+
Let’s train on the [Naruto BLIP captions](https://huggingface.co/datasets/lambdalabs/naruto-blip-captions) dataset to generate your own Naruto characters. Set the environment variables `MODEL_NAME` and `DATASET_NAME` to the model and the dataset (either from the Hub or a local path). You should also specify a VAE other than the SDXL VAE (either from the Hub or a local path) with `VAE_NAME` to avoid numerical instabilities.
|
| 171 |
+
|
| 172 |
+
> [!TIP]
|
| 173 |
+
> To monitor training progress with Weights & Biases, add the `--report_to=wandb` parameter to the training command. You’ll also need to add the `--validation_prompt` and `--validation_epochs` to the training command to keep track of results. This can be really useful for debugging the model and viewing intermediate results.
|
| 174 |
+
|
| 175 |
+
```bash
|
| 176 |
+
export MODEL_NAME="stabilityai/stable-diffusion-xl-base-1.0"
|
| 177 |
+
export VAE_NAME="madebyollin/sdxl-vae-fp16-fix"
|
| 178 |
+
export DATASET_NAME="lambdalabs/naruto-blip-captions"
|
| 179 |
+
|
| 180 |
+
accelerate launch train_text_to_image_sdxl.py \
|
| 181 |
+
--pretrained_model_name_or_path=$MODEL_NAME \
|
| 182 |
+
--pretrained_vae_model_name_or_path=$VAE_NAME \
|
| 183 |
+
--dataset_name=$DATASET_NAME \
|
| 184 |
+
--enable_xformers_memory_efficient_attention \
|
| 185 |
+
--resolution=512 \
|
| 186 |
+
--center_crop \
|
| 187 |
+
--random_flip \
|
| 188 |
+
--proportion_empty_prompts=0.2 \
|
| 189 |
+
--train_batch_size=1 \
|
| 190 |
+
--gradient_accumulation_steps=4 \
|
| 191 |
+
--gradient_checkpointing \
|
| 192 |
+
--max_train_steps=10000 \
|
| 193 |
+
--use_8bit_adam \
|
| 194 |
+
--learning_rate=1e-06 \
|
| 195 |
+
--lr_scheduler="constant" \
|
| 196 |
+
--lr_warmup_steps=0 \
|
| 197 |
+
--mixed_precision="fp16" \
|
| 198 |
+
--report_to="wandb" \
|
| 199 |
+
--validation_prompt="a cute Sundar Pichai creature" \
|
| 200 |
+
--validation_epochs 5 \
|
| 201 |
+
--checkpointing_steps=5000 \
|
| 202 |
+
--output_dir="sdxl-naruto-model" \
|
| 203 |
+
--push_to_hub
|
| 204 |
+
```
|
| 205 |
+
|
| 206 |
+
After you've finished training, you can use your newly trained SDXL model for inference!
|
| 207 |
+
|
| 208 |
+
<hfoptions id="inference">
|
| 209 |
+
<hfoption id="PyTorch">
|
| 210 |
+
|
| 211 |
+
```py
|
| 212 |
+
from diffusers import DiffusionPipeline
|
| 213 |
+
import torch
|
| 214 |
+
|
| 215 |
+
pipeline = DiffusionPipeline.from_pretrained("path/to/your/model", torch_dtype=torch.float16).to("cuda")
|
| 216 |
+
|
| 217 |
+
prompt = "A naruto with green eyes and red legs."
|
| 218 |
+
image = pipeline(prompt, num_inference_steps=30, guidance_scale=7.5).images[0]
|
| 219 |
+
image.save("naruto.png")
|
| 220 |
+
```
|
| 221 |
+
|
| 222 |
+
</hfoption>
|
| 223 |
+
<hfoption id="PyTorch XLA">
|
| 224 |
+
|
| 225 |
+
[PyTorch XLA](https://pytorch.org/xla) allows you to run PyTorch on XLA devices such as TPUs, which can be faster. The initial warmup step takes longer because the model needs to be compiled and optimized. However, subsequent calls to the pipeline on an input **with the same length** as the original prompt are much faster because it can reuse the optimized graph.
|
| 226 |
+
|
| 227 |
+
```py
|
| 228 |
+
from diffusers import DiffusionPipeline
|
| 229 |
+
import torch
|
| 230 |
+
import torch_xla.core.xla_model as xm
|
| 231 |
+
|
| 232 |
+
device = xm.xla_device()
|
| 233 |
+
pipeline = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0").to(device)
|
| 234 |
+
|
| 235 |
+
prompt = "A naruto with green eyes and red legs."
|
| 236 |
+
start = time()
|
| 237 |
+
image = pipeline(prompt, num_inference_steps=inference_steps).images[0]
|
| 238 |
+
print(f'Compilation time is {time()-start} sec')
|
| 239 |
+
image.save("naruto.png")
|
| 240 |
+
|
| 241 |
+
start = time()
|
| 242 |
+
image = pipeline(prompt, num_inference_steps=inference_steps).images[0]
|
| 243 |
+
print(f'Inference time is {time()-start} sec after compilation')
|
| 244 |
+
```
|
| 245 |
+
|
| 246 |
+
</hfoption>
|
| 247 |
+
</hfoptions>
|
| 248 |
+
|
| 249 |
+
## Next steps
|
| 250 |
+
|
| 251 |
+
Congratulations on training a SDXL model! To learn more about how to use your new model, the following guides may be helpful:
|
| 252 |
+
|
| 253 |
+
- Read the [Stable Diffusion XL](../using-diffusers/sdxl) guide to learn how to use it for a variety of different tasks (text-to-image, image-to-image, inpainting), how to use it's refiner model, and the different types of micro-conditionings.
|
| 254 |
+
- Check out the [DreamBooth](dreambooth) and [LoRA](lora) training guides to learn how to train a personalized SDXL model with just a few example images. These two training techniques can even be combined!
|
tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/training/t2i_adapters.md
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# T2I-Adapter
|
| 14 |
+
|
| 15 |
+
[T2I-Adapter](https://hf.co/papers/2302.08453) is a lightweight adapter model that provides an additional conditioning input image (line art, canny, sketch, depth, pose) to better control image generation. It is similar to a ControlNet, but it is a lot smaller (~77M parameters and ~300MB file size) because its only inserts weights into the UNet instead of copying and training it.
|
| 16 |
+
|
| 17 |
+
The T2I-Adapter is only available for training with the Stable Diffusion XL (SDXL) model.
|
| 18 |
+
|
| 19 |
+
This guide will explore the [train_t2i_adapter_sdxl.py](https://github.com/huggingface/diffusers/blob/main/examples/t2i_adapter/train_t2i_adapter_sdxl.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/t2i_adapter
|
| 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/t2i_adapter/train_t2i_adapter_sdxl.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/aab6de22c33cc01fb7bc81c0807d6109e2c998c9/examples/t2i_adapter/train_t2i_adapter_sdxl.py#L233) function. It 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 activate gradient accumulation, add the `--gradient_accumulation_steps` parameter to the training command:
|
| 69 |
+
|
| 70 |
+
```bash
|
| 71 |
+
accelerate launch train_t2i_adapter_sdxl.py \
|
| 72 |
+
----gradient_accumulation_steps=4
|
| 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 T2I-Adapter parameters:
|
| 76 |
+
|
| 77 |
+
- `--pretrained_vae_model_name_or_path`: path to a pretrained VAE; the SDXL VAE is known to suffer from numerical instability, so this parameter allows you to specify a better [VAE](https://huggingface.co/madebyollin/sdxl-vae-fp16-fix)
|
| 78 |
+
- `--crops_coords_top_left_h` and `--crops_coords_top_left_w`: height and width coordinates to include in SDXL's crop coordinate embeddings
|
| 79 |
+
- `--conditioning_image_column`: the column of the conditioning images in the dataset
|
| 80 |
+
- `--proportion_empty_prompts`: the proportion of image prompts to replace with empty strings
|
| 81 |
+
|
| 82 |
+
## Training script
|
| 83 |
+
|
| 84 |
+
As with the script parameters, a 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 T2I-Adapter relevant parts of the script.
|
| 85 |
+
|
| 86 |
+
The training script begins by preparing the dataset. This includes [tokenizing](https://github.com/huggingface/diffusers/blob/aab6de22c33cc01fb7bc81c0807d6109e2c998c9/examples/t2i_adapter/train_t2i_adapter_sdxl.py#L674) the prompt and [applying transforms](https://github.com/huggingface/diffusers/blob/aab6de22c33cc01fb7bc81c0807d6109e2c998c9/examples/t2i_adapter/train_t2i_adapter_sdxl.py#L714) to the images and conditioning images.
|
| 87 |
+
|
| 88 |
+
```py
|
| 89 |
+
conditioning_image_transforms = transforms.Compose(
|
| 90 |
+
[
|
| 91 |
+
transforms.Resize(args.resolution, interpolation=transforms.InterpolationMode.BILINEAR),
|
| 92 |
+
transforms.CenterCrop(args.resolution),
|
| 93 |
+
transforms.ToTensor(),
|
| 94 |
+
]
|
| 95 |
+
)
|
| 96 |
+
```
|
| 97 |
+
|
| 98 |
+
Within the [`main()`](https://github.com/huggingface/diffusers/blob/aab6de22c33cc01fb7bc81c0807d6109e2c998c9/examples/t2i_adapter/train_t2i_adapter_sdxl.py#L770) function, the T2I-Adapter is either loaded from a pretrained adapter or it is randomly initialized:
|
| 99 |
+
|
| 100 |
+
```py
|
| 101 |
+
if args.adapter_model_name_or_path:
|
| 102 |
+
logger.info("Loading existing adapter weights.")
|
| 103 |
+
t2iadapter = T2IAdapter.from_pretrained(args.adapter_model_name_or_path)
|
| 104 |
+
else:
|
| 105 |
+
logger.info("Initializing t2iadapter weights.")
|
| 106 |
+
t2iadapter = T2IAdapter(
|
| 107 |
+
in_channels=3,
|
| 108 |
+
channels=(320, 640, 1280, 1280),
|
| 109 |
+
num_res_blocks=2,
|
| 110 |
+
downscale_factor=16,
|
| 111 |
+
adapter_type="full_adapter_xl",
|
| 112 |
+
)
|
| 113 |
+
```
|
| 114 |
+
|
| 115 |
+
The [optimizer](https://github.com/huggingface/diffusers/blob/aab6de22c33cc01fb7bc81c0807d6109e2c998c9/examples/t2i_adapter/train_t2i_adapter_sdxl.py#L952) is initialized for the T2I-Adapter parameters:
|
| 116 |
+
|
| 117 |
+
```py
|
| 118 |
+
params_to_optimize = t2iadapter.parameters()
|
| 119 |
+
optimizer = optimizer_class(
|
| 120 |
+
params_to_optimize,
|
| 121 |
+
lr=args.learning_rate,
|
| 122 |
+
betas=(args.adam_beta1, args.adam_beta2),
|
| 123 |
+
weight_decay=args.adam_weight_decay,
|
| 124 |
+
eps=args.adam_epsilon,
|
| 125 |
+
)
|
| 126 |
+
```
|
| 127 |
+
|
| 128 |
+
Lastly, in the [training loop](https://github.com/huggingface/diffusers/blob/aab6de22c33cc01fb7bc81c0807d6109e2c998c9/examples/t2i_adapter/train_t2i_adapter_sdxl.py#L1086), the adapter conditioning image and the text embeddings are passed to the UNet to predict the noise residual:
|
| 129 |
+
|
| 130 |
+
```py
|
| 131 |
+
t2iadapter_image = batch["conditioning_pixel_values"].to(dtype=weight_dtype)
|
| 132 |
+
down_block_additional_residuals = t2iadapter(t2iadapter_image)
|
| 133 |
+
down_block_additional_residuals = [
|
| 134 |
+
sample.to(dtype=weight_dtype) for sample in down_block_additional_residuals
|
| 135 |
+
]
|
| 136 |
+
|
| 137 |
+
model_pred = unet(
|
| 138 |
+
inp_noisy_latents,
|
| 139 |
+
timesteps,
|
| 140 |
+
encoder_hidden_states=batch["prompt_ids"],
|
| 141 |
+
added_cond_kwargs=batch["unet_added_conditions"],
|
| 142 |
+
down_block_additional_residuals=down_block_additional_residuals,
|
| 143 |
+
).sample
|
| 144 |
+
```
|
| 145 |
+
|
| 146 |
+
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.
|
| 147 |
+
|
| 148 |
+
## Launch the script
|
| 149 |
+
|
| 150 |
+
Now you’re ready to launch the training script! 🚀
|
| 151 |
+
|
| 152 |
+
For this example training, you'll use the [fusing/fill50k](https://huggingface.co/datasets/fusing/fill50k) dataset. You can also create and use your own dataset if you want (see the [Create a dataset for training](https://moon-ci-docs.huggingface.co/docs/diffusers/pr_5512/en/training/create_dataset) guide).
|
| 153 |
+
|
| 154 |
+
Set the environment variable `MODEL_DIR` 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.
|
| 155 |
+
|
| 156 |
+
Download the following images to condition your training with:
|
| 157 |
+
|
| 158 |
+
```bash
|
| 159 |
+
wget https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/controlnet_training/conditioning_image_1.png
|
| 160 |
+
wget https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/controlnet_training/conditioning_image_2.png
|
| 161 |
+
```
|
| 162 |
+
|
| 163 |
+
> [!TIP]
|
| 164 |
+
> To monitor training progress with Weights & Biases, add the `--report_to=wandb` parameter to the training command. You'll also need to add the `--validation_image`, `--validation_prompt`, and `--validation_steps` to the training command to keep track of results. This can be really useful for debugging the model and viewing intermediate results.
|
| 165 |
+
|
| 166 |
+
```bash
|
| 167 |
+
export MODEL_DIR="stabilityai/stable-diffusion-xl-base-1.0"
|
| 168 |
+
export OUTPUT_DIR="path to save model"
|
| 169 |
+
|
| 170 |
+
accelerate launch train_t2i_adapter_sdxl.py \
|
| 171 |
+
--pretrained_model_name_or_path=$MODEL_DIR \
|
| 172 |
+
--output_dir=$OUTPUT_DIR \
|
| 173 |
+
--dataset_name=fusing/fill50k \
|
| 174 |
+
--mixed_precision="fp16" \
|
| 175 |
+
--resolution=1024 \
|
| 176 |
+
--learning_rate=1e-5 \
|
| 177 |
+
--max_train_steps=15000 \
|
| 178 |
+
--validation_image "./conditioning_image_1.png" "./conditioning_image_2.png" \
|
| 179 |
+
--validation_prompt "red circle with blue background" "cyan circle with brown floral background" \
|
| 180 |
+
--validation_steps=100 \
|
| 181 |
+
--train_batch_size=1 \
|
| 182 |
+
--gradient_accumulation_steps=4 \
|
| 183 |
+
--report_to="wandb" \
|
| 184 |
+
--seed=42 \
|
| 185 |
+
--push_to_hub
|
| 186 |
+
```
|
| 187 |
+
|
| 188 |
+
Once training is complete, you can use your T2I-Adapter for inference:
|
| 189 |
+
|
| 190 |
+
```py
|
| 191 |
+
from diffusers import StableDiffusionXLAdapterPipeline, T2IAdapter, EulerAncestralDiscreteSchedulerTest
|
| 192 |
+
from diffusers.utils import load_image
|
| 193 |
+
import torch
|
| 194 |
+
|
| 195 |
+
adapter = T2IAdapter.from_pretrained("path/to/adapter", torch_dtype=torch.float16)
|
| 196 |
+
pipeline = StableDiffusionXLAdapterPipeline.from_pretrained(
|
| 197 |
+
"stabilityai/stable-diffusion-xl-base-1.0", adapter=adapter, torch_dtype=torch.float16
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
pipeline.scheduler = EulerAncestralDiscreteSchedulerTest.from_config(pipe.scheduler.config)
|
| 201 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 202 |
+
pipeline.enable_model_cpu_offload()
|
| 203 |
+
|
| 204 |
+
control_image = load_image("./conditioning_image_1.png")
|
| 205 |
+
prompt = "pale golden rod circle with old lace background"
|
| 206 |
+
|
| 207 |
+
generator = torch.manual_seed(0)
|
| 208 |
+
image = pipeline(
|
| 209 |
+
prompt, image=control_image, generator=generator
|
| 210 |
+
).images[0]
|
| 211 |
+
image.save("./output.png")
|
| 212 |
+
```
|
| 213 |
+
|
| 214 |
+
## Next steps
|
| 215 |
+
|
| 216 |
+
Congratulations on training a T2I-Adapter model! 🎉 To learn more:
|
| 217 |
+
|
| 218 |
+
- Read the [Efficient Controllable Generation for SDXL with T2I-Adapters](https://huggingface.co/blog/t2i-sdxl-adapters) blog post to learn more details about the experimental results from the T2I-Adapter team.
|
tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/training/text2image.md
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# Text-to-image
|
| 14 |
+
|
| 15 |
+
> [!WARNING]
|
| 16 |
+
> The text-to-image script is experimental, and it's easy to overfit and run into issues like catastrophic forgetting. Try exploring different hyperparameters to get the best results on your dataset.
|
| 17 |
+
|
| 18 |
+
Text-to-image models like Stable Diffusion are conditioned to generate images given a text prompt.
|
| 19 |
+
|
| 20 |
+
Training a model can be taxing on your hardware, but if you enable `gradient_checkpointing` and `mixed_precision`, it is possible to train a model on a single 24GB GPU. If you're training with larger batch sizes or want to train faster, it's better to use GPUs with more than 30GB of memory. You can reduce your memory footprint by enabling memory-efficient attention with [xFormers](../optimization/xformers).
|
| 21 |
+
|
| 22 |
+
This guide will explore the [train_text_to_image.py](https://github.com/huggingface/diffusers/blob/main/examples/text_to_image/train_text_to_image.py) training script to help you become familiar with it, and how you can adapt it for your own use-case.
|
| 23 |
+
|
| 24 |
+
Before running the script, make sure you install the library from source:
|
| 25 |
+
|
| 26 |
+
```bash
|
| 27 |
+
git clone https://github.com/huggingface/diffusers
|
| 28 |
+
cd diffusers
|
| 29 |
+
pip install .
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
Then navigate to the example folder containing the training script and install the required dependencies for the script you're using:
|
| 33 |
+
|
| 34 |
+
```bash
|
| 35 |
+
cd examples/text_to_image
|
| 36 |
+
pip install -r requirements.txt
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
> [!TIP]
|
| 40 |
+
> 🤗 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.
|
| 41 |
+
|
| 42 |
+
Initialize an 🤗 Accelerate environment:
|
| 43 |
+
|
| 44 |
+
```bash
|
| 45 |
+
accelerate config
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
To setup a default 🤗 Accelerate environment without choosing any configurations:
|
| 49 |
+
|
| 50 |
+
```bash
|
| 51 |
+
accelerate config default
|
| 52 |
+
```
|
| 53 |
+
|
| 54 |
+
Or if your environment doesn't support an interactive shell, like a notebook, you can use:
|
| 55 |
+
|
| 56 |
+
```py
|
| 57 |
+
from accelerate.utils import write_basic_config
|
| 58 |
+
|
| 59 |
+
write_basic_config()
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
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.
|
| 63 |
+
|
| 64 |
+
## Script parameters
|
| 65 |
+
|
| 66 |
+
> [!TIP]
|
| 67 |
+
> 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/text_to_image/train_text_to_image.py) and let us know if you have any questions or concerns.
|
| 68 |
+
|
| 69 |
+
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/8959c5b9dec1c94d6ba482c94a58d2215c5fd026/examples/text_to_image/train_text_to_image.py#L193) 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.
|
| 70 |
+
|
| 71 |
+
For example, to speedup training with mixed precision using the fp16 format, add the `--mixed_precision` parameter to the training command:
|
| 72 |
+
|
| 73 |
+
```bash
|
| 74 |
+
accelerate launch train_text_to_image.py \
|
| 75 |
+
--mixed_precision="fp16"
|
| 76 |
+
```
|
| 77 |
+
|
| 78 |
+
Some basic and important parameters include:
|
| 79 |
+
|
| 80 |
+
- `--pretrained_model_name_or_path`: the name of the model on the Hub or a local path to the pretrained model
|
| 81 |
+
- `--dataset_name`: the name of the dataset on the Hub or a local path to the dataset to train on
|
| 82 |
+
- `--image_column`: the name of the image column in the dataset to train on
|
| 83 |
+
- `--caption_column`: the name of the text column in the dataset to train on
|
| 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_text_to_image.py \
|
| 96 |
+
--snr_gamma=5.0
|
| 97 |
+
```
|
| 98 |
+
|
| 99 |
+
You can compare the loss surfaces for different `snr_gamma` values in this [Weights and Biases](https://wandb.ai/sayakpaul/text2image-finetune-minsnr) report. For smaller datasets, the effects of Min-SNR may not be as obvious compared to larger datasets.
|
| 100 |
+
|
| 101 |
+
## Training script
|
| 102 |
+
|
| 103 |
+
The dataset preprocessing code and training loop are found in the [`main()`](https://github.com/huggingface/diffusers/blob/8959c5b9dec1c94d6ba482c94a58d2215c5fd026/examples/text_to_image/train_text_to_image.py#L490) function. If you need to adapt the training script, this is where you'll need to make your changes.
|
| 104 |
+
|
| 105 |
+
The `train_text_to_image` script starts by [loading a scheduler](https://github.com/huggingface/diffusers/blob/8959c5b9dec1c94d6ba482c94a58d2215c5fd026/examples/text_to_image/train_text_to_image.py#L543) and tokenizer. You can choose to use a different scheduler here if you want:
|
| 106 |
+
|
| 107 |
+
```py
|
| 108 |
+
noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
|
| 109 |
+
tokenizer = CLIPTokenizer.from_pretrained(
|
| 110 |
+
args.pretrained_model_name_or_path, subfolder="tokenizer", revision=args.revision
|
| 111 |
+
)
|
| 112 |
+
```
|
| 113 |
+
|
| 114 |
+
Then the script [loads the UNet](https://github.com/huggingface/diffusers/blob/8959c5b9dec1c94d6ba482c94a58d2215c5fd026/examples/text_to_image/train_text_to_image.py#L619) model:
|
| 115 |
+
|
| 116 |
+
```py
|
| 117 |
+
load_model = UNet2DConditionModel.from_pretrained(input_dir, subfolder="unet")
|
| 118 |
+
model.register_to_config(**load_model.config)
|
| 119 |
+
|
| 120 |
+
model.load_state_dict(load_model.state_dict())
|
| 121 |
+
```
|
| 122 |
+
|
| 123 |
+
Next, the text and image columns of the dataset need to be preprocessed. The [`tokenize_captions`](https://github.com/huggingface/diffusers/blob/8959c5b9dec1c94d6ba482c94a58d2215c5fd026/examples/text_to_image/train_text_to_image.py#L724) function handles tokenizing the inputs, and the [`train_transforms`](https://github.com/huggingface/diffusers/blob/8959c5b9dec1c94d6ba482c94a58d2215c5fd026/examples/text_to_image/train_text_to_image.py#L742) function specifies the type of transforms to apply to the image. Both of these functions are bundled into `preprocess_train`:
|
| 124 |
+
|
| 125 |
+
```py
|
| 126 |
+
def preprocess_train(examples):
|
| 127 |
+
images = [image.convert("RGB") for image in examples[image_column]]
|
| 128 |
+
examples["pixel_values"] = [train_transforms(image) for image in images]
|
| 129 |
+
examples["input_ids"] = tokenize_captions(examples)
|
| 130 |
+
return examples
|
| 131 |
+
```
|
| 132 |
+
|
| 133 |
+
Lastly, the [training loop](https://github.com/huggingface/diffusers/blob/8959c5b9dec1c94d6ba482c94a58d2215c5fd026/examples/text_to_image/train_text_to_image.py#L878) handles everything else. It encodes images into latent space, adds noise to the latents, computes the text embeddings to condition on, updates the model parameters, and saves and pushes the model to the Hub. 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.
|
| 134 |
+
|
| 135 |
+
## Launch the script
|
| 136 |
+
|
| 137 |
+
Once you've made all your changes or you're okay with the default configuration, you're ready to launch the training script! 🚀
|
| 138 |
+
|
| 139 |
+
Let's train on the [Naruto BLIP captions](https://huggingface.co/datasets/lambdalabs/naruto-blip-captions) dataset to generate your own Naruto characters. Set the environment variables `MODEL_NAME` and `dataset_name` to the model and the dataset (either from the Hub or a local path). If you're training on more than one GPU, add the `--multi_gpu` parameter to the `accelerate launch` command.
|
| 140 |
+
|
| 141 |
+
> [!TIP]
|
| 142 |
+
> To train on a local dataset, set the `TRAIN_DIR` and `OUTPUT_DIR` environment variables to the path of the dataset and where to save the model to.
|
| 143 |
+
|
| 144 |
+
```bash
|
| 145 |
+
export MODEL_NAME="stable-diffusion-v1-5/stable-diffusion-v1-5"
|
| 146 |
+
export dataset_name="lambdalabs/naruto-blip-captions"
|
| 147 |
+
|
| 148 |
+
accelerate launch --mixed_precision="fp16" train_text_to_image.py \
|
| 149 |
+
--pretrained_model_name_or_path=$MODEL_NAME \
|
| 150 |
+
--dataset_name=$dataset_name \
|
| 151 |
+
--use_ema \
|
| 152 |
+
--resolution=512 --center_crop --random_flip \
|
| 153 |
+
--train_batch_size=1 \
|
| 154 |
+
--gradient_accumulation_steps=4 \
|
| 155 |
+
--gradient_checkpointing \
|
| 156 |
+
--max_train_steps=15000 \
|
| 157 |
+
--learning_rate=1e-05 \
|
| 158 |
+
--max_grad_norm=1 \
|
| 159 |
+
--enable_xformers_memory_efficient_attention \
|
| 160 |
+
--lr_scheduler="constant" --lr_warmup_steps=0 \
|
| 161 |
+
--output_dir="sd-naruto-model" \
|
| 162 |
+
--push_to_hub
|
| 163 |
+
```
|
| 164 |
+
|
| 165 |
+
Once training is complete, you can use your newly trained model for inference:
|
| 166 |
+
|
| 167 |
+
```py
|
| 168 |
+
from diffusers import StableDiffusionPipeline
|
| 169 |
+
import torch
|
| 170 |
+
|
| 171 |
+
pipeline = StableDiffusionPipeline.from_pretrained("path/to/saved_model", torch_dtype=torch.float16, use_safetensors=True).to("cuda")
|
| 172 |
+
|
| 173 |
+
image = pipeline(prompt="yoda").images[0]
|
| 174 |
+
image.save("yoda-naruto.png")
|
| 175 |
+
```
|
| 176 |
+
|
| 177 |
+
## Next steps
|
| 178 |
+
|
| 179 |
+
Congratulations on training your own text-to-image model! To learn more about how to use your new model, the following guides may be helpful:
|
| 180 |
+
|
| 181 |
+
- Learn how to [load LoRA weights](../tutorials/using_peft_for_inference) for inference if you trained your model with LoRA.
|
| 182 |
+
- Learn more about how certain parameters like guidance scale or techniques such as prompt weighting can help you control inference in the [Text-to-image](../using-diffusers/conditional_image_generation) task guide.
|
tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/training/text_inversion.md
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# Textual Inversion
|
| 14 |
+
|
| 15 |
+
[Textual Inversion](https://hf.co/papers/2208.01618) is a training technique for personalizing image generation models with just a few example images of what you want it to learn. This technique works by learning and updating the text embeddings (the new embeddings are tied to a special word you must use in the prompt) to match the example images you provide.
|
| 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 [textual_inversion.py](https://github.com/huggingface/diffusers/blob/main/examples/textual_inversion/textual_inversion.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/textual_inversion
|
| 33 |
+
pip install -r requirements.txt
|
| 34 |
+
```
|
| 35 |
+
> [!TIP]
|
| 36 |
+
> 🤗 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.
|
| 37 |
+
|
| 38 |
+
Initialize an 🤗 Accelerate environment:
|
| 39 |
+
|
| 40 |
+
```bash
|
| 41 |
+
accelerate config
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
To setup a default 🤗 Accelerate environment without choosing any configurations:
|
| 45 |
+
|
| 46 |
+
```bash
|
| 47 |
+
accelerate config default
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
Or if your environment doesn't support an interactive shell, like a notebook, you can use:
|
| 51 |
+
|
| 52 |
+
```py
|
| 53 |
+
from accelerate.utils import write_basic_config
|
| 54 |
+
|
| 55 |
+
write_basic_config()
|
| 56 |
+
```
|
| 57 |
+
|
| 58 |
+
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.
|
| 59 |
+
|
| 60 |
+
> [!TIP]
|
| 61 |
+
> 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/textual_inversion/textual_inversion.py) and let us know if you have any questions or concerns.
|
| 62 |
+
|
| 63 |
+
## Script parameters
|
| 64 |
+
|
| 65 |
+
The training script has many parameters to help you tailor the training run to your needs. All of the parameters and their descriptions are listed in the [`parse_args()`](https://github.com/huggingface/diffusers/blob/839c2a5ece0af4e75530cb520d77bc7ed8acf474/examples/textual_inversion/textual_inversion.py#L176) function. Where applicable, Diffusers provides default values for each parameter such as the training batch size and learning rate, but feel free to change these values in the training command if you'd like.
|
| 66 |
+
|
| 67 |
+
For example, to increase the number of gradient accumulation steps above the default value of 1:
|
| 68 |
+
|
| 69 |
+
```bash
|
| 70 |
+
accelerate launch textual_inversion.py \
|
| 71 |
+
--gradient_accumulation_steps=4
|
| 72 |
+
```
|
| 73 |
+
|
| 74 |
+
Some other basic and important parameters to specify include:
|
| 75 |
+
|
| 76 |
+
- `--pretrained_model_name_or_path`: the name of the model on the Hub or a local path to the pretrained model
|
| 77 |
+
- `--train_data_dir`: path to a folder containing the training dataset (example images)
|
| 78 |
+
- `--output_dir`: where to save the trained model
|
| 79 |
+
- `--push_to_hub`: whether to push the trained model to the Hub
|
| 80 |
+
- `--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
|
| 81 |
+
- `--num_vectors`: the number of vectors to learn the embeddings with; increasing this parameter helps the model learn better but it comes with increased training costs
|
| 82 |
+
- `--placeholder_token`: the special word to tie the learned embeddings to (you must use the word in your prompt for inference)
|
| 83 |
+
- `--initializer_token`: a single-word that roughly describes the object or style you're trying to train on
|
| 84 |
+
- `--learnable_property`: whether you're training the model to learn a new "style" (for example, Van Gogh's painting style) or "object" (for example, your dog)
|
| 85 |
+
|
| 86 |
+
## Training script
|
| 87 |
+
|
| 88 |
+
Unlike some of the other training scripts, textual_inversion.py has a custom dataset class, [`TextualInversionDataset`](https://github.com/huggingface/diffusers/blob/b81c69e489aad3a0ba73798c459a33990dc4379c/examples/textual_inversion/textual_inversion.py#L487) for creating a dataset. You can customize the image size, placeholder token, interpolation method, whether to crop the image, and more. If you need to change how the dataset is created, you can modify `TextualInversionDataset`.
|
| 89 |
+
|
| 90 |
+
Next, you'll find the dataset preprocessing code and training loop in the [`main()`](https://github.com/huggingface/diffusers/blob/839c2a5ece0af4e75530cb520d77bc7ed8acf474/examples/textual_inversion/textual_inversion.py#L573) function.
|
| 91 |
+
|
| 92 |
+
The script starts by loading the [tokenizer](https://github.com/huggingface/diffusers/blob/b81c69e489aad3a0ba73798c459a33990dc4379c/examples/textual_inversion/textual_inversion.py#L616), [scheduler and model](https://github.com/huggingface/diffusers/blob/b81c69e489aad3a0ba73798c459a33990dc4379c/examples/textual_inversion/textual_inversion.py#L622):
|
| 93 |
+
|
| 94 |
+
```py
|
| 95 |
+
# Load tokenizer
|
| 96 |
+
if args.tokenizer_name:
|
| 97 |
+
tokenizer = CLIPTokenizer.from_pretrained(args.tokenizer_name)
|
| 98 |
+
elif args.pretrained_model_name_or_path:
|
| 99 |
+
tokenizer = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="tokenizer")
|
| 100 |
+
|
| 101 |
+
# Load scheduler and models
|
| 102 |
+
noise_scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
|
| 103 |
+
text_encoder = CLIPTextModel.from_pretrained(
|
| 104 |
+
args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision
|
| 105 |
+
)
|
| 106 |
+
vae = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae", revision=args.revision)
|
| 107 |
+
unet = UNet2DConditionModel.from_pretrained(
|
| 108 |
+
args.pretrained_model_name_or_path, subfolder="unet", revision=args.revision
|
| 109 |
+
)
|
| 110 |
+
```
|
| 111 |
+
|
| 112 |
+
The special [placeholder token](https://github.com/huggingface/diffusers/blob/b81c69e489aad3a0ba73798c459a33990dc4379c/examples/textual_inversion/textual_inversion.py#L632) is added next to the tokenizer, and the embedding is readjusted to account for the new token.
|
| 113 |
+
|
| 114 |
+
Then, the script [creates a dataset](https://github.com/huggingface/diffusers/blob/b81c69e489aad3a0ba73798c459a33990dc4379c/examples/textual_inversion/textual_inversion.py#L716) from the `TextualInversionDataset`:
|
| 115 |
+
|
| 116 |
+
```py
|
| 117 |
+
train_dataset = TextualInversionDataset(
|
| 118 |
+
data_root=args.train_data_dir,
|
| 119 |
+
tokenizer=tokenizer,
|
| 120 |
+
size=args.resolution,
|
| 121 |
+
placeholder_token=(" ".join(tokenizer.convert_ids_to_tokens(placeholder_token_ids))),
|
| 122 |
+
repeats=args.repeats,
|
| 123 |
+
learnable_property=args.learnable_property,
|
| 124 |
+
center_crop=args.center_crop,
|
| 125 |
+
set="train",
|
| 126 |
+
)
|
| 127 |
+
train_dataloader = torch.utils.data.DataLoader(
|
| 128 |
+
train_dataset, batch_size=args.train_batch_size, shuffle=True, num_workers=args.dataloader_num_workers
|
| 129 |
+
)
|
| 130 |
+
```
|
| 131 |
+
|
| 132 |
+
Finally, the [training loop](https://github.com/huggingface/diffusers/blob/b81c69e489aad3a0ba73798c459a33990dc4379c/examples/textual_inversion/textual_inversion.py#L784) handles everything else from predicting the noisy residual to updating the embedding weights of the special placeholder token.
|
| 133 |
+
|
| 134 |
+
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.
|
| 135 |
+
|
| 136 |
+
## Launch the script
|
| 137 |
+
|
| 138 |
+
Once you've made all your changes or you're okay with the default configuration, you're ready to launch the training script! 🚀
|
| 139 |
+
|
| 140 |
+
For this guide, you'll download some images of a [cat toy](https://huggingface.co/datasets/diffusers/cat_toy_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).
|
| 141 |
+
|
| 142 |
+
```py
|
| 143 |
+
from huggingface_hub import snapshot_download
|
| 144 |
+
|
| 145 |
+
local_dir = "./cat"
|
| 146 |
+
snapshot_download(
|
| 147 |
+
"diffusers/cat_toy_example", local_dir=local_dir, repo_type="dataset", ignore_patterns=".gitattributes"
|
| 148 |
+
)
|
| 149 |
+
```
|
| 150 |
+
|
| 151 |
+
Set the environment variable `MODEL_NAME` to a model id on the Hub or a path to a local model, and `DATA_DIR` to the path where you just downloaded the cat images to. The script creates and saves the following files to your repository:
|
| 152 |
+
|
| 153 |
+
- `learned_embeds.bin`: the learned embedding vectors corresponding to your example images
|
| 154 |
+
- `token_identifier.txt`: the special placeholder token
|
| 155 |
+
- `type_of_concept.txt`: the type of concept you're training on (either "object" or "style")
|
| 156 |
+
|
| 157 |
+
> [!WARNING]
|
| 158 |
+
> A full training run takes ~1 hour on a single V100 GPU.
|
| 159 |
+
|
| 160 |
+
One more thing before you launch the script. 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:
|
| 161 |
+
|
| 162 |
+
```bash
|
| 163 |
+
--validation_prompt="A <cat-toy> train"
|
| 164 |
+
--num_validation_images=4
|
| 165 |
+
--validation_steps=100
|
| 166 |
+
```
|
| 167 |
+
|
| 168 |
+
```bash
|
| 169 |
+
export MODEL_NAME="stable-diffusion-v1-5/stable-diffusion-v1-5"
|
| 170 |
+
export DATA_DIR="./cat"
|
| 171 |
+
|
| 172 |
+
accelerate launch textual_inversion.py \
|
| 173 |
+
--pretrained_model_name_or_path=$MODEL_NAME \
|
| 174 |
+
--train_data_dir=$DATA_DIR \
|
| 175 |
+
--learnable_property="object" \
|
| 176 |
+
--placeholder_token="<cat-toy>" \
|
| 177 |
+
--initializer_token="toy" \
|
| 178 |
+
--resolution=512 \
|
| 179 |
+
--train_batch_size=1 \
|
| 180 |
+
--gradient_accumulation_steps=4 \
|
| 181 |
+
--max_train_steps=3000 \
|
| 182 |
+
--learning_rate=5.0e-04 \
|
| 183 |
+
--scale_lr \
|
| 184 |
+
--lr_scheduler="constant" \
|
| 185 |
+
--lr_warmup_steps=0 \
|
| 186 |
+
--output_dir="textual_inversion_cat" \
|
| 187 |
+
--push_to_hub
|
| 188 |
+
```
|
| 189 |
+
|
| 190 |
+
After training is complete, you can use your newly trained model for inference like:
|
| 191 |
+
|
| 192 |
+
```py
|
| 193 |
+
from diffusers import StableDiffusionPipeline
|
| 194 |
+
import torch
|
| 195 |
+
|
| 196 |
+
pipeline = StableDiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16).to("cuda")
|
| 197 |
+
pipeline.load_textual_inversion("sd-concepts-library/cat-toy")
|
| 198 |
+
image = pipeline("A <cat-toy> train", num_inference_steps=50).images[0]
|
| 199 |
+
image.save("cat-train.png")
|
| 200 |
+
```
|
| 201 |
+
|
| 202 |
+
## Next steps
|
| 203 |
+
|
| 204 |
+
Congratulations on training your own Textual Inversion model! 🎉 To learn more about how to use your new model, the following guides may be helpful:
|
| 205 |
+
|
| 206 |
+
- Learn how to [load Textual Inversion embeddings](../using-diffusers/textual_inversion_inference) and also use them as negative embeddings.
|
tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/training/unconditional_training.md
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# Unconditional image generation
|
| 14 |
+
|
| 15 |
+
Unconditional image generation models are not conditioned on text or images during training. It only generates images that resemble its training data distribution.
|
| 16 |
+
|
| 17 |
+
This guide will explore the [train_unconditional.py](https://github.com/huggingface/diffusers/blob/main/examples/unconditional_image_generation/train_unconditional.py) training script to help you become familiar with it, and how you can adapt it for your own use-case.
|
| 18 |
+
|
| 19 |
+
Before running the script, make sure you install the library from source:
|
| 20 |
+
|
| 21 |
+
```bash
|
| 22 |
+
git clone https://github.com/huggingface/diffusers
|
| 23 |
+
cd diffusers
|
| 24 |
+
pip install .
|
| 25 |
+
```
|
| 26 |
+
|
| 27 |
+
Then navigate to the example folder containing the training script and install the required dependencies:
|
| 28 |
+
|
| 29 |
+
```bash
|
| 30 |
+
cd examples/unconditional_image_generation
|
| 31 |
+
pip install -r requirements.txt
|
| 32 |
+
```
|
| 33 |
+
|
| 34 |
+
> [!TIP]
|
| 35 |
+
> 🤗 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.
|
| 36 |
+
|
| 37 |
+
Initialize an 🤗 Accelerate environment:
|
| 38 |
+
|
| 39 |
+
```bash
|
| 40 |
+
accelerate config
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
To setup a default 🤗 Accelerate environment without choosing any configurations:
|
| 44 |
+
|
| 45 |
+
```bash
|
| 46 |
+
accelerate config default
|
| 47 |
+
```
|
| 48 |
+
|
| 49 |
+
Or if your environment doesn't support an interactive shell like a notebook, you can use:
|
| 50 |
+
|
| 51 |
+
```py
|
| 52 |
+
from accelerate.utils import write_basic_config
|
| 53 |
+
|
| 54 |
+
write_basic_config()
|
| 55 |
+
```
|
| 56 |
+
|
| 57 |
+
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.
|
| 58 |
+
|
| 59 |
+
## Script parameters
|
| 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/unconditional_image_generation/train_unconditional.py) and let us know if you have any questions or concerns.
|
| 63 |
+
|
| 64 |
+
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/096f84b05f9514fae9f185cbec0a4d38fbad9919/examples/unconditional_image_generation/train_unconditional.py#L55) function. It 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.
|
| 65 |
+
|
| 66 |
+
For example, to speedup training with mixed precision using the bf16 format, add the `--mixed_precision` parameter to the training command:
|
| 67 |
+
|
| 68 |
+
```bash
|
| 69 |
+
accelerate launch train_unconditional.py \
|
| 70 |
+
--mixed_precision="bf16"
|
| 71 |
+
```
|
| 72 |
+
|
| 73 |
+
Some basic and important parameters to specify include:
|
| 74 |
+
|
| 75 |
+
- `--dataset_name`: the name of the dataset on the Hub or a local path to the dataset to train on
|
| 76 |
+
- `--output_dir`: where to save the trained model
|
| 77 |
+
- `--push_to_hub`: whether to push the trained model to the Hub
|
| 78 |
+
- `--checkpointing_steps`: frequency of saving a checkpoint as the model trains; this is useful if training is interrupted, you can continue training from that checkpoint by adding `--resume_from_checkpoint` to your training command
|
| 79 |
+
|
| 80 |
+
Bring your dataset, and let the training script handle everything else!
|
| 81 |
+
|
| 82 |
+
## Training script
|
| 83 |
+
|
| 84 |
+
The code for preprocessing the dataset and the training loop is found in the [`main()`](https://github.com/huggingface/diffusers/blob/096f84b05f9514fae9f185cbec0a4d38fbad9919/examples/unconditional_image_generation/train_unconditional.py#L275) function. If you need to adapt the training script, this is where you'll need to make your changes.
|
| 85 |
+
|
| 86 |
+
The `train_unconditional` script [initializes a `UNet2DModel`](https://github.com/huggingface/diffusers/blob/096f84b05f9514fae9f185cbec0a4d38fbad9919/examples/unconditional_image_generation/train_unconditional.py#L356) if you don't provide a model configuration. You can configure the UNet here if you'd like:
|
| 87 |
+
|
| 88 |
+
```py
|
| 89 |
+
model = UNet2DModel(
|
| 90 |
+
sample_size=args.resolution,
|
| 91 |
+
in_channels=3,
|
| 92 |
+
out_channels=3,
|
| 93 |
+
layers_per_block=2,
|
| 94 |
+
block_out_channels=(128, 128, 256, 256, 512, 512),
|
| 95 |
+
down_block_types=(
|
| 96 |
+
"DownBlock2D",
|
| 97 |
+
"DownBlock2D",
|
| 98 |
+
"DownBlock2D",
|
| 99 |
+
"DownBlock2D",
|
| 100 |
+
"AttnDownBlock2D",
|
| 101 |
+
"DownBlock2D",
|
| 102 |
+
),
|
| 103 |
+
up_block_types=(
|
| 104 |
+
"UpBlock2D",
|
| 105 |
+
"AttnUpBlock2D",
|
| 106 |
+
"UpBlock2D",
|
| 107 |
+
"UpBlock2D",
|
| 108 |
+
"UpBlock2D",
|
| 109 |
+
"UpBlock2D",
|
| 110 |
+
),
|
| 111 |
+
)
|
| 112 |
+
```
|
| 113 |
+
|
| 114 |
+
Next, the script initializes a [scheduler](https://github.com/huggingface/diffusers/blob/096f84b05f9514fae9f185cbec0a4d38fbad9919/examples/unconditional_image_generation/train_unconditional.py#L418) and [optimizer](https://github.com/huggingface/diffusers/blob/096f84b05f9514fae9f185cbec0a4d38fbad9919/examples/unconditional_image_generation/train_unconditional.py#L429):
|
| 115 |
+
|
| 116 |
+
```py
|
| 117 |
+
# Initialize the scheduler
|
| 118 |
+
accepts_prediction_type = "prediction_type" in set(inspect.signature(DDPMScheduler.__init__).parameters.keys())
|
| 119 |
+
if accepts_prediction_type:
|
| 120 |
+
noise_scheduler = DDPMScheduler(
|
| 121 |
+
num_train_timesteps=args.ddpm_num_steps,
|
| 122 |
+
beta_schedule=args.ddpm_beta_schedule,
|
| 123 |
+
prediction_type=args.prediction_type,
|
| 124 |
+
)
|
| 125 |
+
else:
|
| 126 |
+
noise_scheduler = DDPMScheduler(num_train_timesteps=args.ddpm_num_steps, beta_schedule=args.ddpm_beta_schedule)
|
| 127 |
+
|
| 128 |
+
# Initialize the optimizer
|
| 129 |
+
optimizer = torch.optim.AdamW(
|
| 130 |
+
model.parameters(),
|
| 131 |
+
lr=args.learning_rate,
|
| 132 |
+
betas=(args.adam_beta1, args.adam_beta2),
|
| 133 |
+
weight_decay=args.adam_weight_decay,
|
| 134 |
+
eps=args.adam_epsilon,
|
| 135 |
+
)
|
| 136 |
+
```
|
| 137 |
+
|
| 138 |
+
Then it [loads a dataset](https://github.com/huggingface/diffusers/blob/096f84b05f9514fae9f185cbec0a4d38fbad9919/examples/unconditional_image_generation/train_unconditional.py#L451) and you can specify how to [preprocess](https://github.com/huggingface/diffusers/blob/096f84b05f9514fae9f185cbec0a4d38fbad9919/examples/unconditional_image_generation/train_unconditional.py#L455) it:
|
| 139 |
+
|
| 140 |
+
```py
|
| 141 |
+
dataset = load_dataset("imagefolder", data_dir=args.train_data_dir, cache_dir=args.cache_dir, split="train")
|
| 142 |
+
|
| 143 |
+
augmentations = transforms.Compose(
|
| 144 |
+
[
|
| 145 |
+
transforms.Resize(args.resolution, interpolation=transforms.InterpolationMode.BILINEAR),
|
| 146 |
+
transforms.CenterCrop(args.resolution) if args.center_crop else transforms.RandomCrop(args.resolution),
|
| 147 |
+
transforms.RandomHorizontalFlip() if args.random_flip else transforms.Lambda(lambda x: x),
|
| 148 |
+
transforms.ToTensor(),
|
| 149 |
+
transforms.Normalize([0.5], [0.5]),
|
| 150 |
+
]
|
| 151 |
+
)
|
| 152 |
+
```
|
| 153 |
+
|
| 154 |
+
Finally, the [training loop](https://github.com/huggingface/diffusers/blob/096f84b05f9514fae9f185cbec0a4d38fbad9919/examples/unconditional_image_generation/train_unconditional.py#L540) handles everything else such as adding noise to the images, predicting the noise residual, calculating the loss, saving checkpoints at specified steps, and saving and pushing the model to the Hub. 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.
|
| 155 |
+
|
| 156 |
+
## Launch the script
|
| 157 |
+
|
| 158 |
+
Once you've made all your changes or you're okay with the default configuration, you're ready to launch the training script! 🚀
|
| 159 |
+
|
| 160 |
+
> [!WARNING]
|
| 161 |
+
> A full training run takes 2 hours on 4xV100 GPUs.
|
| 162 |
+
|
| 163 |
+
<hfoptions id="launchtraining">
|
| 164 |
+
<hfoption id="single GPU">
|
| 165 |
+
|
| 166 |
+
```bash
|
| 167 |
+
accelerate launch train_unconditional.py \
|
| 168 |
+
--dataset_name="huggan/flowers-102-categories" \
|
| 169 |
+
--output_dir="ddpm-ema-flowers-64" \
|
| 170 |
+
--mixed_precision="fp16" \
|
| 171 |
+
--push_to_hub
|
| 172 |
+
```
|
| 173 |
+
|
| 174 |
+
</hfoption>
|
| 175 |
+
<hfoption id="multi-GPU">
|
| 176 |
+
|
| 177 |
+
If you're training with more than one GPU, add the `--multi_gpu` parameter to the training command:
|
| 178 |
+
|
| 179 |
+
```bash
|
| 180 |
+
accelerate launch --multi_gpu train_unconditional.py \
|
| 181 |
+
--dataset_name="huggan/flowers-102-categories" \
|
| 182 |
+
--output_dir="ddpm-ema-flowers-64" \
|
| 183 |
+
--mixed_precision="fp16" \
|
| 184 |
+
--push_to_hub
|
| 185 |
+
```
|
| 186 |
+
|
| 187 |
+
</hfoption>
|
| 188 |
+
</hfoptions>
|
| 189 |
+
|
| 190 |
+
The training script creates and saves a checkpoint file in your repository. Now you can load and use your trained model for inference:
|
| 191 |
+
|
| 192 |
+
```py
|
| 193 |
+
from diffusers import DiffusionPipeline
|
| 194 |
+
import torch
|
| 195 |
+
|
| 196 |
+
pipeline = DiffusionPipeline.from_pretrained("anton-l/ddpm-butterflies-128").to("cuda")
|
| 197 |
+
image = pipeline().images[0]
|
| 198 |
+
```
|
tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/training/wuerstchen.md
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# Wuerstchen
|
| 14 |
+
|
| 15 |
+
The [Wuerstchen](https://hf.co/papers/2306.00637) model drastically reduces computational costs by compressing the latent space by 42x, without compromising image quality and accelerating inference. During training, Wuerstchen uses two models (VQGAN + autoencoder) to compress the latents, and then a third model (text-conditioned latent diffusion model) is conditioned on this highly compressed space to generate an image.
|
| 16 |
+
|
| 17 |
+
To fit the prior model into GPU memory and to speedup training, try enabling `gradient_accumulation_steps`, `gradient_checkpointing`, and `mixed_precision` respectively.
|
| 18 |
+
|
| 19 |
+
This guide explores the [train_text_to_image_prior.py](https://github.com/huggingface/diffusers/blob/main/examples/wuerstchen/text_to_image/train_text_to_image_prior.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 |
+
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/wuerstchen/text_to_image
|
| 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 scripts that are important for understanding how to modify it, but it doesn't cover every aspect of the [script](https://github.com/huggingface/diffusers/blob/main/examples/wuerstchen/text_to_image/train_text_to_image_prior.py) in detail. If you're interested in learning more, feel free to read through the scripts and let us know if you have any questions or concerns.
|
| 63 |
+
|
| 64 |
+
## Script parameters
|
| 65 |
+
|
| 66 |
+
The training scripts 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/6e68c71503682c8693cb5b06a4da4911dfd655ee/examples/wuerstchen/text_to_image/train_text_to_image_prior.py#L192) function. It 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_text_to_image_prior.py \
|
| 72 |
+
--mixed_precision="fp16"
|
| 73 |
+
```
|
| 74 |
+
|
| 75 |
+
Most of the parameters are identical to the parameters in the [Text-to-image](text2image#script-parameters) training guide, so let's dive right into the Wuerstchen training script!
|
| 76 |
+
|
| 77 |
+
## Training script
|
| 78 |
+
|
| 79 |
+
The training script is also similar to the [Text-to-image](text2image#training-script) training guide, but it's been modified to support Wuerstchen. This guide focuses on the code that is unique to the Wuerstchen training script.
|
| 80 |
+
|
| 81 |
+
The [`main()`](https://github.com/huggingface/diffusers/blob/6e68c71503682c8693cb5b06a4da4911dfd655ee/examples/wuerstchen/text_to_image/train_text_to_image_prior.py#L441) function starts by initializing the image encoder - an [EfficientNet](https://github.com/huggingface/diffusers/blob/main/examples/wuerstchen/text_to_image/modeling_efficient_net_encoder.py) - in addition to the usual scheduler and tokenizer.
|
| 82 |
+
|
| 83 |
+
```py
|
| 84 |
+
with ContextManagers(deepspeed_zero_init_disabled_context_manager()):
|
| 85 |
+
pretrained_checkpoint_file = hf_hub_download("dome272/wuerstchen", filename="model_v2_stage_b.pt")
|
| 86 |
+
state_dict = torch.load(pretrained_checkpoint_file, map_location="cpu")
|
| 87 |
+
image_encoder = EfficientNetEncoder()
|
| 88 |
+
image_encoder.load_state_dict(state_dict["effnet_state_dict"])
|
| 89 |
+
image_encoder.eval()
|
| 90 |
+
```
|
| 91 |
+
|
| 92 |
+
You'll also load the [`WuerstchenPrior`] model for optimization.
|
| 93 |
+
|
| 94 |
+
```py
|
| 95 |
+
prior = WuerstchenPrior.from_pretrained(args.pretrained_prior_model_name_or_path, subfolder="prior")
|
| 96 |
+
|
| 97 |
+
optimizer = optimizer_cls(
|
| 98 |
+
prior.parameters(),
|
| 99 |
+
lr=args.learning_rate,
|
| 100 |
+
betas=(args.adam_beta1, args.adam_beta2),
|
| 101 |
+
weight_decay=args.adam_weight_decay,
|
| 102 |
+
eps=args.adam_epsilon,
|
| 103 |
+
)
|
| 104 |
+
```
|
| 105 |
+
|
| 106 |
+
Next, you'll apply some [transforms](https://github.com/huggingface/diffusers/blob/65ef7a0c5c594b4f84092e328fbdd73183613b30/examples/wuerstchen/text_to_image/train_text_to_image_prior.py#L656) to the images and [tokenize](https://github.com/huggingface/diffusers/blob/65ef7a0c5c594b4f84092e328fbdd73183613b30/examples/wuerstchen/text_to_image/train_text_to_image_prior.py#L637) the captions:
|
| 107 |
+
|
| 108 |
+
```py
|
| 109 |
+
def preprocess_train(examples):
|
| 110 |
+
images = [image.convert("RGB") for image in examples[image_column]]
|
| 111 |
+
examples["effnet_pixel_values"] = [effnet_transforms(image) for image in images]
|
| 112 |
+
examples["text_input_ids"], examples["text_mask"] = tokenize_captions(examples)
|
| 113 |
+
return examples
|
| 114 |
+
```
|
| 115 |
+
|
| 116 |
+
Finally, the [training loop](https://github.com/huggingface/diffusers/blob/65ef7a0c5c594b4f84092e328fbdd73183613b30/examples/wuerstchen/text_to_image/train_text_to_image_prior.py#L656) handles compressing the images to latent space with the `EfficientNetEncoder`, adding noise to the latents, and predicting the noise residual with the [`WuerstchenPrior`] model.
|
| 117 |
+
|
| 118 |
+
```py
|
| 119 |
+
pred_noise = prior(noisy_latents, timesteps, prompt_embeds)
|
| 120 |
+
```
|
| 121 |
+
|
| 122 |
+
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.
|
| 123 |
+
|
| 124 |
+
## Launch the script
|
| 125 |
+
|
| 126 |
+
Once you’ve made all your changes or you’re okay with the default configuration, you’re ready to launch the training script! 🚀
|
| 127 |
+
|
| 128 |
+
Set the `DATASET_NAME` environment variable to the dataset name from the Hub. This guide uses the [Naruto BLIP captions](https://huggingface.co/datasets/lambdalabs/naruto-blip-captions) dataset, but you can create and train on your own datasets as well (see the [Create a dataset for training](create_dataset) guide).
|
| 129 |
+
|
| 130 |
+
> [!TIP]
|
| 131 |
+
> To monitor training progress with Weights & Biases, add the `--report_to=wandb` parameter to the training command. You’ll also need to add the `--validation_prompt` to the training command to keep track of results. This can be really useful for debugging the model and viewing intermediate results.
|
| 132 |
+
|
| 133 |
+
```bash
|
| 134 |
+
export DATASET_NAME="lambdalabs/naruto-blip-captions"
|
| 135 |
+
|
| 136 |
+
accelerate launch train_text_to_image_prior.py \
|
| 137 |
+
--mixed_precision="fp16" \
|
| 138 |
+
--dataset_name=$DATASET_NAME \
|
| 139 |
+
--resolution=768 \
|
| 140 |
+
--train_batch_size=4 \
|
| 141 |
+
--gradient_accumulation_steps=4 \
|
| 142 |
+
--gradient_checkpointing \
|
| 143 |
+
--dataloader_num_workers=4 \
|
| 144 |
+
--max_train_steps=15000 \
|
| 145 |
+
--learning_rate=1e-05 \
|
| 146 |
+
--max_grad_norm=1 \
|
| 147 |
+
--checkpoints_total_limit=3 \
|
| 148 |
+
--lr_scheduler="constant" \
|
| 149 |
+
--lr_warmup_steps=0 \
|
| 150 |
+
--validation_prompts="A robot naruto, 4k photo" \
|
| 151 |
+
--report_to="wandb" \
|
| 152 |
+
--push_to_hub \
|
| 153 |
+
--output_dir="wuerstchen-prior-naruto-model"
|
| 154 |
+
```
|
| 155 |
+
|
| 156 |
+
Once training is complete, you can use your newly trained model for inference!
|
| 157 |
+
|
| 158 |
+
```py
|
| 159 |
+
import torch
|
| 160 |
+
from diffusers import AutoPipelineForText2Image
|
| 161 |
+
from diffusers.pipelines.wuerstchen import DEFAULT_STAGE_C_TIMESTEPS
|
| 162 |
+
|
| 163 |
+
pipeline = AutoPipelineForText2Image.from_pretrained("path/to/saved/model", torch_dtype=torch.float16).to("cuda")
|
| 164 |
+
|
| 165 |
+
caption = "A cute bird naruto holding a shield"
|
| 166 |
+
images = pipeline(
|
| 167 |
+
caption,
|
| 168 |
+
width=1024,
|
| 169 |
+
height=1536,
|
| 170 |
+
prior_timesteps=DEFAULT_STAGE_C_TIMESTEPS,
|
| 171 |
+
prior_guidance_scale=4.0,
|
| 172 |
+
num_images_per_prompt=2,
|
| 173 |
+
).images
|
| 174 |
+
```
|
| 175 |
+
|
| 176 |
+
## Next steps
|
| 177 |
+
|
| 178 |
+
Congratulations on training a Wuerstchen model! To learn more about how to use your new model, the following may be helpful:
|
| 179 |
+
|
| 180 |
+
- Take a look at the [Wuerstchen](../api/pipelines/wuerstchen#text-to-image-generation) API documentation to learn more about how to use the pipeline for text-to-image generation and its limitations.
|
tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/tutorials/autopipeline.md
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# AutoPipeline
|
| 14 |
+
|
| 15 |
+
[AutoPipeline](../api/models/auto_model) is a *task-and-model* pipeline that automatically selects the correct pipeline subclass based on the task. It handles the complexity of loading different pipeline subclasses without needing to know the specific pipeline subclass name.
|
| 16 |
+
|
| 17 |
+
This is unlike [`DiffusionPipeline`], a *model-only* pipeline that automatically selects the pipeline subclass based on the model.
|
| 18 |
+
|
| 19 |
+
[`AutoPipelineForImage2Image`] returns a specific pipeline subclass, (for example, [`StableDiffusionXLImg2ImgPipeline`]), which can only be used for image-to-image tasks.
|
| 20 |
+
|
| 21 |
+
```py
|
| 22 |
+
import torch
|
| 23 |
+
from diffusers import AutoPipelineForImage2Image
|
| 24 |
+
|
| 25 |
+
pipeline = AutoPipelineForImage2Image.from_pretrained(
|
| 26 |
+
"RunDiffusion/Juggernaut-XL-v9", torch_dtype=torch.bfloat16, device_map="cuda",
|
| 27 |
+
)
|
| 28 |
+
print(pipeline)
|
| 29 |
+
"StableDiffusionXLImg2ImgPipeline {
|
| 30 |
+
"_class_name": "StableDiffusionXLImg2ImgPipeline",
|
| 31 |
+
...
|
| 32 |
+
"
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
Loading the same model with [`DiffusionPipeline`] returns the [`StableDiffusionXLPipeline`] subclass. It can be used for text-to-image, image-to-image, or inpainting tasks depending on the inputs.
|
| 36 |
+
|
| 37 |
+
```py
|
| 38 |
+
import torch
|
| 39 |
+
from diffusers import DiffusionPipeline
|
| 40 |
+
|
| 41 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
| 42 |
+
"RunDiffusion/Juggernaut-XL-v9", torch_dtype=torch.bfloat16, device_map="cuda",
|
| 43 |
+
)
|
| 44 |
+
print(pipeline)
|
| 45 |
+
"StableDiffusionXLPipeline {
|
| 46 |
+
"_class_name": "StableDiffusionXLPipeline",
|
| 47 |
+
...
|
| 48 |
+
"
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
Check the [mappings](https://github.com/huggingface/diffusers/blob/130fd8df54f24ffb006d84787b598d8adc899f23/src/diffusers/pipelines/auto_pipeline.py#L114) to see whether a model is supported or not.
|
| 52 |
+
|
| 53 |
+
Trying to load an unsupported model returns an error.
|
| 54 |
+
|
| 55 |
+
```py
|
| 56 |
+
import torch
|
| 57 |
+
from diffusers import AutoPipelineForImage2Image
|
| 58 |
+
|
| 59 |
+
pipeline = AutoPipelineForImage2Image.from_pretrained(
|
| 60 |
+
"openai/shap-e-img2img", torch_dtype=torch.float16,
|
| 61 |
+
)
|
| 62 |
+
"ValueError: AutoPipeline can't find a pipeline linked to ShapEImg2ImgPipeline for None"
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
There are three types of [AutoPipeline](../api/models/auto_model) classes, [`AutoPipelineForText2Image`], [`AutoPipelineForImage2Image`] and [`AutoPipelineForInpainting`]. Each of these classes have a predefined mapping, linking a pipeline to their task-specific subclass.
|
| 66 |
+
|
| 67 |
+
When [`~AutoPipelineForText2Image.from_pretrained`] is called, it extracts the class name from the `model_index.json` file and selects the appropriate pipeline subclass for the task based on the mapping.
|
tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/tutorials/basic_training.md
ADDED
|
@@ -0,0 +1,395 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# Train a diffusion model
|
| 16 |
+
|
| 17 |
+
Unconditional image generation is a popular application of diffusion models that generates images that look like those in the dataset used for training. Typically, the best results are obtained from finetuning a pretrained model on a specific dataset. You can find many of these checkpoints on the [Hub](https://huggingface.co/search/full-text?q=unconditional-image-generation&type=model), but if you can't find one you like, you can always train your own!
|
| 18 |
+
|
| 19 |
+
This tutorial will teach you how to train a [`UNet2DModel`] from scratch on a subset of the [Smithsonian Butterflies](https://huggingface.co/datasets/huggan/smithsonian_butterflies_subset) dataset to generate your own 🦋 butterflies 🦋.
|
| 20 |
+
|
| 21 |
+
> [!TIP]
|
| 22 |
+
> 💡 This training tutorial is based on the [Training with 🧨 Diffusers](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/training_example.ipynb) notebook. For additional details and context about diffusion models like how they work, check out the notebook!
|
| 23 |
+
|
| 24 |
+
Before you begin, make sure you have 🤗 Datasets installed to load and preprocess image datasets, and 🤗 Accelerate, to simplify training on any number of GPUs. The following command will also install [TensorBoard](https://www.tensorflow.org/tensorboard) to visualize training metrics (you can also use [Weights & Biases](https://docs.wandb.ai/) to track your training).
|
| 25 |
+
|
| 26 |
+
```py
|
| 27 |
+
# uncomment to install the necessary libraries in Colab
|
| 28 |
+
#!pip install diffusers[training]
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
We encourage you to share your model with the community, and in order to do that, you'll need to login to your Hugging Face account (create one [here](https://hf.co/join) if you don't already have one!). You can login from a notebook and enter your token when prompted. Make sure your token has the write role.
|
| 32 |
+
|
| 33 |
+
```py
|
| 34 |
+
>>> from huggingface_hub import notebook_login
|
| 35 |
+
|
| 36 |
+
>>> notebook_login()
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
Or login in from the terminal:
|
| 40 |
+
|
| 41 |
+
```bash
|
| 42 |
+
hf auth login
|
| 43 |
+
```
|
| 44 |
+
|
| 45 |
+
Since the model checkpoints are quite large, install [Git-LFS](https://git-lfs.com/) to version these large files:
|
| 46 |
+
|
| 47 |
+
```bash
|
| 48 |
+
!sudo apt -qq install git-lfs
|
| 49 |
+
!git config --global credential.helper store
|
| 50 |
+
```
|
| 51 |
+
|
| 52 |
+
## Training configuration
|
| 53 |
+
|
| 54 |
+
For convenience, create a `TrainingConfig` class containing the training hyperparameters (feel free to adjust them):
|
| 55 |
+
|
| 56 |
+
```py
|
| 57 |
+
>>> from dataclasses import dataclass
|
| 58 |
+
|
| 59 |
+
>>> @dataclass
|
| 60 |
+
... class TrainingConfig:
|
| 61 |
+
... image_size = 128 # the generated image resolution
|
| 62 |
+
... train_batch_size = 16
|
| 63 |
+
... eval_batch_size = 16 # how many images to sample during evaluation
|
| 64 |
+
... num_epochs = 50
|
| 65 |
+
... gradient_accumulation_steps = 1
|
| 66 |
+
... learning_rate = 1e-4
|
| 67 |
+
... lr_warmup_steps = 500
|
| 68 |
+
... save_image_epochs = 10
|
| 69 |
+
... save_model_epochs = 30
|
| 70 |
+
... mixed_precision = "fp16" # `no` for float32, `fp16` for automatic mixed precision
|
| 71 |
+
... output_dir = "ddpm-butterflies-128" # the model name locally and on the HF Hub
|
| 72 |
+
|
| 73 |
+
... push_to_hub = True # whether to upload the saved model to the HF Hub
|
| 74 |
+
... hub_model_id = "<your-username>/<my-awesome-model>" # the name of the repository to create on the HF Hub
|
| 75 |
+
... hub_private_repo = None
|
| 76 |
+
... overwrite_output_dir = True # overwrite the old model when re-running the notebook
|
| 77 |
+
... seed = 0
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
>>> config = TrainingConfig()
|
| 81 |
+
```
|
| 82 |
+
|
| 83 |
+
## Load the dataset
|
| 84 |
+
|
| 85 |
+
You can easily load the [Smithsonian Butterflies](https://huggingface.co/datasets/huggan/smithsonian_butterflies_subset) dataset with the 🤗 Datasets library:
|
| 86 |
+
|
| 87 |
+
```py
|
| 88 |
+
>>> from datasets import load_dataset
|
| 89 |
+
|
| 90 |
+
>>> config.dataset_name = "huggan/smithsonian_butterflies_subset"
|
| 91 |
+
>>> dataset = load_dataset(config.dataset_name, split="train")
|
| 92 |
+
```
|
| 93 |
+
|
| 94 |
+
> [!TIP]
|
| 95 |
+
> 💡 You can find additional datasets from the [HugGan Community Event](https://huggingface.co/huggan) or you can use your own dataset by creating a local [`ImageFolder`](https://huggingface.co/docs/datasets/image_dataset#imagefolder). Set `config.dataset_name` to the repository id of the dataset if it is from the HugGan Community Event, or `imagefolder` if you're using your own images.
|
| 96 |
+
|
| 97 |
+
🤗 Datasets uses the [`~datasets.Image`] feature to automatically decode the image data and load it as a [`PIL.Image`](https://pillow.readthedocs.io/en/stable/reference/Image.html) which we can visualize:
|
| 98 |
+
|
| 99 |
+
```py
|
| 100 |
+
>>> import matplotlib.pyplot as plt
|
| 101 |
+
|
| 102 |
+
>>> fig, axs = plt.subplots(1, 4, figsize=(16, 4))
|
| 103 |
+
>>> for i, image in enumerate(dataset[:4]["image"]):
|
| 104 |
+
... axs[i].imshow(image)
|
| 105 |
+
... axs[i].set_axis_off()
|
| 106 |
+
>>> fig.show()
|
| 107 |
+
```
|
| 108 |
+
|
| 109 |
+
<div class="flex justify-center">
|
| 110 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/butterflies_ds.png"/>
|
| 111 |
+
</div>
|
| 112 |
+
|
| 113 |
+
The images are all different sizes though, so you'll need to preprocess them first:
|
| 114 |
+
|
| 115 |
+
* `Resize` changes the image size to the one defined in `config.image_size`.
|
| 116 |
+
* `RandomHorizontalFlip` augments the dataset by randomly mirroring the images.
|
| 117 |
+
* `Normalize` is important to rescale the pixel values into a [-1, 1] range, which is what the model expects.
|
| 118 |
+
|
| 119 |
+
```py
|
| 120 |
+
>>> from torchvision import transforms
|
| 121 |
+
|
| 122 |
+
>>> preprocess = transforms.Compose(
|
| 123 |
+
... [
|
| 124 |
+
... transforms.Resize((config.image_size, config.image_size)),
|
| 125 |
+
... transforms.RandomHorizontalFlip(),
|
| 126 |
+
... transforms.ToTensor(),
|
| 127 |
+
... transforms.Normalize([0.5], [0.5]),
|
| 128 |
+
... ]
|
| 129 |
+
... )
|
| 130 |
+
```
|
| 131 |
+
|
| 132 |
+
Use 🤗 Datasets' [`~datasets.Dataset.set_transform`] method to apply the `preprocess` function on the fly during training:
|
| 133 |
+
|
| 134 |
+
```py
|
| 135 |
+
>>> def transform(examples):
|
| 136 |
+
... images = [preprocess(image.convert("RGB")) for image in examples["image"]]
|
| 137 |
+
... return {"images": images}
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
>>> dataset.set_transform(transform)
|
| 141 |
+
```
|
| 142 |
+
|
| 143 |
+
Feel free to visualize the images again to confirm that they've been resized. Now you're ready to wrap the dataset in a [DataLoader](https://pytorch.org/docs/stable/data#torch.utils.data.DataLoader) for training!
|
| 144 |
+
|
| 145 |
+
```py
|
| 146 |
+
>>> import torch
|
| 147 |
+
|
| 148 |
+
>>> train_dataloader = torch.utils.data.DataLoader(dataset, batch_size=config.train_batch_size, shuffle=True)
|
| 149 |
+
```
|
| 150 |
+
|
| 151 |
+
## Create a UNet2DModel
|
| 152 |
+
|
| 153 |
+
Pretrained models in 🧨 Diffusers are easily created from their model class with the parameters you want. For example, to create a [`UNet2DModel`]:
|
| 154 |
+
|
| 155 |
+
```py
|
| 156 |
+
>>> from diffusers import UNet2DModel
|
| 157 |
+
|
| 158 |
+
>>> model = UNet2DModel(
|
| 159 |
+
... sample_size=config.image_size, # the target image resolution
|
| 160 |
+
... in_channels=3, # the number of input channels, 3 for RGB images
|
| 161 |
+
... out_channels=3, # the number of output channels
|
| 162 |
+
... layers_per_block=2, # how many ResNet layers to use per UNet block
|
| 163 |
+
... block_out_channels=(128, 128, 256, 256, 512, 512), # the number of output channels for each UNet block
|
| 164 |
+
... down_block_types=(
|
| 165 |
+
... "DownBlock2D", # a regular ResNet downsampling block
|
| 166 |
+
... "DownBlock2D",
|
| 167 |
+
... "DownBlock2D",
|
| 168 |
+
... "DownBlock2D",
|
| 169 |
+
... "AttnDownBlock2D", # a ResNet downsampling block with spatial self-attention
|
| 170 |
+
... "DownBlock2D",
|
| 171 |
+
... ),
|
| 172 |
+
... up_block_types=(
|
| 173 |
+
... "UpBlock2D", # a regular ResNet upsampling block
|
| 174 |
+
... "AttnUpBlock2D", # a ResNet upsampling block with spatial self-attention
|
| 175 |
+
... "UpBlock2D",
|
| 176 |
+
... "UpBlock2D",
|
| 177 |
+
... "UpBlock2D",
|
| 178 |
+
... "UpBlock2D",
|
| 179 |
+
... ),
|
| 180 |
+
... )
|
| 181 |
+
```
|
| 182 |
+
|
| 183 |
+
It is often a good idea to quickly check the sample image shape matches the model output shape:
|
| 184 |
+
|
| 185 |
+
```py
|
| 186 |
+
>>> sample_image = dataset[0]["images"].unsqueeze(0)
|
| 187 |
+
>>> print("Input shape:", sample_image.shape)
|
| 188 |
+
Input shape: torch.Size([1, 3, 128, 128])
|
| 189 |
+
|
| 190 |
+
>>> print("Output shape:", model(sample_image, timestep=0).sample.shape)
|
| 191 |
+
Output shape: torch.Size([1, 3, 128, 128])
|
| 192 |
+
```
|
| 193 |
+
|
| 194 |
+
Great! Next, you'll need a scheduler to add some noise to the image.
|
| 195 |
+
|
| 196 |
+
## Create a scheduler
|
| 197 |
+
|
| 198 |
+
The scheduler behaves differently depending on whether you're using the model for training or inference. During inference, the scheduler generates image from the noise. During training, the scheduler takes a model output - or a sample - from a specific point in the diffusion process and applies noise to the image according to a *noise schedule* and an *update rule*.
|
| 199 |
+
|
| 200 |
+
Let's take a look at the [`DDPMScheduler`] and use the `add_noise` method to add some random noise to the `sample_image` from before:
|
| 201 |
+
|
| 202 |
+
```py
|
| 203 |
+
>>> import torch
|
| 204 |
+
>>> from PIL import Image
|
| 205 |
+
>>> from diffusers import DDPMScheduler
|
| 206 |
+
|
| 207 |
+
>>> noise_scheduler = DDPMScheduler(num_train_timesteps=1000)
|
| 208 |
+
>>> noise = torch.randn(sample_image.shape)
|
| 209 |
+
>>> timesteps = torch.LongTensor([50])
|
| 210 |
+
>>> noisy_image = noise_scheduler.add_noise(sample_image, noise, timesteps)
|
| 211 |
+
|
| 212 |
+
>>> Image.fromarray(((noisy_image.permute(0, 2, 3, 1) + 1.0) * 127.5).type(torch.uint8).numpy()[0])
|
| 213 |
+
```
|
| 214 |
+
|
| 215 |
+
<div class="flex justify-center">
|
| 216 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/noisy_butterfly.png"/>
|
| 217 |
+
</div>
|
| 218 |
+
|
| 219 |
+
The training objective of the model is to predict the noise added to the image. The loss at this step can be calculated by:
|
| 220 |
+
|
| 221 |
+
```py
|
| 222 |
+
>>> import torch.nn.functional as F
|
| 223 |
+
|
| 224 |
+
>>> noise_pred = model(noisy_image, timesteps).sample
|
| 225 |
+
>>> loss = F.mse_loss(noise_pred, noise)
|
| 226 |
+
```
|
| 227 |
+
|
| 228 |
+
## Train the model
|
| 229 |
+
|
| 230 |
+
By now, you have most of the pieces to start training the model and all that's left is putting everything together.
|
| 231 |
+
|
| 232 |
+
First, you'll need an optimizer and a learning rate scheduler:
|
| 233 |
+
|
| 234 |
+
```py
|
| 235 |
+
>>> from diffusers.optimization import get_cosine_schedule_with_warmup
|
| 236 |
+
|
| 237 |
+
>>> optimizer = torch.optim.AdamW(model.parameters(), lr=config.learning_rate)
|
| 238 |
+
>>> lr_scheduler = get_cosine_schedule_with_warmup(
|
| 239 |
+
... optimizer=optimizer,
|
| 240 |
+
... num_warmup_steps=config.lr_warmup_steps,
|
| 241 |
+
... num_training_steps=(len(train_dataloader) * config.num_epochs),
|
| 242 |
+
... )
|
| 243 |
+
```
|
| 244 |
+
|
| 245 |
+
Then, you'll need a way to evaluate the model. For evaluation, you can use the [`DDPMPipeline`] to generate a batch of sample images and save it as a grid:
|
| 246 |
+
|
| 247 |
+
```py
|
| 248 |
+
>>> from diffusers import DDPMPipeline
|
| 249 |
+
>>> from diffusers.utils import make_image_grid
|
| 250 |
+
>>> import os
|
| 251 |
+
|
| 252 |
+
>>> def evaluate(config, epoch, pipeline):
|
| 253 |
+
... # Sample some images from random noise (this is the backward diffusion process).
|
| 254 |
+
... # The default pipeline output type is `List[PIL.Image]`
|
| 255 |
+
... images = pipeline(
|
| 256 |
+
... batch_size=config.eval_batch_size,
|
| 257 |
+
... generator=torch.Generator(device='cpu').manual_seed(config.seed), # Use a separate torch generator to avoid rewinding the random state of the main training loop
|
| 258 |
+
... ).images
|
| 259 |
+
|
| 260 |
+
... # Make a grid out of the images
|
| 261 |
+
... image_grid = make_image_grid(images, rows=4, cols=4)
|
| 262 |
+
|
| 263 |
+
... # Save the images
|
| 264 |
+
... test_dir = os.path.join(config.output_dir, "samples")
|
| 265 |
+
... os.makedirs(test_dir, exist_ok=True)
|
| 266 |
+
... image_grid.save(f"{test_dir}/{epoch:04d}.png")
|
| 267 |
+
```
|
| 268 |
+
|
| 269 |
+
Now you can wrap all these components together in a training loop with 🤗 Accelerate for easy TensorBoard logging, gradient accumulation, and mixed precision training. To upload the model to the Hub, write a function to get your repository name and information and then push it to the Hub.
|
| 270 |
+
|
| 271 |
+
> [!TIP]
|
| 272 |
+
> 💡 The training loop below may look intimidating and long, but it'll be worth it later when you launch your training in just one line of code! If you can't wait and want to start generating images, feel free to copy and run the code below. You can always come back and examine the training loop more closely later, like when you're waiting for your model to finish training. 🤗
|
| 273 |
+
|
| 274 |
+
```py
|
| 275 |
+
>>> from accelerate import Accelerator
|
| 276 |
+
>>> from huggingface_hub import create_repo, upload_folder
|
| 277 |
+
>>> from tqdm.auto import tqdm
|
| 278 |
+
>>> from pathlib import Path
|
| 279 |
+
>>> import os
|
| 280 |
+
|
| 281 |
+
>>> def train_loop(config, model, noise_scheduler, optimizer, train_dataloader, lr_scheduler):
|
| 282 |
+
... # Initialize accelerator and tensorboard logging
|
| 283 |
+
... accelerator = Accelerator(
|
| 284 |
+
... mixed_precision=config.mixed_precision,
|
| 285 |
+
... gradient_accumulation_steps=config.gradient_accumulation_steps,
|
| 286 |
+
... log_with="tensorboard",
|
| 287 |
+
... project_dir=os.path.join(config.output_dir, "logs"),
|
| 288 |
+
... )
|
| 289 |
+
... if accelerator.is_main_process:
|
| 290 |
+
... if config.output_dir is not None:
|
| 291 |
+
... os.makedirs(config.output_dir, exist_ok=True)
|
| 292 |
+
... if config.push_to_hub:
|
| 293 |
+
... repo_id = create_repo(
|
| 294 |
+
... repo_id=config.hub_model_id or Path(config.output_dir).name, exist_ok=True
|
| 295 |
+
... ).repo_id
|
| 296 |
+
... accelerator.init_trackers("train_example")
|
| 297 |
+
|
| 298 |
+
... # Prepare everything
|
| 299 |
+
... # There is no specific order to remember, you just need to unpack the
|
| 300 |
+
... # objects in the same order you gave them to the prepare method.
|
| 301 |
+
... model, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
|
| 302 |
+
... model, optimizer, train_dataloader, lr_scheduler
|
| 303 |
+
... )
|
| 304 |
+
|
| 305 |
+
... global_step = 0
|
| 306 |
+
|
| 307 |
+
... # Now you train the model
|
| 308 |
+
... for epoch in range(config.num_epochs):
|
| 309 |
+
... progress_bar = tqdm(total=len(train_dataloader), disable=not accelerator.is_local_main_process)
|
| 310 |
+
... progress_bar.set_description(f"Epoch {epoch}")
|
| 311 |
+
|
| 312 |
+
... for step, batch in enumerate(train_dataloader):
|
| 313 |
+
... clean_images = batch["images"]
|
| 314 |
+
... # Sample noise to add to the images
|
| 315 |
+
... noise = torch.randn(clean_images.shape, device=clean_images.device)
|
| 316 |
+
... bs = clean_images.shape[0]
|
| 317 |
+
|
| 318 |
+
... # Sample a random timestep for each image
|
| 319 |
+
... timesteps = torch.randint(
|
| 320 |
+
... 0, noise_scheduler.config.num_train_timesteps, (bs,), device=clean_images.device,
|
| 321 |
+
... dtype=torch.int64
|
| 322 |
+
... )
|
| 323 |
+
|
| 324 |
+
... # Add noise to the clean images according to the noise magnitude at each timestep
|
| 325 |
+
... # (this is the forward diffusion process)
|
| 326 |
+
... noisy_images = noise_scheduler.add_noise(clean_images, noise, timesteps)
|
| 327 |
+
|
| 328 |
+
... with accelerator.accumulate(model):
|
| 329 |
+
... # Predict the noise residual
|
| 330 |
+
... noise_pred = model(noisy_images, timesteps, return_dict=False)[0]
|
| 331 |
+
... loss = F.mse_loss(noise_pred, noise)
|
| 332 |
+
... accelerator.backward(loss)
|
| 333 |
+
|
| 334 |
+
... if accelerator.sync_gradients:
|
| 335 |
+
... accelerator.clip_grad_norm_(model.parameters(), 1.0)
|
| 336 |
+
... optimizer.step()
|
| 337 |
+
... lr_scheduler.step()
|
| 338 |
+
... optimizer.zero_grad()
|
| 339 |
+
|
| 340 |
+
... progress_bar.update(1)
|
| 341 |
+
... logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0], "step": global_step}
|
| 342 |
+
... progress_bar.set_postfix(**logs)
|
| 343 |
+
... accelerator.log(logs, step=global_step)
|
| 344 |
+
... global_step += 1
|
| 345 |
+
|
| 346 |
+
... # After each epoch you optionally sample some demo images with evaluate() and save the model
|
| 347 |
+
... if accelerator.is_main_process:
|
| 348 |
+
... pipeline = DDPMPipeline(unet=accelerator.unwrap_model(model), scheduler=noise_scheduler)
|
| 349 |
+
|
| 350 |
+
... if (epoch + 1) % config.save_image_epochs == 0 or epoch == config.num_epochs - 1:
|
| 351 |
+
... evaluate(config, epoch, pipeline)
|
| 352 |
+
|
| 353 |
+
... if (epoch + 1) % config.save_model_epochs == 0 or epoch == config.num_epochs - 1:
|
| 354 |
+
... if config.push_to_hub:
|
| 355 |
+
... upload_folder(
|
| 356 |
+
... repo_id=repo_id,
|
| 357 |
+
... folder_path=config.output_dir,
|
| 358 |
+
... commit_message=f"Epoch {epoch}",
|
| 359 |
+
... ignore_patterns=["step_*", "epoch_*"],
|
| 360 |
+
... )
|
| 361 |
+
... else:
|
| 362 |
+
... pipeline.save_pretrained(config.output_dir)
|
| 363 |
+
```
|
| 364 |
+
|
| 365 |
+
Phew, that was quite a bit of code! But you're finally ready to launch the training with 🤗 Accelerate's [`~accelerate.notebook_launcher`] function. Pass the function the training loop, all the training arguments, and the number of processes (you can change this value to the number of GPUs available to you) to use for training:
|
| 366 |
+
|
| 367 |
+
```py
|
| 368 |
+
>>> from accelerate import notebook_launcher
|
| 369 |
+
|
| 370 |
+
>>> args = (config, model, noise_scheduler, optimizer, train_dataloader, lr_scheduler)
|
| 371 |
+
|
| 372 |
+
>>> notebook_launcher(train_loop, args, num_processes=1)
|
| 373 |
+
```
|
| 374 |
+
|
| 375 |
+
Once training is complete, take a look at the final 🦋 images 🦋 generated by your diffusion model!
|
| 376 |
+
|
| 377 |
+
```py
|
| 378 |
+
>>> import glob
|
| 379 |
+
|
| 380 |
+
>>> sample_images = sorted(glob.glob(f"{config.output_dir}/samples/*.png"))
|
| 381 |
+
>>> Image.open(sample_images[-1])
|
| 382 |
+
```
|
| 383 |
+
|
| 384 |
+
<div class="flex justify-center">
|
| 385 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/butterflies_final.png"/>
|
| 386 |
+
</div>
|
| 387 |
+
|
| 388 |
+
## Next steps
|
| 389 |
+
|
| 390 |
+
Unconditional image generation is one example of a task that can be trained. You can explore other tasks and training techniques by visiting the [🧨 Diffusers Training Examples](../training/overview) page. Here are some examples of what you can learn:
|
| 391 |
+
|
| 392 |
+
* [Textual Inversion](../training/text_inversion), an algorithm that teaches a model a specific visual concept and integrates it into the generated image.
|
| 393 |
+
* [DreamBooth](../training/dreambooth), a technique for generating personalized images of a subject given several input images of the subject.
|
| 394 |
+
* [Guide](../training/text2image) to finetuning a Stable Diffusion model on your own dataset.
|
| 395 |
+
* [Guide](../training/lora) to using LoRA, a memory-efficient technique for finetuning really large models faster.
|
tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/tutorials/using_peft_for_inference.md
ADDED
|
@@ -0,0 +1,691 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# LoRA
|
| 14 |
+
|
| 15 |
+
[LoRA (Low-Rank Adaptation)](https://huggingface.co/papers/2106.09685) is a method for quickly training a model for a new task. It works by freezing the original model weights and adding a small number of *new* trainable parameters. This means it is significantly faster and cheaper to adapt an existing model to new tasks, such as generating images in a new style.
|
| 16 |
+
|
| 17 |
+
LoRA checkpoints are typically only a couple hundred MBs in size, so they're very lightweight and easy to store. Load these smaller set of weights into an existing base model with [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] and specify the file name.
|
| 18 |
+
|
| 19 |
+
<hfoptions id="usage">
|
| 20 |
+
<hfoption id="text-to-image">
|
| 21 |
+
|
| 22 |
+
```py
|
| 23 |
+
import torch
|
| 24 |
+
from diffusers import AutoPipelineForText2Image
|
| 25 |
+
|
| 26 |
+
pipeline = AutoPipelineForText2Image.from_pretrained(
|
| 27 |
+
"stabilityai/stable-diffusion-xl-base-1.0",
|
| 28 |
+
torch_dtype=torch.float16
|
| 29 |
+
).to("cuda")
|
| 30 |
+
pipeline.load_lora_weights(
|
| 31 |
+
"ostris/super-cereal-sdxl-lora",
|
| 32 |
+
weight_name="cereal_box_sdxl_v1.safetensors",
|
| 33 |
+
adapter_name="cereal"
|
| 34 |
+
)
|
| 35 |
+
pipeline("bears, pizza bites").images[0]
|
| 36 |
+
```
|
| 37 |
+
|
| 38 |
+
</hfoption>
|
| 39 |
+
<hfoption id="text-to-video">
|
| 40 |
+
|
| 41 |
+
```py
|
| 42 |
+
import torch
|
| 43 |
+
from diffusers import LTXConditionPipeline
|
| 44 |
+
from diffusers.utils import export_to_video, load_image
|
| 45 |
+
|
| 46 |
+
pipeline = LTXConditionPipeline.from_pretrained(
|
| 47 |
+
"Lightricks/LTX-Video-0.9.5", torch_dtype=torch.bfloat16
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
pipeline.load_lora_weights(
|
| 51 |
+
"Lightricks/LTX-Video-Cakeify-LoRA",
|
| 52 |
+
weight_name="ltxv_095_cakeify_lora.safetensors",
|
| 53 |
+
adapter_name="cakeify"
|
| 54 |
+
)
|
| 55 |
+
pipeline.set_adapters("cakeify")
|
| 56 |
+
|
| 57 |
+
# use "CAKEIFY" to trigger the LoRA
|
| 58 |
+
prompt = "CAKEIFY a person using a knife to cut a cake shaped like a Pikachu plushie"
|
| 59 |
+
image = load_image("https://huggingface.co/Lightricks/LTX-Video-Cakeify-LoRA/resolve/main/assets/images/pikachu.png")
|
| 60 |
+
|
| 61 |
+
video = pipeline(
|
| 62 |
+
prompt=prompt,
|
| 63 |
+
image=image,
|
| 64 |
+
width=576,
|
| 65 |
+
height=576,
|
| 66 |
+
num_frames=161,
|
| 67 |
+
decode_timestep=0.03,
|
| 68 |
+
decode_noise_scale=0.025,
|
| 69 |
+
num_inference_steps=50,
|
| 70 |
+
).frames[0]
|
| 71 |
+
export_to_video(video, "output.mp4", fps=26)
|
| 72 |
+
```
|
| 73 |
+
|
| 74 |
+
</hfoption>
|
| 75 |
+
</hfoptions>
|
| 76 |
+
|
| 77 |
+
The [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] method is the preferred way to load LoRA weights into the UNet and text encoder because it can handle cases where:
|
| 78 |
+
|
| 79 |
+
- the LoRA weights don't have separate UNet and text encoder identifiers
|
| 80 |
+
- the LoRA weights have separate UNet and text encoder identifiers
|
| 81 |
+
|
| 82 |
+
The [`~loaders.PeftAdapterMixin.load_lora_adapter`] method is used to directly load a LoRA adapter at the *model-level*, as long as the model is a Diffusers model that is a subclass of [`PeftAdapterMixin`]. It builds and prepares the necessary model configuration for the adapter. This method also loads the LoRA adapter into the UNet.
|
| 83 |
+
|
| 84 |
+
For example, if you're only loading a LoRA into the UNet, [`~loaders.PeftAdapterMixin.load_lora_adapter`] ignores the text encoder keys. Use the `prefix` parameter to filter and load the appropriate state dicts, `"unet"` to load.
|
| 85 |
+
|
| 86 |
+
```py
|
| 87 |
+
import torch
|
| 88 |
+
from diffusers import AutoPipelineForText2Image
|
| 89 |
+
|
| 90 |
+
pipeline = AutoPipelineForText2Image.from_pretrained(
|
| 91 |
+
"stabilityai/stable-diffusion-xl-base-1.0",
|
| 92 |
+
torch_dtype=torch.float16
|
| 93 |
+
).to("cuda")
|
| 94 |
+
pipeline.unet.load_lora_adapter(
|
| 95 |
+
"jbilcke-hf/sdxl-cinematic-1",
|
| 96 |
+
weight_name="pytorch_lora_weights.safetensors",
|
| 97 |
+
adapter_name="cinematic",
|
| 98 |
+
prefix="unet"
|
| 99 |
+
)
|
| 100 |
+
# use cnmt in the prompt to trigger the LoRA
|
| 101 |
+
pipeline("A cute cnmt eating a slice of pizza, stunning color scheme, masterpiece, illustration").images[0]
|
| 102 |
+
```
|
| 103 |
+
|
| 104 |
+
## torch.compile
|
| 105 |
+
|
| 106 |
+
[torch.compile](../optimization/fp16#torchcompile) speeds up inference by compiling the PyTorch model to use optimized kernels. Before compiling, the LoRA weights need to be fused into the base model and unloaded first.
|
| 107 |
+
|
| 108 |
+
```py
|
| 109 |
+
import torch
|
| 110 |
+
from diffusers import DiffusionPipeline
|
| 111 |
+
|
| 112 |
+
# load base model and LoRA
|
| 113 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
| 114 |
+
"stabilityai/stable-diffusion-xl-base-1.0",
|
| 115 |
+
torch_dtype=torch.float16
|
| 116 |
+
).to("cuda")
|
| 117 |
+
pipeline.load_lora_weights(
|
| 118 |
+
"ostris/ikea-instructions-lora-sdxl",
|
| 119 |
+
weight_name="ikea_instructions_xl_v1_5.safetensors",
|
| 120 |
+
adapter_name="ikea"
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
# activate LoRA and set adapter weight
|
| 124 |
+
pipeline.set_adapters("ikea", adapter_weights=0.7)
|
| 125 |
+
|
| 126 |
+
# fuse LoRAs and unload weights
|
| 127 |
+
pipeline.fuse_lora(adapter_names=["ikea"], lora_scale=1.0)
|
| 128 |
+
pipeline.unload_lora_weights()
|
| 129 |
+
```
|
| 130 |
+
|
| 131 |
+
Typically, the UNet is compiled because its the most compute intensive component of the pipeline.
|
| 132 |
+
|
| 133 |
+
```py
|
| 134 |
+
pipeline.unet.to(memory_format=torch.channels_last)
|
| 135 |
+
pipeline.unet = torch.compile(pipeline.unet, mode="reduce-overhead", fullgraph=True)
|
| 136 |
+
|
| 137 |
+
pipeline("A bowl of ramen shaped like a cute kawaii bear").images[0]
|
| 138 |
+
```
|
| 139 |
+
|
| 140 |
+
Refer to the [hotswapping](#hotswapping) section to learn how to avoid recompilation when working with compiled models and multiple LoRAs.
|
| 141 |
+
|
| 142 |
+
## Weight scale
|
| 143 |
+
|
| 144 |
+
The `scale` parameter is used to control how much of a LoRA to apply. A value of `0` is equivalent to only using the base model weights and a value of `1` is equivalent to fully using the LoRA.
|
| 145 |
+
|
| 146 |
+
<hfoptions id="weight-scale">
|
| 147 |
+
<hfoption id="simple use case">
|
| 148 |
+
|
| 149 |
+
For simple use cases, you can pass `cross_attention_kwargs={"scale": 1.0}` to the pipeline.
|
| 150 |
+
|
| 151 |
+
```py
|
| 152 |
+
import torch
|
| 153 |
+
from diffusers import AutoPipelineForText2Image
|
| 154 |
+
|
| 155 |
+
pipeline = AutoPipelineForText2Image.from_pretrained(
|
| 156 |
+
"stabilityai/stable-diffusion-xl-base-1.0",
|
| 157 |
+
torch_dtype=torch.float16
|
| 158 |
+
).to("cuda")
|
| 159 |
+
pipeline.load_lora_weights(
|
| 160 |
+
"ostris/super-cereal-sdxl-lora",
|
| 161 |
+
weight_name="cereal_box_sdxl_v1.safetensors",
|
| 162 |
+
adapter_name="cereal"
|
| 163 |
+
)
|
| 164 |
+
pipeline("bears, pizza bites", cross_attention_kwargs={"scale": 1.0}).images[0]
|
| 165 |
+
```
|
| 166 |
+
|
| 167 |
+
</hfoption>
|
| 168 |
+
<hfoption id="finer control">
|
| 169 |
+
|
| 170 |
+
> [!WARNING]
|
| 171 |
+
> The [`~loaders.PeftAdapterMixin.set_adapters`] method only scales attention weights. If a LoRA has ResNets or down and upsamplers, these components keep a scale value of `1.0`.
|
| 172 |
+
|
| 173 |
+
For finer control over each individual component of the UNet or text encoder, pass a dictionary instead. In the example below, the `"down"` block in the UNet is scaled by 0.9 and you can further specify in the `"up"` block the scales of the transformers in `"block_0"` and `"block_1"`. If a block like `"mid"` isn't specified, the default value `1.0` is used.
|
| 174 |
+
|
| 175 |
+
```py
|
| 176 |
+
import torch
|
| 177 |
+
from diffusers import AutoPipelineForText2Image
|
| 178 |
+
|
| 179 |
+
pipeline = AutoPipelineForText2Image.from_pretrained(
|
| 180 |
+
"stabilityai/stable-diffusion-xl-base-1.0",
|
| 181 |
+
torch_dtype=torch.float16
|
| 182 |
+
).to("cuda")
|
| 183 |
+
pipeline.load_lora_weights(
|
| 184 |
+
"ostris/super-cereal-sdxl-lora",
|
| 185 |
+
weight_name="cereal_box_sdxl_v1.safetensors",
|
| 186 |
+
adapter_name="cereal"
|
| 187 |
+
)
|
| 188 |
+
scales = {
|
| 189 |
+
"text_encoder": 0.5,
|
| 190 |
+
"text_encoder_2": 0.5,
|
| 191 |
+
"unet": {
|
| 192 |
+
"down": 0.9,
|
| 193 |
+
"up": {
|
| 194 |
+
"block_0": 0.6,
|
| 195 |
+
"block_1": [0.4, 0.8, 1.0],
|
| 196 |
+
}
|
| 197 |
+
}
|
| 198 |
+
}
|
| 199 |
+
pipeline.set_adapters("cereal", scales)
|
| 200 |
+
pipeline("bears, pizza bites").images[0]
|
| 201 |
+
```
|
| 202 |
+
|
| 203 |
+
</hfoption>
|
| 204 |
+
</hfoptions>
|
| 205 |
+
|
| 206 |
+
### Scale scheduling
|
| 207 |
+
|
| 208 |
+
Dynamically adjusting the LoRA scale during sampling gives you better control over the overall composition and layout because certain steps may benefit more from an increased or reduced scale.
|
| 209 |
+
|
| 210 |
+
The [character LoRA](https://huggingface.co/alvarobartt/ghibli-characters-flux-lora) in the example below starts with a higher scale that gradually decays over the first 20 steps to establish the character generation. In the later steps, only a scale of 0.2 is applied to avoid adding too much of the LoRA features to other parts of the image the LoRA wasn't trained on.
|
| 211 |
+
|
| 212 |
+
```py
|
| 213 |
+
import torch
|
| 214 |
+
from diffusers import FluxPipeline
|
| 215 |
+
|
| 216 |
+
pipeline = FluxPipeline.from_pretrained(
|
| 217 |
+
"black-forest-labs/FLUX.1-dev", torch_dtype=torch.bfloat16
|
| 218 |
+
).to("cuda")
|
| 219 |
+
|
| 220 |
+
pipelne.load_lora_weights("alvarobartt/ghibli-characters-flux-lora", "lora")
|
| 221 |
+
|
| 222 |
+
num_inference_steps = 30
|
| 223 |
+
lora_steps = 20
|
| 224 |
+
lora_scales = torch.linspace(1.5, 0.7, lora_steps).tolist()
|
| 225 |
+
lora_scales += [0.2] * (num_inference_steps - lora_steps + 1)
|
| 226 |
+
|
| 227 |
+
pipeline.set_adapters("lora", lora_scales[0])
|
| 228 |
+
|
| 229 |
+
def callback(pipeline: FluxPipeline, step: int, timestep: torch.LongTensor, callback_kwargs: dict):
|
| 230 |
+
pipeline.set_adapters("lora", lora_scales[step + 1])
|
| 231 |
+
return callback_kwargs
|
| 232 |
+
|
| 233 |
+
prompt = """
|
| 234 |
+
Ghibli style The Grinch, a mischievous green creature with a sly grin, peeking out from behind a snow-covered tree while plotting his antics,
|
| 235 |
+
in a quaint snowy village decorated for the holidays, warm light glowing from cozy homes, with playful snowflakes dancing in the air
|
| 236 |
+
"""
|
| 237 |
+
pipeline(
|
| 238 |
+
prompt=prompt,
|
| 239 |
+
guidance_scale=3.0,
|
| 240 |
+
num_inference_steps=num_inference_steps,
|
| 241 |
+
generator=torch.Generator().manual_seed(42),
|
| 242 |
+
callback_on_step_end=callback,
|
| 243 |
+
).images[0]
|
| 244 |
+
```
|
| 245 |
+
|
| 246 |
+
## Hotswapping
|
| 247 |
+
|
| 248 |
+
Hotswapping LoRAs is an efficient way to work with multiple LoRAs while avoiding accumulating memory from multiple calls to [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] and in some cases, recompilation, if a model is compiled. This workflow requires a loaded LoRA because the new LoRA weights are swapped in place for the existing loaded LoRA.
|
| 249 |
+
|
| 250 |
+
```py
|
| 251 |
+
import torch
|
| 252 |
+
from diffusers import DiffusionPipeline
|
| 253 |
+
|
| 254 |
+
# load base model and LoRAs
|
| 255 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
| 256 |
+
"stabilityai/stable-diffusion-xl-base-1.0",
|
| 257 |
+
torch_dtype=torch.float16
|
| 258 |
+
).to("cuda")
|
| 259 |
+
pipeline.load_lora_weights(
|
| 260 |
+
"ostris/ikea-instructions-lora-sdxl",
|
| 261 |
+
weight_name="ikea_instructions_xl_v1_5.safetensors",
|
| 262 |
+
adapter_name="ikea"
|
| 263 |
+
)
|
| 264 |
+
```
|
| 265 |
+
|
| 266 |
+
> [!WARNING]
|
| 267 |
+
> Hotswapping is unsupported for LoRAs that target the text encoder.
|
| 268 |
+
|
| 269 |
+
Set `hotswap=True` in [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] to swap the second LoRA. Use the `adapter_name` parameter to indicate which LoRA to swap (`default_0` is the default name).
|
| 270 |
+
|
| 271 |
+
```py
|
| 272 |
+
pipeline.load_lora_weights(
|
| 273 |
+
"lordjia/by-feng-zikai",
|
| 274 |
+
hotswap=True,
|
| 275 |
+
adapter_name="ikea"
|
| 276 |
+
)
|
| 277 |
+
```
|
| 278 |
+
|
| 279 |
+
### Compiled models
|
| 280 |
+
|
| 281 |
+
For compiled models, use [`~loaders.lora_base.LoraBaseMixin.enable_lora_hotswap`] to avoid recompilation when hotswapping LoRAs. This method should be called *before* loading the first LoRA and `torch.compile` should be called *after* loading the first LoRA.
|
| 282 |
+
|
| 283 |
+
> [!TIP]
|
| 284 |
+
> The [`~loaders.lora_base.LoraBaseMixin.enable_lora_hotswap`] method isn't always necessary if the second LoRA targets the identical LoRA ranks and scales as the first LoRA.
|
| 285 |
+
|
| 286 |
+
Within [`~loaders.lora_base.LoraBaseMixin.enable_lora_hotswap`], the `target_rank` parameter is important for setting the rank for all LoRA adapters. Setting it to `max_rank` sets it to the highest value. For LoRAs with different ranks, you set it to a higher rank value. The default rank value is 128.
|
| 287 |
+
|
| 288 |
+
```py
|
| 289 |
+
import torch
|
| 290 |
+
from diffusers import DiffusionPipeline
|
| 291 |
+
|
| 292 |
+
# load base model and LoRAs
|
| 293 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
| 294 |
+
"stabilityai/stable-diffusion-xl-base-1.0",
|
| 295 |
+
torch_dtype=torch.float16
|
| 296 |
+
).to("cuda")
|
| 297 |
+
# 1. enable_lora_hotswap
|
| 298 |
+
pipeline.enable_lora_hotswap(target_rank=max_rank)
|
| 299 |
+
pipeline.load_lora_weights(
|
| 300 |
+
"ostris/ikea-instructions-lora-sdxl",
|
| 301 |
+
weight_name="ikea_instructions_xl_v1_5.safetensors",
|
| 302 |
+
adapter_name="ikea"
|
| 303 |
+
)
|
| 304 |
+
# 2. torch.compile
|
| 305 |
+
pipeline.unet = torch.compile(pipeline.unet, mode="reduce-overhead", fullgraph=True)
|
| 306 |
+
|
| 307 |
+
# 3. hotswap
|
| 308 |
+
pipeline.load_lora_weights(
|
| 309 |
+
"lordjia/by-feng-zikai",
|
| 310 |
+
hotswap=True,
|
| 311 |
+
adapter_name="ikea"
|
| 312 |
+
)
|
| 313 |
+
```
|
| 314 |
+
|
| 315 |
+
> [!TIP]
|
| 316 |
+
> Move your code inside the `with torch._dynamo.config.patch(error_on_recompile=True)` context manager to detect if a model was recompiled. If a model is recompiled despite following all the steps above, please open an [issue](https://github.com/huggingface/diffusers/issues) with a reproducible example.
|
| 317 |
+
|
| 318 |
+
If you expect to varied resolutions during inference with this feature, then make sure set `dynamic=True` during compilation. Refer to [this document](../optimization/fp16#dynamic-shape-compilation) for more details.
|
| 319 |
+
|
| 320 |
+
There are still scenarios where recompulation is unavoidable, such as when the hotswapped LoRA targets more layers than the initial adapter. Try to load the LoRA that targets the most layers *first*. For more details about this limitation, refer to the PEFT [hotswapping](https://huggingface.co/docs/peft/main/en/package_reference/hotswap#peft.utils.hotswap.hotswap_adapter) docs.
|
| 321 |
+
|
| 322 |
+
<details>
|
| 323 |
+
<summary>Technical details of hotswapping</summary>
|
| 324 |
+
|
| 325 |
+
The [`~loaders.lora_base.LoraBaseMixin.enable_lora_hotswap`] method converts the LoRA scaling factor from floats to torch.tensors and pads the shape of the weights to the largest required shape to avoid reassigning the whole attribute when the data in the weights are replaced.
|
| 326 |
+
|
| 327 |
+
This is why the `max_rank` argument is important. The results are unchanged even when the values are padded with zeros. Computation may be slower though depending on the padding size.
|
| 328 |
+
|
| 329 |
+
Since no new LoRA attributes are added, each subsequent LoRA is only allowed to target the same layers, or subset of layers, the first LoRA targets. Choosing the LoRA loading order is important because if the LoRAs target disjoint layers, you may end up creating a dummy LoRA that targets the union of all target layers.
|
| 330 |
+
|
| 331 |
+
For more implementation details, take a look at the [`hotswap.py`](https://github.com/huggingface/peft/blob/92d65cafa51c829484ad3d95cf71d09de57ff066/src/peft/utils/hotswap.py) file.
|
| 332 |
+
|
| 333 |
+
</details>
|
| 334 |
+
|
| 335 |
+
## Merge
|
| 336 |
+
|
| 337 |
+
The weights from each LoRA can be merged together to produce a blend of multiple existing styles. There are several methods for merging LoRAs, each of which differ in *how* the weights are merged (may affect generation quality).
|
| 338 |
+
|
| 339 |
+
### set_adapters
|
| 340 |
+
|
| 341 |
+
The [`~loaders.PeftAdapterMixin.set_adapters`] method merges LoRAs by concatenating their weighted matrices. Pass the LoRA names to [`~loaders.PeftAdapterMixin.set_adapters`] and use the `adapter_weights` parameter to control the scaling of each LoRA. For example, if `adapter_weights=[0.5, 0.5]`, the output is an average of both LoRAs.
|
| 342 |
+
|
| 343 |
+
> [!TIP]
|
| 344 |
+
> The `"scale"` parameter determines how much of the merged LoRA to apply. See the [Weight scale](#weight-scale) section for more details.
|
| 345 |
+
|
| 346 |
+
```py
|
| 347 |
+
import torch
|
| 348 |
+
from diffusers import DiffusionPipeline
|
| 349 |
+
|
| 350 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
| 351 |
+
"stabilityai/stable-diffusion-xl-base-1.0",
|
| 352 |
+
torch_dtype=torch.float16
|
| 353 |
+
).to("cuda")
|
| 354 |
+
pipeline.load_lora_weights(
|
| 355 |
+
"ostris/ikea-instructions-lora-sdxl",
|
| 356 |
+
weight_name="ikea_instructions_xl_v1_5.safetensors",
|
| 357 |
+
adapter_name="ikea"
|
| 358 |
+
)
|
| 359 |
+
pipeline.load_lora_weights(
|
| 360 |
+
"lordjia/by-feng-zikai",
|
| 361 |
+
weight_name="fengzikai_v1.0_XL.safetensors",
|
| 362 |
+
adapter_name="feng"
|
| 363 |
+
)
|
| 364 |
+
pipeline.set_adapters(["ikea", "feng"], adapter_weights=[0.7, 0.8])
|
| 365 |
+
# use by Feng Zikai to activate the lordjia/by-feng-zikai LoRA
|
| 366 |
+
pipeline("A bowl of ramen shaped like a cute kawaii bear, by Feng Zikai", cross_attention_kwargs={"scale": 1.0}).images[0]
|
| 367 |
+
```
|
| 368 |
+
|
| 369 |
+
<div class="flex justify-center">
|
| 370 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/lora_merge_set_adapters.png"/>
|
| 371 |
+
</div>
|
| 372 |
+
|
| 373 |
+
### add_weighted_adapter
|
| 374 |
+
|
| 375 |
+
> [!TIP]
|
| 376 |
+
> This is an experimental method and you can refer to PEFTs [Model merging](https://huggingface.co/docs/peft/developer_guides/model_merging) for more details. Take a look at this [issue](https://github.com/huggingface/diffusers/issues/6892) if you're interested in the motivation and design behind this integration.
|
| 377 |
+
|
| 378 |
+
The [`~peft.LoraModel.add_weighted_adapter`] method enables more efficient merging methods like [TIES](https://huggingface.co/papers/2306.01708) or [DARE](https://huggingface.co/papers/2311.03099). These merging methods remove redundant and potentially interfering parameters from merged models. Keep in mind the LoRA ranks need to have identical ranks to be merged.
|
| 379 |
+
|
| 380 |
+
Make sure the latest stable version of Diffusers and PEFT is installed.
|
| 381 |
+
|
| 382 |
+
```bash
|
| 383 |
+
pip install -U -q diffusers peft
|
| 384 |
+
```
|
| 385 |
+
|
| 386 |
+
Load a UNET that corresponds to the LoRA UNet.
|
| 387 |
+
|
| 388 |
+
```py
|
| 389 |
+
import copy
|
| 390 |
+
import torch
|
| 391 |
+
from diffusers import AutoModel, DiffusionPipeline
|
| 392 |
+
from peft import get_peft_model, LoraConfig, PeftModel
|
| 393 |
+
|
| 394 |
+
unet = AutoModel.from_pretrained(
|
| 395 |
+
"stabilityai/stable-diffusion-xl-base-1.0",
|
| 396 |
+
torch_dtype=torch.float16,
|
| 397 |
+
use_safetensors=True,
|
| 398 |
+
variant="fp16",
|
| 399 |
+
subfolder="unet",
|
| 400 |
+
).to("cuda")
|
| 401 |
+
```
|
| 402 |
+
|
| 403 |
+
Load a pipeline, pass the UNet to it, and load a LoRA.
|
| 404 |
+
|
| 405 |
+
```py
|
| 406 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
| 407 |
+
"stabilityai/stable-diffusion-xl-base-1.0",
|
| 408 |
+
variant="fp16",
|
| 409 |
+
torch_dtype=torch.float16,
|
| 410 |
+
unet=unet
|
| 411 |
+
).to("cuda")
|
| 412 |
+
pipeline.load_lora_weights(
|
| 413 |
+
"ostris/ikea-instructions-lora-sdxl",
|
| 414 |
+
weight_name="ikea_instructions_xl_v1_5.safetensors",
|
| 415 |
+
adapter_name="ikea"
|
| 416 |
+
)
|
| 417 |
+
```
|
| 418 |
+
|
| 419 |
+
Create a [`~peft.PeftModel`] from the LoRA checkpoint by combining the first UNet you loaded and the LoRA UNet from the pipeline.
|
| 420 |
+
|
| 421 |
+
```py
|
| 422 |
+
sdxl_unet = copy.deepcopy(unet)
|
| 423 |
+
ikea_peft_model = get_peft_model(
|
| 424 |
+
sdxl_unet,
|
| 425 |
+
pipeline.unet.peft_config["ikea"],
|
| 426 |
+
adapter_name="ikea"
|
| 427 |
+
)
|
| 428 |
+
|
| 429 |
+
original_state_dict = {f"base_model.model.{k}": v for k, v in pipeline.unet.state_dict().items()}
|
| 430 |
+
ikea_peft_model.load_state_dict(original_state_dict, strict=True)
|
| 431 |
+
```
|
| 432 |
+
|
| 433 |
+
> [!TIP]
|
| 434 |
+
> You can save and reuse the `ikea_peft_model` by pushing it to the Hub as shown below.
|
| 435 |
+
> ```py
|
| 436 |
+
> ikea_peft_model.push_to_hub("ikea_peft_model", token=TOKEN)
|
| 437 |
+
> ```
|
| 438 |
+
|
| 439 |
+
Repeat this process and create a [`~peft.PeftModel`] for the second LoRA.
|
| 440 |
+
|
| 441 |
+
```py
|
| 442 |
+
pipeline.delete_adapters("ikea")
|
| 443 |
+
sdxl_unet.delete_adapters("ikea")
|
| 444 |
+
|
| 445 |
+
pipeline.load_lora_weights(
|
| 446 |
+
"lordjia/by-feng-zikai",
|
| 447 |
+
weight_name="fengzikai_v1.0_XL.safetensors",
|
| 448 |
+
adapter_name="feng"
|
| 449 |
+
)
|
| 450 |
+
pipeline.set_adapters(adapter_names="feng")
|
| 451 |
+
|
| 452 |
+
feng_peft_model = get_peft_model(
|
| 453 |
+
sdxl_unet,
|
| 454 |
+
pipeline.unet.peft_config["feng"],
|
| 455 |
+
adapter_name="feng"
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
original_state_dict = {f"base_model.model.{k}": v for k, v in pipe.unet.state_dict().items()}
|
| 459 |
+
feng_peft_model.load_state_dict(original_state_dict, strict=True)
|
| 460 |
+
```
|
| 461 |
+
|
| 462 |
+
Load a base UNet model and load the adapters.
|
| 463 |
+
|
| 464 |
+
```py
|
| 465 |
+
base_unet = AutoModel.from_pretrained(
|
| 466 |
+
"stabilityai/stable-diffusion-xl-base-1.0",
|
| 467 |
+
torch_dtype=torch.float16,
|
| 468 |
+
use_safetensors=True,
|
| 469 |
+
variant="fp16",
|
| 470 |
+
subfolder="unet",
|
| 471 |
+
).to("cuda")
|
| 472 |
+
|
| 473 |
+
model = PeftModel.from_pretrained(
|
| 474 |
+
base_unet,
|
| 475 |
+
"stevhliu/ikea_peft_model",
|
| 476 |
+
use_safetensors=True,
|
| 477 |
+
subfolder="ikea",
|
| 478 |
+
adapter_name="ikea"
|
| 479 |
+
)
|
| 480 |
+
model.load_adapter(
|
| 481 |
+
"stevhliu/feng_peft_model",
|
| 482 |
+
use_safetensors=True,
|
| 483 |
+
subfolder="feng",
|
| 484 |
+
adapter_name="feng"
|
| 485 |
+
)
|
| 486 |
+
```
|
| 487 |
+
|
| 488 |
+
Merge the LoRAs with [`~peft.LoraModel.add_weighted_adapter`] and specify how you want to merge them with `combination_type`. The example below uses the `"dare_linear"` method (refer to this [blog post](https://huggingface.co/blog/peft_merging) to learn more about these merging methods), which randomly prunes some weights and then performs a weighted sum of the tensors based on the set weightage of each LoRA in `weights`.
|
| 489 |
+
|
| 490 |
+
Activate the merged LoRAs with [`~loaders.PeftAdapterMixin.set_adapters`].
|
| 491 |
+
|
| 492 |
+
```py
|
| 493 |
+
model.add_weighted_adapter(
|
| 494 |
+
adapters=["ikea", "feng"],
|
| 495 |
+
combination_type="dare_linear",
|
| 496 |
+
weights=[1.0, 1.0],
|
| 497 |
+
adapter_name="ikea-feng"
|
| 498 |
+
)
|
| 499 |
+
model.set_adapters("ikea-feng")
|
| 500 |
+
|
| 501 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
| 502 |
+
"stabilityai/stable-diffusion-xl-base-1.0",
|
| 503 |
+
unet=model,
|
| 504 |
+
variant="fp16",
|
| 505 |
+
torch_dtype=torch.float16,
|
| 506 |
+
).to("cuda")
|
| 507 |
+
pipeline("A bowl of ramen shaped like a cute kawaii bear, by Feng Zikai").images[0]
|
| 508 |
+
```
|
| 509 |
+
|
| 510 |
+
<div class="flex justify-center">
|
| 511 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ikea-feng-dare-linear.png"/>
|
| 512 |
+
</div>
|
| 513 |
+
|
| 514 |
+
### fuse_lora
|
| 515 |
+
|
| 516 |
+
The [`~loaders.lora_base.LoraBaseMixin.fuse_lora`] method fuses the LoRA weights directly with the original UNet and text encoder weights of the underlying model. This reduces the overhead of loading the underlying model for each LoRA because it only loads the model once, which lowers memory usage and increases inference speed.
|
| 517 |
+
|
| 518 |
+
```py
|
| 519 |
+
import torch
|
| 520 |
+
from diffusers import DiffusionPipeline
|
| 521 |
+
|
| 522 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
| 523 |
+
"stabilityai/stable-diffusion-xl-base-1.0",
|
| 524 |
+
torch_dtype=torch.float16
|
| 525 |
+
).to("cuda")
|
| 526 |
+
pipeline.load_lora_weights(
|
| 527 |
+
"ostris/ikea-instructions-lora-sdxl",
|
| 528 |
+
weight_name="ikea_instructions_xl_v1_5.safetensors",
|
| 529 |
+
adapter_name="ikea"
|
| 530 |
+
)
|
| 531 |
+
pipeline.load_lora_weights(
|
| 532 |
+
"lordjia/by-feng-zikai",
|
| 533 |
+
weight_name="fengzikai_v1.0_XL.safetensors",
|
| 534 |
+
adapter_name="feng"
|
| 535 |
+
)
|
| 536 |
+
pipeline.set_adapters(["ikea", "feng"], adapter_weights=[0.7, 0.8])
|
| 537 |
+
```
|
| 538 |
+
|
| 539 |
+
Call [`~loaders.lora_base.LoraBaseMixin.fuse_lora`] to fuse them. The `lora_scale` parameter controls how much to scale the output by with the LoRA weights. It is important to make this adjustment now because passing `scale` to `cross_attention_kwargs` won't work in the pipeline.
|
| 540 |
+
|
| 541 |
+
```py
|
| 542 |
+
pipeline.fuse_lora(adapter_names=["ikea", "feng"], lora_scale=1.0)
|
| 543 |
+
```
|
| 544 |
+
|
| 545 |
+
Unload the LoRA weights since they're already fused with the underlying model. Save the fused pipeline with either [`~DiffusionPipeline.save_pretrained`] to save it locally or [`~PushToHubMixin.push_to_hub`] to save it to the Hub.
|
| 546 |
+
|
| 547 |
+
<hfoptions id="save">
|
| 548 |
+
<hfoption id="save locally">
|
| 549 |
+
|
| 550 |
+
```py
|
| 551 |
+
pipeline.unload_lora_weights()
|
| 552 |
+
pipeline.save_pretrained("path/to/fused-pipeline")
|
| 553 |
+
```
|
| 554 |
+
|
| 555 |
+
</hfoption>
|
| 556 |
+
<hfoption id="save to Hub">
|
| 557 |
+
|
| 558 |
+
```py
|
| 559 |
+
pipeline.unload_lora_weights()
|
| 560 |
+
pipeline.push_to_hub("fused-ikea-feng")
|
| 561 |
+
```
|
| 562 |
+
|
| 563 |
+
</hfoption>
|
| 564 |
+
</hfoptions>
|
| 565 |
+
|
| 566 |
+
The fused pipeline can now be quickly loaded for inference without requiring each LoRA to be separately loaded.
|
| 567 |
+
|
| 568 |
+
```py
|
| 569 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
| 570 |
+
"username/fused-ikea-feng", torch_dtype=torch.float16,
|
| 571 |
+
).to("cuda")
|
| 572 |
+
pipeline("A bowl of ramen shaped like a cute kawaii bear, by Feng Zikai").images[0]
|
| 573 |
+
```
|
| 574 |
+
|
| 575 |
+
Use [`~loaders.LoraLoaderMixin.unfuse_lora`] to restore the underlying models weights, for example, if you want to use a different `lora_scale` value. You can only unfuse if there is a single LoRA fused. For example, it won't work with the pipeline from above because there are multiple fused LoRAs. In these cases, you'll need to reload the entire model.
|
| 576 |
+
|
| 577 |
+
```py
|
| 578 |
+
pipeline.unfuse_lora()
|
| 579 |
+
```
|
| 580 |
+
|
| 581 |
+
<div class="flex justify-center">
|
| 582 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/fuse_lora.png"/>
|
| 583 |
+
</div>
|
| 584 |
+
|
| 585 |
+
## Manage
|
| 586 |
+
|
| 587 |
+
Diffusers provides several methods to help you manage working with LoRAs. These methods can be especially useful if you're working with multiple LoRAs.
|
| 588 |
+
|
| 589 |
+
### set_adapters
|
| 590 |
+
|
| 591 |
+
[`~loaders.PeftAdapterMixin.set_adapters`] also activates the current LoRA to use if there are multiple active LoRAs. This allows you to switch between different LoRAs by specifying their name.
|
| 592 |
+
|
| 593 |
+
```py
|
| 594 |
+
import torch
|
| 595 |
+
from diffusers import DiffusionPipeline
|
| 596 |
+
|
| 597 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
| 598 |
+
"stabilityai/stable-diffusion-xl-base-1.0",
|
| 599 |
+
torch_dtype=torch.float16
|
| 600 |
+
).to("cuda")
|
| 601 |
+
pipeline.load_lora_weights(
|
| 602 |
+
"ostris/ikea-instructions-lora-sdxl",
|
| 603 |
+
weight_name="ikea_instructions_xl_v1_5.safetensors",
|
| 604 |
+
adapter_name="ikea"
|
| 605 |
+
)
|
| 606 |
+
pipeline.load_lora_weights(
|
| 607 |
+
"lordjia/by-feng-zikai",
|
| 608 |
+
weight_name="fengzikai_v1.0_XL.safetensors",
|
| 609 |
+
adapter_name="feng"
|
| 610 |
+
)
|
| 611 |
+
# activates the feng LoRA instead of the ikea LoRA
|
| 612 |
+
pipeline.set_adapters("feng")
|
| 613 |
+
```
|
| 614 |
+
|
| 615 |
+
### save_lora_adapter
|
| 616 |
+
|
| 617 |
+
Save an adapter with [`~loaders.PeftAdapterMixin.save_lora_adapter`].
|
| 618 |
+
|
| 619 |
+
```py
|
| 620 |
+
import torch
|
| 621 |
+
from diffusers import AutoPipelineForText2Image
|
| 622 |
+
|
| 623 |
+
pipeline = AutoPipelineForText2Image.from_pretrained(
|
| 624 |
+
"stabilityai/stable-diffusion-xl-base-1.0",
|
| 625 |
+
torch_dtype=torch.float16
|
| 626 |
+
).to("cuda")
|
| 627 |
+
pipeline.unet.load_lora_adapter(
|
| 628 |
+
"jbilcke-hf/sdxl-cinematic-1",
|
| 629 |
+
weight_name="pytorch_lora_weights.safetensors",
|
| 630 |
+
adapter_name="cinematic"
|
| 631 |
+
prefix="unet"
|
| 632 |
+
)
|
| 633 |
+
pipeline.save_lora_adapter("path/to/save", adapter_name="cinematic")
|
| 634 |
+
```
|
| 635 |
+
|
| 636 |
+
### unload_lora_weights
|
| 637 |
+
|
| 638 |
+
The [`~loaders.lora_base.LoraBaseMixin.unload_lora_weights`] method unloads any LoRA weights in the pipeline to restore the underlying model weights.
|
| 639 |
+
|
| 640 |
+
```py
|
| 641 |
+
pipeline.unload_lora_weights()
|
| 642 |
+
```
|
| 643 |
+
|
| 644 |
+
### disable_lora
|
| 645 |
+
|
| 646 |
+
The [`~loaders.PeftAdapterMixin.disable_lora`] method disables all LoRAs (but they're still kept on the pipeline) and restores the pipeline to the underlying model weights.
|
| 647 |
+
|
| 648 |
+
```py
|
| 649 |
+
pipeline.disable_lora()
|
| 650 |
+
```
|
| 651 |
+
|
| 652 |
+
### get_active_adapters
|
| 653 |
+
|
| 654 |
+
The [`~loaders.lora_base.LoraBaseMixin.get_active_adapters`] method returns a list of active LoRAs attached to a pipeline.
|
| 655 |
+
|
| 656 |
+
```py
|
| 657 |
+
pipeline.get_active_adapters()
|
| 658 |
+
["cereal", "ikea"]
|
| 659 |
+
```
|
| 660 |
+
|
| 661 |
+
### get_list_adapters
|
| 662 |
+
|
| 663 |
+
The [`~loaders.lora_base.LoraBaseMixin.get_list_adapters`] method returns the active LoRAs for each component in the pipeline.
|
| 664 |
+
|
| 665 |
+
```py
|
| 666 |
+
pipeline.get_list_adapters()
|
| 667 |
+
{"unet": ["cereal", "ikea"], "text_encoder_2": ["cereal"]}
|
| 668 |
+
```
|
| 669 |
+
|
| 670 |
+
### delete_adapters
|
| 671 |
+
|
| 672 |
+
The [`~loaders.PeftAdapterMixin.delete_adapters`] method completely removes a LoRA and its layers from a model.
|
| 673 |
+
|
| 674 |
+
```py
|
| 675 |
+
pipeline.delete_adapters("ikea")
|
| 676 |
+
```
|
| 677 |
+
|
| 678 |
+
## Resources
|
| 679 |
+
|
| 680 |
+
Browse the [LoRA Studio](https://lorastudio.co/models) for different LoRAs to use or you can upload your favorite LoRAs from Civitai to the Hub with the Space below.
|
| 681 |
+
|
| 682 |
+
<iframe
|
| 683 |
+
src="https://multimodalart-civitai-to-hf.hf.space"
|
| 684 |
+
frameborder="0"
|
| 685 |
+
width="850"
|
| 686 |
+
height="450"
|
| 687 |
+
></iframe>
|
| 688 |
+
|
| 689 |
+
You can find additional LoRAs in the [FLUX LoRA the Explorer](https://huggingface.co/spaces/multimodalart/flux-lora-the-explorer) and [LoRA the Explorer](https://huggingface.co/spaces/multimodalart/LoraTheExplorer) Spaces.
|
| 690 |
+
|
| 691 |
+
Check out the [Fast LoRA inference for Flux with Diffusers and PEFT](https://huggingface.co/blog/lora-fast) blog post to learn how to optimize LoRA inference with methods like FlashAttention-3 and fp8 quantization.
|
tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/automodel.md
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# AutoModel
|
| 14 |
+
|
| 15 |
+
The [`AutoModel`] class automatically detects and loads the correct model class (UNet, transformer, VAE) from a `config.json` file. You don't need to know the specific model class name ahead of time. It supports data types and device placement, and works across model types and libraries.
|
| 16 |
+
|
| 17 |
+
The example below loads a transformer from Diffusers and a text encoder from Transformers. Use the `subfolder` parameter to specify where to load the `config.json` file from.
|
| 18 |
+
|
| 19 |
+
```py
|
| 20 |
+
import torch
|
| 21 |
+
from diffusers import AutoModel, DiffusionPipeline
|
| 22 |
+
|
| 23 |
+
transformer = AutoModel.from_pretrained(
|
| 24 |
+
"Qwen/Qwen-Image", subfolder="transformer", torch_dtype=torch.bfloat16, device_map="cuda"
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
text_encoder = AutoModel.from_pretrained(
|
| 28 |
+
"Qwen/Qwen-Image", subfolder="text_encoder", torch_dtype=torch.bfloat16, device_map="cuda"
|
| 29 |
+
)
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
## Custom models
|
| 33 |
+
|
| 34 |
+
[`AutoModel`] also loads models from the [Hub](https://huggingface.co/models) that aren't included in Diffusers. Set `trust_remote_code=True` in [`AutoModel.from_pretrained`] to load custom models.
|
| 35 |
+
|
| 36 |
+
A custom model repository needs a Python module with the model class, and a `config.json` with an `auto_map` entry that maps `"AutoModel"` to `"module_file.ClassName"`.
|
| 37 |
+
|
| 38 |
+
```
|
| 39 |
+
custom/custom-transformer-model/
|
| 40 |
+
├── config.json
|
| 41 |
+
├── my_model.py
|
| 42 |
+
└── diffusion_pytorch_model.safetensors
|
| 43 |
+
```
|
| 44 |
+
|
| 45 |
+
The `config.json` includes the `auto_map` field pointing to the custom class.
|
| 46 |
+
|
| 47 |
+
```json
|
| 48 |
+
{
|
| 49 |
+
"auto_map": {
|
| 50 |
+
"AutoModel": "my_model.MyCustomModel"
|
| 51 |
+
}
|
| 52 |
+
}
|
| 53 |
+
```
|
| 54 |
+
|
| 55 |
+
Then load it with `trust_remote_code=True`.
|
| 56 |
+
|
| 57 |
+
```py
|
| 58 |
+
import torch
|
| 59 |
+
from diffusers import AutoModel
|
| 60 |
+
|
| 61 |
+
transformer = AutoModel.from_pretrained(
|
| 62 |
+
"custom/custom-transformer-model", trust_remote_code=True, torch_dtype=torch.bfloat16, device_map="cuda"
|
| 63 |
+
)
|
| 64 |
+
```
|
| 65 |
+
|
| 66 |
+
For a real-world example, [Overworld/Waypoint-1-Small](https://huggingface.co/Overworld/Waypoint-1-Small/tree/main/transformer) hosts a custom `WorldModel` class across several modules in its `transformer` subfolder.
|
| 67 |
+
|
| 68 |
+
```
|
| 69 |
+
transformer/
|
| 70 |
+
├── config.json # auto_map: "model.WorldModel"
|
| 71 |
+
├── model.py
|
| 72 |
+
├── attn.py
|
| 73 |
+
├── nn.py
|
| 74 |
+
├── cache.py
|
| 75 |
+
├── quantize.py
|
| 76 |
+
├── __init__.py
|
| 77 |
+
└── diffusion_pytorch_model.safetensors
|
| 78 |
+
```
|
| 79 |
+
|
| 80 |
+
```py
|
| 81 |
+
import torch
|
| 82 |
+
from diffusers import AutoModel
|
| 83 |
+
|
| 84 |
+
transformer = AutoModel.from_pretrained(
|
| 85 |
+
"Overworld/Waypoint-1-Small", subfolder="transformer", trust_remote_code=True, torch_dtype=torch.bfloat16, device_map="cuda"
|
| 86 |
+
)
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
If the custom model inherits from the [`ModelMixin`] class, it gets access to the same features as Diffusers model classes, like [regional compilation](../optimization/fp16#regional-compilation) and [group offloading](../optimization/memory#group-offloading).
|
| 90 |
+
|
| 91 |
+
> [!WARNING]
|
| 92 |
+
> As a precaution with `trust_remote_code=True`, pass a commit hash to the `revision` argument in [`AutoModel.from_pretrained`] to make sure the code hasn't been updated with new malicious code (unless you fully trust the model owners).
|
| 93 |
+
>
|
| 94 |
+
> ```py
|
| 95 |
+
> transformer = AutoModel.from_pretrained(
|
| 96 |
+
> "Overworld/Waypoint-1-Small", subfolder="transformer", trust_remote_code=True, revision="a3d8cb2"
|
| 97 |
+
> )
|
| 98 |
+
> ```
|
| 99 |
+
|
| 100 |
+
### Saving custom models
|
| 101 |
+
|
| 102 |
+
Use [`~ConfigMixin.register_for_auto_class`] to add the `auto_map` entry to `config.json` automatically when saving. This avoids having to manually edit the config file.
|
| 103 |
+
|
| 104 |
+
```py
|
| 105 |
+
# my_model.py
|
| 106 |
+
from diffusers import ModelMixin, ConfigMixin
|
| 107 |
+
|
| 108 |
+
class MyCustomModel(ModelMixin, ConfigMixin):
|
| 109 |
+
...
|
| 110 |
+
|
| 111 |
+
MyCustomModel.register_for_auto_class("AutoModel")
|
| 112 |
+
|
| 113 |
+
model = MyCustomModel(...)
|
| 114 |
+
model.save_pretrained("./my_model")
|
| 115 |
+
```
|
| 116 |
+
|
| 117 |
+
The saved `config.json` will include the `auto_map` field.
|
| 118 |
+
|
| 119 |
+
```json
|
| 120 |
+
{
|
| 121 |
+
"auto_map": {
|
| 122 |
+
"AutoModel": "my_model.MyCustomModel"
|
| 123 |
+
}
|
| 124 |
+
}
|
| 125 |
+
```
|
| 126 |
+
|
| 127 |
+
> [!NOTE]
|
| 128 |
+
> Learn more about implementing custom models in the [Community components](../using-diffusers/custom_pipeline_overview#community-components) guide.
|
tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/batched_inference.md
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# Batch inference
|
| 14 |
+
|
| 15 |
+
Batch inference processes multiple prompts at a time to increase throughput. It is more efficient because processing multiple prompts at once maximizes GPU usage versus processing a single prompt and underutilizing the GPU.
|
| 16 |
+
|
| 17 |
+
The downside is increased latency because you must wait for the entire batch to complete, and more GPU memory is required for large batches.
|
| 18 |
+
|
| 19 |
+
For text-to-image, pass a list of prompts to the pipeline and for image-to-image, pass a list of images and prompts to the pipeline. The example below demonstrates batched text-to-image inference.
|
| 20 |
+
|
| 21 |
+
```py
|
| 22 |
+
import torch
|
| 23 |
+
import matplotlib.pyplot as plt
|
| 24 |
+
from diffusers import DiffusionPipeline
|
| 25 |
+
|
| 26 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
| 27 |
+
"stabilityai/stable-diffusion-xl-base-1.0",
|
| 28 |
+
torch_dtype=torch.float16,
|
| 29 |
+
device_map="cuda"
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
prompts = [
|
| 33 |
+
"Cinematic shot of a cozy coffee shop interior, warm pastel light streaming through a window where a cat rests. Shallow depth of field, glowing cups in soft focus, dreamy lofi-inspired mood, nostalgic tones, framed like a quiet film scene.",
|
| 34 |
+
"Polaroid-style photograph of a cozy coffee shop interior, bathed in warm pastel light. A cat sits on the windowsill near steaming mugs. Soft, slightly faded tones and dreamy blur evoke nostalgia, a lofi mood, and the intimate, imperfect charm of instant film.",
|
| 35 |
+
"Soft watercolor illustration of a cozy coffee shop interior, pastel washes of color filling the space. A cat rests peacefully on the windowsill as warm light glows through. Gentle brushstrokes create a dreamy, lofi-inspired atmosphere with whimsical textures and nostalgic calm.",
|
| 36 |
+
"Isometric pixel-art illustration of a cozy coffee shop interior in detailed 8-bit style. Warm pastel light fills the space as a cat rests on the windowsill. Blocky furniture and tiny mugs add charm, low-res retro graphics enhance the nostalgic, lofi-inspired game aesthetic."
|
| 37 |
+
]
|
| 38 |
+
|
| 39 |
+
images = pipeline(
|
| 40 |
+
prompt=prompts,
|
| 41 |
+
).images
|
| 42 |
+
|
| 43 |
+
fig, axes = plt.subplots(2, 2, figsize=(12, 12))
|
| 44 |
+
axes = axes.flatten()
|
| 45 |
+
|
| 46 |
+
for i, image in enumerate(images):
|
| 47 |
+
axes[i].imshow(image)
|
| 48 |
+
axes[i].set_title(f"Image {i+1}")
|
| 49 |
+
axes[i].axis('off')
|
| 50 |
+
|
| 51 |
+
plt.tight_layout()
|
| 52 |
+
plt.show()
|
| 53 |
+
```
|
| 54 |
+
|
| 55 |
+
<div class="flex justify-center">
|
| 56 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/batch-inference.png"/>
|
| 57 |
+
</div>
|
| 58 |
+
|
| 59 |
+
To generate multiple variations of one prompt, use the `num_images_per_prompt` argument.
|
| 60 |
+
|
| 61 |
+
```py
|
| 62 |
+
import torch
|
| 63 |
+
import matplotlib.pyplot as plt
|
| 64 |
+
from diffusers import DiffusionPipeline
|
| 65 |
+
|
| 66 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
| 67 |
+
"stabilityai/stable-diffusion-xl-base-1.0",
|
| 68 |
+
torch_dtype=torch.float16,
|
| 69 |
+
device_map="cuda"
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
prompt="""
|
| 73 |
+
Isometric pixel-art illustration of a cozy coffee shop interior in detailed 8-bit style. Warm pastel light fills the
|
| 74 |
+
space as a cat rests on the windowsill. Blocky furniture and tiny mugs add charm, low-res retro graphics enhance the
|
| 75 |
+
nostalgic, lofi-inspired game aesthetic.
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
images = pipeline(
|
| 79 |
+
prompt=prompt,
|
| 80 |
+
num_images_per_prompt=4
|
| 81 |
+
).images
|
| 82 |
+
|
| 83 |
+
fig, axes = plt.subplots(2, 2, figsize=(12, 12))
|
| 84 |
+
axes = axes.flatten()
|
| 85 |
+
|
| 86 |
+
for i, image in enumerate(images):
|
| 87 |
+
axes[i].imshow(image)
|
| 88 |
+
axes[i].set_title(f"Image {i+1}")
|
| 89 |
+
axes[i].axis('off')
|
| 90 |
+
|
| 91 |
+
plt.tight_layout()
|
| 92 |
+
plt.show()
|
| 93 |
+
```
|
| 94 |
+
|
| 95 |
+
<div class="flex justify-center">
|
| 96 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/batch-inference-2.png"/>
|
| 97 |
+
</div>
|
| 98 |
+
|
| 99 |
+
Combine both approaches to generate different variations of different prompts.
|
| 100 |
+
|
| 101 |
+
```py
|
| 102 |
+
images = pipeline(
|
| 103 |
+
prompt=prompts,
|
| 104 |
+
num_images_per_prompt=2,
|
| 105 |
+
).images
|
| 106 |
+
|
| 107 |
+
fig, axes = plt.subplots(2, 4, figsize=(12, 12))
|
| 108 |
+
axes = axes.flatten()
|
| 109 |
+
|
| 110 |
+
for i, image in enumerate(images):
|
| 111 |
+
axes[i].imshow(image)
|
| 112 |
+
axes[i].set_title(f"Image {i+1}")
|
| 113 |
+
axes[i].axis('off')
|
| 114 |
+
|
| 115 |
+
plt.tight_layout()
|
| 116 |
+
plt.show()
|
| 117 |
+
```
|
| 118 |
+
|
| 119 |
+
<div class="flex justify-center">
|
| 120 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/batch-inference-3.png"/>
|
| 121 |
+
</div>
|
| 122 |
+
|
| 123 |
+
## Deterministic generation
|
| 124 |
+
|
| 125 |
+
Enable reproducible batch generation by passing a list of [Generator’s](https://pytorch.org/docs/stable/generated/torch.Generator.html) to the pipeline and tie each `Generator` to a seed to reuse it.
|
| 126 |
+
|
| 127 |
+
> [!TIP]
|
| 128 |
+
> Refer to the [Reproducibility](./reusing_seeds) docs to learn more about deterministic algorithms and the `Generator` object.
|
| 129 |
+
|
| 130 |
+
Use a list comprehension to iterate over the batch size specified in `range()` to create a unique `Generator` object for each image in the batch. Don't multiply the `Generator` by the batch size because that only creates one `Generator` object that is used sequentially for each image in the batch.
|
| 131 |
+
|
| 132 |
+
```py
|
| 133 |
+
generator = [torch.Generator(device="cuda").manual_seed(0)] * 3
|
| 134 |
+
```
|
| 135 |
+
|
| 136 |
+
Pass the `generator` to the pipeline.
|
| 137 |
+
|
| 138 |
+
```py
|
| 139 |
+
import torch
|
| 140 |
+
from diffusers import DiffusionPipeline
|
| 141 |
+
|
| 142 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
| 143 |
+
"stabilityai/stable-diffusion-xl-base-1.0",
|
| 144 |
+
torch_dtype=torch.float16,
|
| 145 |
+
device_map="cuda"
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
generator = [torch.Generator(device="cuda").manual_seed(i) for i in range(3)]
|
| 149 |
+
prompts = [
|
| 150 |
+
"Cinematic shot of a cozy coffee shop interior, warm pastel light streaming through a window where a cat rests. Shallow depth of field, glowing cups in soft focus, dreamy lofi-inspired mood, nostalgic tones, framed like a quiet film scene.",
|
| 151 |
+
"Polaroid-style photograph of a cozy coffee shop interior, bathed in warm pastel light. A cat sits on the windowsill near steaming mugs. Soft, slightly faded tones and dreamy blur evoke nostalgia, a lofi mood, and the intimate, imperfect charm of instant film.",
|
| 152 |
+
"Soft watercolor illustration of a cozy coffee shop interior, pastel washes of color filling the space. A cat rests peacefully on the windowsill as warm light glows through. Gentle brushstrokes create a dreamy, lofi-inspired atmosphere with whimsical textures and nostalgic calm.",
|
| 153 |
+
"Isometric pixel-art illustration of a cozy coffee shop interior in detailed 8-bit style. Warm pastel light fills the space as a cat rests on the windowsill. Blocky furniture and tiny mugs add charm, low-res retro graphics enhance the nostalgic, lofi-inspired game aesthetic."
|
| 154 |
+
]
|
| 155 |
+
|
| 156 |
+
images = pipeline(
|
| 157 |
+
prompt=prompts,
|
| 158 |
+
generator=generator
|
| 159 |
+
).images
|
| 160 |
+
|
| 161 |
+
fig, axes = plt.subplots(2, 2, figsize=(12, 12))
|
| 162 |
+
axes = axes.flatten()
|
| 163 |
+
|
| 164 |
+
for i, image in enumerate(images):
|
| 165 |
+
axes[i].imshow(image)
|
| 166 |
+
axes[i].set_title(f"Image {i+1}")
|
| 167 |
+
axes[i].axis('off')
|
| 168 |
+
|
| 169 |
+
plt.tight_layout()
|
| 170 |
+
plt.show()
|
| 171 |
+
```
|
| 172 |
+
|
| 173 |
+
You can use this to select an image associated with a seed and iteratively improve on it by crafting a more detailed prompt.
|
tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/callback.md
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# Pipeline callbacks
|
| 14 |
+
|
| 15 |
+
A callback is a function that modifies [`DiffusionPipeline`] behavior and it is executed at the end of a denoising step. The changes are propagated to subsequent steps in the denoising process. It is useful for adjusting pipeline attributes or tensor variables to support new features without rewriting the underlying pipeline code.
|
| 16 |
+
|
| 17 |
+
Diffusers provides several callbacks in the pipeline [overview](../api/pipelines/overview#callbacks).
|
| 18 |
+
|
| 19 |
+
To enable a callback, configure when the callback is executed after a certain number of denoising steps with one of the following arguments.
|
| 20 |
+
|
| 21 |
+
- `cutoff_step_ratio` specifies when a callback is activated as a percentage of the total denoising steps.
|
| 22 |
+
- `cutoff_step_index` specifies the exact step number a callback is activated.
|
| 23 |
+
|
| 24 |
+
The example below uses `cutoff_step_ratio=0.4`, which means the callback is activated once denoising reaches 40% of the total inference steps. [`~callbacks.SDXLCFGCutoffCallback`] disables classifier-free guidance (CFG) after a certain number of steps, which can help save compute without significantly affecting performance.
|
| 25 |
+
|
| 26 |
+
Define a callback with either of the `cutoff` arguments and pass it to the `callback_on_step_end` parameter in the pipeline.
|
| 27 |
+
|
| 28 |
+
```py
|
| 29 |
+
import torch
|
| 30 |
+
from diffusers import DPMSolverMultistepScheduler, StableDiffusionXLPipeline
|
| 31 |
+
from diffusers.callbacks import SDXLCFGCutoffCallback
|
| 32 |
+
|
| 33 |
+
callback = SDXLCFGCutoffCallback(cutoff_step_ratio=0.4)
|
| 34 |
+
# if using cutoff_step_index
|
| 35 |
+
# callback = SDXLCFGCutoffCallback(cutoff_step_ratio=None, cutoff_step_index=10)
|
| 36 |
+
|
| 37 |
+
pipeline = StableDiffusionXLPipeline.from_pretrained(
|
| 38 |
+
"stabilityai/stable-diffusion-xl-base-1.0",
|
| 39 |
+
torch_dtype=torch.float16,
|
| 40 |
+
device_map="cuda"
|
| 41 |
+
)
|
| 42 |
+
pipeline.scheduler = DPMSolverMultistepScheduler.from_config(pipeline.scheduler.config, use_karras_sigmas=True)
|
| 43 |
+
|
| 44 |
+
prompt = "a sports car at the road, best quality, high quality, high detail, 8k resolution"
|
| 45 |
+
output = pipeline(
|
| 46 |
+
prompt=prompt,
|
| 47 |
+
negative_prompt="",
|
| 48 |
+
guidance_scale=6.5,
|
| 49 |
+
num_inference_steps=25,
|
| 50 |
+
generator=generator,
|
| 51 |
+
callback_on_step_end=callback,
|
| 52 |
+
)
|
| 53 |
+
```
|
| 54 |
+
|
| 55 |
+
If you want to add a new official callback, feel free to open a [feature request](https://github.com/huggingface/diffusers/issues/new/choose) or [submit a PR](https://huggingface.co/docs/diffusers/main/en/conceptual/contribution#how-to-open-a-pr). Otherwise, you can also create your own callback as shown below.
|
| 56 |
+
|
| 57 |
+
## Early stopping
|
| 58 |
+
|
| 59 |
+
Early stopping is useful if you aren't happy with the intermediate results during generation. This callback sets a hardcoded stop point after which the pipeline terminates by setting the `_interrupt` attribute to `True`.
|
| 60 |
+
|
| 61 |
+
```py
|
| 62 |
+
from diffusers import StableDiffusionXLPipeline
|
| 63 |
+
|
| 64 |
+
def interrupt_callback(pipeline, i, t, callback_kwargs):
|
| 65 |
+
stop_idx = 10
|
| 66 |
+
if i == stop_idx:
|
| 67 |
+
pipeline._interrupt = True
|
| 68 |
+
|
| 69 |
+
return callback_kwargs
|
| 70 |
+
|
| 71 |
+
pipeline = StableDiffusionXLPipeline.from_pretrained(
|
| 72 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5"
|
| 73 |
+
)
|
| 74 |
+
num_inference_steps = 50
|
| 75 |
+
|
| 76 |
+
pipeline(
|
| 77 |
+
"A photo of a cat",
|
| 78 |
+
num_inference_steps=num_inference_steps,
|
| 79 |
+
callback_on_step_end=interrupt_callback,
|
| 80 |
+
)
|
| 81 |
+
```
|
| 82 |
+
|
| 83 |
+
## Display intermediate images
|
| 84 |
+
|
| 85 |
+
Visualizing the intermediate images is useful for progress monitoring and assessing the quality of the generated content. This callback decodes the latent tensors at each step and converts them to images.
|
| 86 |
+
|
| 87 |
+
[Convert](https://huggingface.co/blog/TimothyAlexisVass/explaining-the-sdxl-latent-space) the Stable Diffusion XL latents from latents (4 channels) to RGB tensors (3 tensors).
|
| 88 |
+
|
| 89 |
+
```py
|
| 90 |
+
def latents_to_rgb(latents):
|
| 91 |
+
weights = (
|
| 92 |
+
(60, -60, 25, -70),
|
| 93 |
+
(60, -5, 15, -50),
|
| 94 |
+
(60, 10, -5, -35),
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
weights_tensor = torch.t(torch.tensor(weights, dtype=latents.dtype).to(latents.device))
|
| 98 |
+
biases_tensor = torch.tensor((150, 140, 130), dtype=latents.dtype).to(latents.device)
|
| 99 |
+
rgb_tensor = torch.einsum("...lxy,lr -> ...rxy", latents, weights_tensor) + biases_tensor.unsqueeze(-1).unsqueeze(-1)
|
| 100 |
+
image_array = rgb_tensor.clamp(0, 255).byte().cpu().numpy().transpose(1, 2, 0)
|
| 101 |
+
|
| 102 |
+
return Image.fromarray(image_array)
|
| 103 |
+
```
|
| 104 |
+
|
| 105 |
+
Extract the latents and convert the first image in the batch to RGB. Save the image as a PNG file with the step number.
|
| 106 |
+
|
| 107 |
+
```py
|
| 108 |
+
def decode_tensors(pipe, step, timestep, callback_kwargs):
|
| 109 |
+
latents = callback_kwargs["latents"]
|
| 110 |
+
|
| 111 |
+
image = latents_to_rgb(latents[0])
|
| 112 |
+
image.save(f"{step}.png")
|
| 113 |
+
|
| 114 |
+
return callback_kwargs
|
| 115 |
+
```
|
| 116 |
+
|
| 117 |
+
Use the `callback_on_step_end_tensor_inputs` parameter to specify what input type to modify, which in this case, are the latents.
|
| 118 |
+
|
| 119 |
+
```py
|
| 120 |
+
import torch
|
| 121 |
+
from PIL import Image
|
| 122 |
+
from diffusers import AutoPipelineForText2Image
|
| 123 |
+
|
| 124 |
+
pipeline = AutoPipelineForText2Image.from_pretrained(
|
| 125 |
+
"stabilityai/stable-diffusion-xl-base-1.0",
|
| 126 |
+
torch_dtype=torch.float16,
|
| 127 |
+
device_map="cuda"
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
image = pipeline(
|
| 131 |
+
prompt="A croissant shaped like a cute bear.",
|
| 132 |
+
negative_prompt="Deformed, ugly, bad anatomy",
|
| 133 |
+
callback_on_step_end=decode_tensors,
|
| 134 |
+
callback_on_step_end_tensor_inputs=["latents"],
|
| 135 |
+
).images[0]
|
| 136 |
+
```
|
tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/conditional_image_generation.md
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# Text-to-image
|
| 14 |
+
|
| 15 |
+
[[open-in-colab]]
|
| 16 |
+
|
| 17 |
+
When you think of diffusion models, text-to-image is usually one of the first things that come to mind. Text-to-image generates an image from a text description (for example, "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k") which is also known as a *prompt*.
|
| 18 |
+
|
| 19 |
+
From a very high level, a diffusion model takes a prompt and some random initial noise, and iteratively removes the noise to construct an image. The *denoising* process is guided by the prompt, and once the denoising process ends after a predetermined number of time steps, the image representation is decoded into an image.
|
| 20 |
+
|
| 21 |
+
> [!TIP]
|
| 22 |
+
> Read the [How does Stable Diffusion work?](https://huggingface.co/blog/stable_diffusion#how-does-stable-diffusion-work) blog post to learn more about how a latent diffusion model works.
|
| 23 |
+
|
| 24 |
+
You can generate images from a prompt in 🤗 Diffusers in two steps:
|
| 25 |
+
|
| 26 |
+
1. Load a checkpoint into the [`AutoPipelineForText2Image`] class, which automatically detects the appropriate pipeline class to use based on the checkpoint:
|
| 27 |
+
|
| 28 |
+
```py
|
| 29 |
+
from diffusers import AutoPipelineForText2Image
|
| 30 |
+
import torch
|
| 31 |
+
|
| 32 |
+
pipeline = AutoPipelineForText2Image.from_pretrained(
|
| 33 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16, variant="fp16"
|
| 34 |
+
).to("cuda")
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
2. Pass a prompt to the pipeline to generate an image:
|
| 38 |
+
|
| 39 |
+
```py
|
| 40 |
+
image = pipeline(
|
| 41 |
+
"stained glass of darth vader, backlight, centered composition, masterpiece, photorealistic, 8k"
|
| 42 |
+
).images[0]
|
| 43 |
+
image
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
<div class="flex justify-center">
|
| 47 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/text2img-vader.png"/>
|
| 48 |
+
</div>
|
| 49 |
+
|
| 50 |
+
## Popular models
|
| 51 |
+
|
| 52 |
+
The most common text-to-image models are [Stable Diffusion v1.5](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5), [Stable Diffusion XL (SDXL)](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0), and [Kandinsky 2.2](https://huggingface.co/kandinsky-community/kandinsky-2-2-decoder). There are also ControlNet models or adapters that can be used with text-to-image models for more direct control in generating images. The results from each model are slightly different because of their architecture and training process, but no matter which model you choose, their usage is more or less the same. Let's use the same prompt for each model and compare their results.
|
| 53 |
+
|
| 54 |
+
### Stable Diffusion v1.5
|
| 55 |
+
|
| 56 |
+
[Stable Diffusion v1.5](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5) is a latent diffusion model initialized from [Stable Diffusion v1-4](https://huggingface.co/CompVis/stable-diffusion-v1-4), and finetuned for 595K steps on 512x512 images from the LAION-Aesthetics V2 dataset. You can use this model like:
|
| 57 |
+
|
| 58 |
+
```py
|
| 59 |
+
from diffusers import AutoPipelineForText2Image
|
| 60 |
+
import torch
|
| 61 |
+
|
| 62 |
+
pipeline = AutoPipelineForText2Image.from_pretrained(
|
| 63 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16, variant="fp16"
|
| 64 |
+
).to("cuda")
|
| 65 |
+
generator = torch.Generator("cuda").manual_seed(31)
|
| 66 |
+
image = pipeline("Astronaut in a jungle, cold color palette, muted colors, detailed, 8k", generator=generator).images[0]
|
| 67 |
+
image
|
| 68 |
+
```
|
| 69 |
+
|
| 70 |
+
### Stable Diffusion XL
|
| 71 |
+
|
| 72 |
+
SDXL is a much larger version of the previous Stable Diffusion models, and involves a two-stage model process that adds even more details to an image. It also includes some additional *micro-conditionings* to generate high-quality images centered subjects. Take a look at the more comprehensive [SDXL](sdxl) guide to learn more about how to use it. In general, you can use SDXL like:
|
| 73 |
+
|
| 74 |
+
```py
|
| 75 |
+
from diffusers import AutoPipelineForText2Image
|
| 76 |
+
import torch
|
| 77 |
+
|
| 78 |
+
pipeline = AutoPipelineForText2Image.from_pretrained(
|
| 79 |
+
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16, variant="fp16"
|
| 80 |
+
).to("cuda")
|
| 81 |
+
generator = torch.Generator("cuda").manual_seed(31)
|
| 82 |
+
image = pipeline("Astronaut in a jungle, cold color palette, muted colors, detailed, 8k", generator=generator).images[0]
|
| 83 |
+
image
|
| 84 |
+
```
|
| 85 |
+
|
| 86 |
+
### Kandinsky 2.2
|
| 87 |
+
|
| 88 |
+
The Kandinsky model is a bit different from the Stable Diffusion models because it also uses an image prior model to create embeddings that are used to better align text and images in the diffusion model.
|
| 89 |
+
|
| 90 |
+
The easiest way to use Kandinsky 2.2 is:
|
| 91 |
+
|
| 92 |
+
```py
|
| 93 |
+
from diffusers import AutoPipelineForText2Image
|
| 94 |
+
import torch
|
| 95 |
+
|
| 96 |
+
pipeline = AutoPipelineForText2Image.from_pretrained(
|
| 97 |
+
"kandinsky-community/kandinsky-2-2-decoder", torch_dtype=torch.float16
|
| 98 |
+
).to("cuda")
|
| 99 |
+
generator = torch.Generator("cuda").manual_seed(31)
|
| 100 |
+
image = pipeline("Astronaut in a jungle, cold color palette, muted colors, detailed, 8k", generator=generator).images[0]
|
| 101 |
+
image
|
| 102 |
+
```
|
| 103 |
+
|
| 104 |
+
### ControlNet
|
| 105 |
+
|
| 106 |
+
ControlNet models are auxiliary models or adapters that are finetuned on top of text-to-image models, such as [Stable Diffusion v1.5](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5). Using ControlNet models in combination with text-to-image models offers diverse options for more explicit control over how to generate an image. With ControlNet, you add an additional conditioning input image to the model. For example, if you provide an image of a human pose (usually represented as multiple keypoints that are connected into a skeleton) as a conditioning input, the model generates an image that follows the pose of the image. Check out the more in-depth [ControlNet](controlnet) guide to learn more about other conditioning inputs and how to use them.
|
| 107 |
+
|
| 108 |
+
In this example, let's condition the ControlNet with a human pose estimation image. Load the ControlNet model pretrained on human pose estimations:
|
| 109 |
+
|
| 110 |
+
```py
|
| 111 |
+
from diffusers import ControlNetModel, AutoPipelineForText2Image
|
| 112 |
+
from diffusers.utils import load_image
|
| 113 |
+
import torch
|
| 114 |
+
|
| 115 |
+
controlnet = ControlNetModel.from_pretrained(
|
| 116 |
+
"lllyasviel/control_v11p_sd15_openpose", torch_dtype=torch.float16, variant="fp16"
|
| 117 |
+
).to("cuda")
|
| 118 |
+
pose_image = load_image("https://huggingface.co/lllyasviel/control_v11p_sd15_openpose/resolve/main/images/control.png")
|
| 119 |
+
```
|
| 120 |
+
|
| 121 |
+
Pass the `controlnet` to the [`AutoPipelineForText2Image`], and provide the prompt and pose estimation image:
|
| 122 |
+
|
| 123 |
+
```py
|
| 124 |
+
pipeline = AutoPipelineForText2Image.from_pretrained(
|
| 125 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5", controlnet=controlnet, torch_dtype=torch.float16, variant="fp16"
|
| 126 |
+
).to("cuda")
|
| 127 |
+
generator = torch.Generator("cuda").manual_seed(31)
|
| 128 |
+
image = pipeline("Astronaut in a jungle, cold color palette, muted colors, detailed, 8k", image=pose_image, generator=generator).images[0]
|
| 129 |
+
image
|
| 130 |
+
```
|
| 131 |
+
|
| 132 |
+
<div class="flex flex-row gap-4">
|
| 133 |
+
<div class="flex-1">
|
| 134 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/text2img-1.png"/>
|
| 135 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">Stable Diffusion v1.5</figcaption>
|
| 136 |
+
</div>
|
| 137 |
+
<div class="flex-1">
|
| 138 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/sdxl-text2img.png"/>
|
| 139 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">Stable Diffusion XL</figcaption>
|
| 140 |
+
</div>
|
| 141 |
+
<div class="flex-1">
|
| 142 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/text2img-2.png"/>
|
| 143 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">Kandinsky 2.2</figcaption>
|
| 144 |
+
</div>
|
| 145 |
+
<div class="flex-1">
|
| 146 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/text2img-3.png"/>
|
| 147 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">ControlNet (pose conditioning)</figcaption>
|
| 148 |
+
</div>
|
| 149 |
+
</div>
|
| 150 |
+
|
| 151 |
+
## Configure pipeline parameters
|
| 152 |
+
|
| 153 |
+
There are a number of parameters that can be configured in the pipeline that affect how an image is generated. You can change the image's output size, specify a negative prompt to improve image quality, and more. This section dives deeper into how to use these parameters.
|
| 154 |
+
|
| 155 |
+
### Height and width
|
| 156 |
+
|
| 157 |
+
The `height` and `width` parameters control the height and width (in pixels) of the generated image. By default, the Stable Diffusion v1.5 model outputs 512x512 images, but you can change this to any size that is a multiple of 8. For example, to create a rectangular image:
|
| 158 |
+
|
| 159 |
+
```py
|
| 160 |
+
from diffusers import AutoPipelineForText2Image
|
| 161 |
+
import torch
|
| 162 |
+
|
| 163 |
+
pipeline = AutoPipelineForText2Image.from_pretrained(
|
| 164 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16, variant="fp16"
|
| 165 |
+
).to("cuda")
|
| 166 |
+
image = pipeline(
|
| 167 |
+
"Astronaut in a jungle, cold color palette, muted colors, detailed, 8k", height=768, width=512
|
| 168 |
+
).images[0]
|
| 169 |
+
image
|
| 170 |
+
```
|
| 171 |
+
|
| 172 |
+
<div class="flex justify-center">
|
| 173 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/text2img-hw.png"/>
|
| 174 |
+
</div>
|
| 175 |
+
|
| 176 |
+
> [!WARNING]
|
| 177 |
+
> Other models may have different default image sizes depending on the image sizes in the training dataset. For example, SDXL's default image size is 1024x1024 and using lower `height` and `width` values may result in lower quality images. Make sure you check the model's API reference first!
|
| 178 |
+
|
| 179 |
+
### Guidance scale
|
| 180 |
+
|
| 181 |
+
The `guidance_scale` parameter affects how much the prompt influences image generation. A lower value gives the model "creativity" to generate images that are more loosely related to the prompt. Higher `guidance_scale` values push the model to follow the prompt more closely, and if this value is too high, you may observe some artifacts in the generated image.
|
| 182 |
+
|
| 183 |
+
```py
|
| 184 |
+
from diffusers import AutoPipelineForText2Image
|
| 185 |
+
import torch
|
| 186 |
+
|
| 187 |
+
pipeline = AutoPipelineForText2Image.from_pretrained(
|
| 188 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16
|
| 189 |
+
).to("cuda")
|
| 190 |
+
image = pipeline(
|
| 191 |
+
"Astronaut in a jungle, cold color palette, muted colors, detailed, 8k", guidance_scale=3.5
|
| 192 |
+
).images[0]
|
| 193 |
+
image
|
| 194 |
+
```
|
| 195 |
+
|
| 196 |
+
<div class="flex flex-row gap-4">
|
| 197 |
+
<div class="flex-1">
|
| 198 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/text2img-guidance-scale-2.5.png"/>
|
| 199 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">guidance_scale = 2.5</figcaption>
|
| 200 |
+
</div>
|
| 201 |
+
<div class="flex-1">
|
| 202 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/text2img-guidance-scale-7.5.png"/>
|
| 203 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">guidance_scale = 7.5</figcaption>
|
| 204 |
+
</div>
|
| 205 |
+
<div class="flex-1">
|
| 206 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/text2img-guidance-scale-10.5.png"/>
|
| 207 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">guidance_scale = 10.5</figcaption>
|
| 208 |
+
</div>
|
| 209 |
+
</div>
|
| 210 |
+
|
| 211 |
+
### Negative prompt
|
| 212 |
+
|
| 213 |
+
Just like how a prompt guides generation, a *negative prompt* steers the model away from things you don't want the model to generate. This is commonly used to improve overall image quality by removing poor or bad image features such as "low resolution" or "bad details". You can also use a negative prompt to remove or modify the content and style of an image.
|
| 214 |
+
|
| 215 |
+
```py
|
| 216 |
+
from diffusers import AutoPipelineForText2Image
|
| 217 |
+
import torch
|
| 218 |
+
|
| 219 |
+
pipeline = AutoPipelineForText2Image.from_pretrained(
|
| 220 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16
|
| 221 |
+
).to("cuda")
|
| 222 |
+
image = pipeline(
|
| 223 |
+
prompt="Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
|
| 224 |
+
negative_prompt="ugly, deformed, disfigured, poor details, bad anatomy",
|
| 225 |
+
).images[0]
|
| 226 |
+
image
|
| 227 |
+
```
|
| 228 |
+
|
| 229 |
+
<div class="flex flex-row gap-4">
|
| 230 |
+
<div class="flex-1">
|
| 231 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/text2img-neg-prompt-1.png"/>
|
| 232 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">negative_prompt = "ugly, deformed, disfigured, poor details, bad anatomy"</figcaption>
|
| 233 |
+
</div>
|
| 234 |
+
<div class="flex-1">
|
| 235 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/text2img-neg-prompt-2.png"/>
|
| 236 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">negative_prompt = "astronaut"</figcaption>
|
| 237 |
+
</div>
|
| 238 |
+
</div>
|
| 239 |
+
|
| 240 |
+
### Generator
|
| 241 |
+
|
| 242 |
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html#generator) object enables reproducibility in a pipeline by setting a manual seed. You can use a `Generator` to generate batches of images and iteratively improve on an image generated from a seed as detailed in the [Improve image quality with deterministic generation](reusing_seeds) guide.
|
| 243 |
+
|
| 244 |
+
You can set a seed and `Generator` as shown below. Creating an image with a `Generator` should return the same result each time instead of randomly generating a new image.
|
| 245 |
+
|
| 246 |
+
```py
|
| 247 |
+
from diffusers import AutoPipelineForText2Image
|
| 248 |
+
import torch
|
| 249 |
+
|
| 250 |
+
pipeline = AutoPipelineForText2Image.from_pretrained(
|
| 251 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16
|
| 252 |
+
).to("cuda")
|
| 253 |
+
generator = torch.Generator(device="cuda").manual_seed(30)
|
| 254 |
+
image = pipeline(
|
| 255 |
+
"Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
|
| 256 |
+
generator=generator,
|
| 257 |
+
).images[0]
|
| 258 |
+
image
|
| 259 |
+
```
|
| 260 |
+
|
| 261 |
+
## Control image generation
|
| 262 |
+
|
| 263 |
+
There are several ways to exert more control over how an image is generated outside of configuring a pipeline's parameters, such as prompt weighting and ControlNet models.
|
| 264 |
+
|
| 265 |
+
### Prompt weighting
|
| 266 |
+
|
| 267 |
+
Prompt weighting is a technique for increasing or decreasing the importance of concepts in a prompt to emphasize or minimize certain features in an image. We recommend using the [Compel](https://github.com/damian0815/compel) library to help you generate the weighted prompt embeddings.
|
| 268 |
+
|
| 269 |
+
> [!TIP]
|
| 270 |
+
> Learn how to create the prompt embeddings in the [Prompt weighting](weighted_prompts) guide. This example focuses on how to use the prompt embeddings in the pipeline.
|
| 271 |
+
|
| 272 |
+
Once you've created the embeddings, you can pass them to the `prompt_embeds` (and `negative_prompt_embeds` if you're using a negative prompt) parameter in the pipeline.
|
| 273 |
+
|
| 274 |
+
```py
|
| 275 |
+
from diffusers import AutoPipelineForText2Image
|
| 276 |
+
import torch
|
| 277 |
+
|
| 278 |
+
pipeline = AutoPipelineForText2Image.from_pretrained(
|
| 279 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16
|
| 280 |
+
).to("cuda")
|
| 281 |
+
image = pipeline(
|
| 282 |
+
prompt_embeds=prompt_embeds, # generated from Compel
|
| 283 |
+
negative_prompt_embeds=negative_prompt_embeds, # generated from Compel
|
| 284 |
+
).images[0]
|
| 285 |
+
```
|
| 286 |
+
|
| 287 |
+
### ControlNet
|
| 288 |
+
|
| 289 |
+
As you saw in the [ControlNet](#controlnet) section, these models offer a more flexible and accurate way to generate images by incorporating an additional conditioning image input. Each ControlNet model is pretrained on a particular type of conditioning image to generate new images that resemble it. For example, if you take a ControlNet model pretrained on depth maps, you can give the model a depth map as a conditioning input and it'll generate an image that preserves the spatial information in it. This is quicker and easier than specifying the depth information in a prompt. You can even combine multiple conditioning inputs with a [MultiControlNet](controlnet#multicontrolnet)!
|
| 290 |
+
|
| 291 |
+
There are many types of conditioning inputs you can use, and 🤗 Diffusers supports ControlNet for Stable Diffusion and SDXL models. Take a look at the more comprehensive [ControlNet](controlnet) guide to learn how you can use these models.
|
| 292 |
+
|
| 293 |
+
## Optimize
|
| 294 |
+
|
| 295 |
+
Diffusion models are large, and the iterative nature of denoising an image is computationally expensive and intensive. But this doesn't mean you need access to powerful - or even many - GPUs to use them. There are many optimization techniques for running diffusion models on consumer and free-tier resources. For example, you can load model weights in half-precision to save GPU memory and increase speed or offload the entire model to the GPU to save even more memory.
|
| 296 |
+
|
| 297 |
+
PyTorch 2.0 also supports a more memory-efficient attention mechanism called [*scaled dot product attention*](../optimization/fp16#scaled-dot-product-attention) that is automatically enabled if you're using PyTorch 2.0. You can combine this with [`torch.compile`](https://pytorch.org/tutorials/intermediate/torch_compile_tutorial.html) to speed your code up even more:
|
| 298 |
+
|
| 299 |
+
```py
|
| 300 |
+
from diffusers import AutoPipelineForText2Image
|
| 301 |
+
import torch
|
| 302 |
+
|
| 303 |
+
pipeline = AutoPipelineForText2Image.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16, variant="fp16").to("cuda")
|
| 304 |
+
pipeline.unet = torch.compile(pipeline.unet, mode="reduce-overhead", fullgraph=True)
|
| 305 |
+
```
|
| 306 |
+
|
| 307 |
+
For more tips on how to optimize your code to save memory and speed up inference, read the [Accelerate inference](../optimization/fp16) and [Reduce memory usage](../optimization/memory) guides.
|
tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/consisid.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 |
+
# ConsisID
|
| 13 |
+
|
| 14 |
+
[ConsisID](https://github.com/PKU-YuanGroup/ConsisID) is an identity-preserving text-to-video generation model that keeps the face consistent in the generated video by frequency decomposition. The main features of ConsisID are:
|
| 15 |
+
|
| 16 |
+
- Frequency decomposition: The characteristics of the DiT architecture are analyzed from the frequency domain perspective, and based on these characteristics, a reasonable control information injection method is designed.
|
| 17 |
+
- Consistency training strategy: A coarse-to-fine training strategy, dynamic masking loss, and dynamic cross-face loss further enhance the model's generalization ability and identity preservation performance.
|
| 18 |
+
- Inference without finetuning: Previous methods required case-by-case finetuning of the input ID before inference, leading to significant time and computational costs. In contrast, ConsisID is tuning-free.
|
| 19 |
+
|
| 20 |
+
This guide will walk you through using ConsisID for use cases.
|
| 21 |
+
|
| 22 |
+
## Load Model Checkpoints
|
| 23 |
+
|
| 24 |
+
Model weights may be stored in separate subfolders on the Hub or locally, in which case, you should use the [`~DiffusionPipeline.from_pretrained`] method.
|
| 25 |
+
|
| 26 |
+
```python
|
| 27 |
+
# !pip install consisid_eva_clip insightface facexlib
|
| 28 |
+
import torch
|
| 29 |
+
from diffusers import ConsisIDPipeline
|
| 30 |
+
from diffusers.pipelines.consisid.consisid_utils import prepare_face_models, process_face_embeddings_infer
|
| 31 |
+
from huggingface_hub import snapshot_download
|
| 32 |
+
|
| 33 |
+
# Download ckpts
|
| 34 |
+
snapshot_download(repo_id="BestWishYsh/ConsisID-preview", local_dir="BestWishYsh/ConsisID-preview")
|
| 35 |
+
|
| 36 |
+
# Load face helper model to preprocess input face image
|
| 37 |
+
face_helper_1, face_helper_2, face_clip_model, face_main_model, eva_transform_mean, eva_transform_std = prepare_face_models("BestWishYsh/ConsisID-preview", device="cuda", dtype=torch.bfloat16)
|
| 38 |
+
|
| 39 |
+
# Load consisid base model
|
| 40 |
+
pipe = ConsisIDPipeline.from_pretrained("BestWishYsh/ConsisID-preview", torch_dtype=torch.bfloat16)
|
| 41 |
+
pipe.to("cuda")
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
## Identity-Preserving Text-to-Video
|
| 45 |
+
|
| 46 |
+
For identity-preserving text-to-video, pass a text prompt and an image contain clear face (e.g., preferably half-body or full-body). By default, ConsisID generates a 720x480 video for the best results.
|
| 47 |
+
|
| 48 |
+
```python
|
| 49 |
+
from diffusers.utils import export_to_video
|
| 50 |
+
|
| 51 |
+
prompt = "The video captures a boy walking along a city street, filmed in black and white on a classic 35mm camera. His expression is thoughtful, his brow slightly furrowed as if he's lost in contemplation. The film grain adds a textured, timeless quality to the image, evoking a sense of nostalgia. Around him, the cityscape is filled with vintage buildings, cobblestone sidewalks, and softly blurred figures passing by, their outlines faint and indistinct. Streetlights cast a gentle glow, while shadows play across the boy's path, adding depth to the scene. The lighting highlights the boy's subtle smile, hinting at a fleeting moment of curiosity. The overall cinematic atmosphere, complete with classic film still aesthetics and dramatic contrasts, gives the scene an evocative and introspective feel."
|
| 52 |
+
image = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/consisid/consisid_input.png?download=true"
|
| 53 |
+
|
| 54 |
+
id_cond, id_vit_hidden, image, face_kps = process_face_embeddings_infer(face_helper_1, face_clip_model, face_helper_2, eva_transform_mean, eva_transform_std, face_main_model, "cuda", torch.bfloat16, image, is_align_face=True)
|
| 55 |
+
|
| 56 |
+
video = pipe(image=image, prompt=prompt, num_inference_steps=50, guidance_scale=6.0, use_dynamic_cfg=False, id_vit_hidden=id_vit_hidden, id_cond=id_cond, kps_cond=face_kps, generator=torch.Generator("cuda").manual_seed(42))
|
| 57 |
+
export_to_video(video.frames[0], "output.mp4", fps=8)
|
| 58 |
+
```
|
| 59 |
+
<table>
|
| 60 |
+
<tr>
|
| 61 |
+
<th style="text-align: center;">Face Image</th>
|
| 62 |
+
<th style="text-align: center;">Video</th>
|
| 63 |
+
<th style="text-align: center;">Description</th>
|
| 64 |
+
</tr>
|
| 65 |
+
<tr>
|
| 66 |
+
<td><img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/consisid/consisid_image_0.png?download=true" style="height: auto; width: 600px;"></td>
|
| 67 |
+
<td><img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/consisid/consisid_output_0.gif?download=true" style="height: auto; width: 2000px;"></td>
|
| 68 |
+
<td>The video, in a beautifully crafted animated style, features a confident woman riding a horse through a lush forest clearing. Her expression is focused yet serene as she adjusts her wide-brimmed hat with a practiced hand. She wears a flowy bohemian dress, which moves gracefully with the rhythm of the horse, the fabric flowing fluidly in the animated motion. The dappled sunlight filters through the trees, casting soft, painterly patterns on the forest floor. Her posture is poised, showing both control and elegance as she guides the horse with ease. The animation's gentle, fluid style adds a dreamlike quality to the scene, with the woman’s calm demeanor and the peaceful surroundings evoking a sense of freedom and harmony.</td>
|
| 69 |
+
</tr>
|
| 70 |
+
<tr>
|
| 71 |
+
<td><img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/consisid/consisid_image_1.png?download=true" style="height: auto; width: 600px;"></td>
|
| 72 |
+
<td><img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/consisid/consisid_output_1.gif?download=true" style="height: auto; width: 2000px;"></td>
|
| 73 |
+
<td>The video, in a captivating animated style, shows a woman standing in the center of a snowy forest, her eyes narrowed in concentration as she extends her hand forward. She is dressed in a deep blue cloak, her breath visible in the cold air, which is rendered with soft, ethereal strokes. A faint smile plays on her lips as she summons a wisp of ice magic, watching with focus as the surrounding trees and ground begin to shimmer and freeze, covered in delicate ice crystals. The animation’s fluid motion brings the magic to life, with the frost spreading outward in intricate, sparkling patterns. The environment is painted with soft, watercolor-like hues, enhancing the magical, dreamlike atmosphere. The overall mood is serene yet powerful, with the quiet winter air amplifying the delicate beauty of the frozen scene.</td>
|
| 74 |
+
</tr>
|
| 75 |
+
<tr>
|
| 76 |
+
<td><img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/consisid/consisid_image_2.png?download=true" style="height: auto; width: 600px;"></td>
|
| 77 |
+
<td><img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/consisid/consisid_output_2.gif?download=true" style="height: auto; width: 2000px;"></td>
|
| 78 |
+
<td>The animation features a whimsical portrait of a balloon seller standing in a gentle breeze, captured with soft, hazy brushstrokes that evoke the feel of a serene spring day. His face is framed by a gentle smile, his eyes squinting slightly against the sun, while a few wisps of hair flutter in the wind. He is dressed in a light, pastel-colored shirt, and the balloons around him sway with the wind, adding a sense of playfulness to the scene. The background blurs softly, with hints of a vibrant market or park, enhancing the light-hearted, yet tender mood of the moment.</td>
|
| 79 |
+
</tr>
|
| 80 |
+
<tr>
|
| 81 |
+
<td><img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/consisid/consisid_image_3.png?download=true" style="height: auto; width: 600px;"></td>
|
| 82 |
+
<td><img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/consisid/consisid_output_3.gif?download=true" style="height: auto; width: 2000px;"></td>
|
| 83 |
+
<td>The video captures a boy walking along a city street, filmed in black and white on a classic 35mm camera. His expression is thoughtful, his brow slightly furrowed as if he's lost in contemplation. The film grain adds a textured, timeless quality to the image, evoking a sense of nostalgia. Around him, the cityscape is filled with vintage buildings, cobblestone sidewalks, and softly blurred figures passing by, their outlines faint and indistinct. Streetlights cast a gentle glow, while shadows play across the boy's path, adding depth to the scene. The lighting highlights the boy's subtle smile, hinting at a fleeting moment of curiosity. The overall cinematic atmosphere, complete with classic film still aesthetics and dramatic contrasts, gives the scene an evocative and introspective feel.</td>
|
| 84 |
+
</tr>
|
| 85 |
+
<tr>
|
| 86 |
+
<td><img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/consisid/consisid_image_4.png?download=true" style="height: auto; width: 600px;"></td>
|
| 87 |
+
<td><img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/consisid/consisid_output_4.gif?download=true" style="height: auto; width: 2000px;"></td>
|
| 88 |
+
<td>The video features a baby wearing a bright superhero cape, standing confidently with arms raised in a powerful pose. The baby has a determined look on their face, with eyes wide and lips pursed in concentration, as if ready to take on a challenge. The setting appears playful, with colorful toys scattered around and a soft rug underfoot, while sunlight streams through a nearby window, highlighting the fluttering cape and adding to the impression of heroism. The overall atmosphere is lighthearted and fun, with the baby's expressions capturing a mix of innocence and an adorable attempt at bravery, as if truly ready to save the day.</td>
|
| 89 |
+
</tr>
|
| 90 |
+
</table>
|
| 91 |
+
|
| 92 |
+
## Resources
|
| 93 |
+
|
| 94 |
+
Learn more about ConsisID with the following resources.
|
| 95 |
+
- A [video](https://www.youtube.com/watch?v=PhlgC-bI5SQ) demonstrating ConsisID's main features.
|
| 96 |
+
- The research paper, [Identity-Preserving Text-to-Video Generation by Frequency Decomposition](https://hf.co/papers/2411.17440) for more details.
|
tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/controlling_generation.md
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# Controlled generation
|
| 14 |
+
|
| 15 |
+
Controlling outputs generated by diffusion models has been long pursued by the community and is now an active research topic. In many popular diffusion models, subtle changes in inputs, both images and text prompts, can drastically change outputs. In an ideal world we want to be able to control how semantics are preserved and changed.
|
| 16 |
+
|
| 17 |
+
Most examples of preserving semantics reduce to being able to accurately map a change in input to a change in output. I.e. adding an adjective to a subject in a prompt preserves the entire image, only modifying the changed subject. Or, image variation of a particular subject preserves the subject's pose.
|
| 18 |
+
|
| 19 |
+
Additionally, there are qualities of generated images that we would like to influence beyond semantic preservation. I.e. in general, we would like our outputs to be of good quality, adhere to a particular style, or be realistic.
|
| 20 |
+
|
| 21 |
+
We will document some of the techniques `diffusers` supports to control generation of diffusion models. Much is cutting edge research and can be quite nuanced. If something needs clarifying or you have a suggestion, don't hesitate to open a discussion on the [forum](https://discuss.huggingface.co/c/discussion-related-to-httpsgithubcomhuggingfacediffusers/63) or a [GitHub issue](https://github.com/huggingface/diffusers/issues).
|
| 22 |
+
|
| 23 |
+
We provide a high level explanation of how the generation can be controlled as well as a snippet of the technicals. For more in depth explanations on the technicals, the original papers which are linked from the pipelines are always the best resources.
|
| 24 |
+
|
| 25 |
+
Depending on the use case, one should choose a technique accordingly. In many cases, these techniques can be combined. For example, one can combine Textual Inversion with SEGA to provide more semantic guidance to the outputs generated using Textual Inversion.
|
| 26 |
+
|
| 27 |
+
Unless otherwise mentioned, these are techniques that work with existing models and don't require their own weights.
|
| 28 |
+
|
| 29 |
+
1. [InstructPix2Pix](#instruct-pix2pix)
|
| 30 |
+
2. [Pix2Pix Zero](#pix2pix-zero)
|
| 31 |
+
3. [Attend and Excite](#attend-and-excite)
|
| 32 |
+
4. [Semantic Guidance](#semantic-guidance-sega)
|
| 33 |
+
5. [Self-attention Guidance](#self-attention-guidance-sag)
|
| 34 |
+
6. [Depth2Image](#depth2image)
|
| 35 |
+
7. [MultiDiffusion Panorama](#multidiffusion-panorama)
|
| 36 |
+
8. [DreamBooth](#dreambooth)
|
| 37 |
+
9. [Textual Inversion](#textual-inversion)
|
| 38 |
+
10. [ControlNet](#controlnet)
|
| 39 |
+
11. [Prompt Weighting](#prompt-weighting)
|
| 40 |
+
12. [Custom Diffusion](#custom-diffusion)
|
| 41 |
+
13. [Model Editing](#model-editing)
|
| 42 |
+
14. [DiffEdit](#diffedit)
|
| 43 |
+
15. [T2I-Adapter](#t2i-adapter)
|
| 44 |
+
16. [FABRIC](#fabric)
|
| 45 |
+
|
| 46 |
+
For convenience, we provide a table to denote which methods are inference-only and which require fine-tuning/training.
|
| 47 |
+
|
| 48 |
+
| **Method** | **Inference only** | **Requires training /<br> fine-tuning** | **Comments** |
|
| 49 |
+
| :-------------------------------------------------: | :----------------: | :-------------------------------------: | :---------------------------------------------------------------------------------------------: |
|
| 50 |
+
| [InstructPix2Pix](#instruct-pix2pix) | ✅ | ❌ | Can additionally be<br>fine-tuned for better <br>performance on specific <br>edit instructions. |
|
| 51 |
+
| [Pix2Pix Zero](#pix2pix-zero) | ✅ | ❌ | |
|
| 52 |
+
| [Attend and Excite](#attend-and-excite) | ✅ | ❌ | |
|
| 53 |
+
| [Semantic Guidance](#semantic-guidance-sega) | ✅ | ❌ | |
|
| 54 |
+
| [Self-attention Guidance](#self-attention-guidance-sag) | ✅ | ❌ | |
|
| 55 |
+
| [Depth2Image](#depth2image) | ✅ | ❌ | |
|
| 56 |
+
| [MultiDiffusion Panorama](#multidiffusion-panorama) | ✅ | ❌ | |
|
| 57 |
+
| [DreamBooth](#dreambooth) | ❌ | ✅ | |
|
| 58 |
+
| [Textual Inversion](#textual-inversion) | ❌ | ✅ | |
|
| 59 |
+
| [ControlNet](#controlnet) | ✅ | ❌ | A ControlNet can be <br>trained/fine-tuned on<br>a custom conditioning. |
|
| 60 |
+
| [Prompt Weighting](#prompt-weighting) | ✅ | ❌ | |
|
| 61 |
+
| [Custom Diffusion](#custom-diffusion) | ❌ | ✅ | |
|
| 62 |
+
| [Model Editing](#model-editing) | ✅ | ❌ | |
|
| 63 |
+
| [DiffEdit](#diffedit) | ✅ | ❌ | |
|
| 64 |
+
| [T2I-Adapter](#t2i-adapter) | ✅ | ❌ | |
|
| 65 |
+
| [Fabric](#fabric) | ✅ | ❌ | |
|
| 66 |
+
## InstructPix2Pix
|
| 67 |
+
|
| 68 |
+
[Paper](https://huggingface.co/papers/2211.09800)
|
| 69 |
+
|
| 70 |
+
[InstructPix2Pix](../api/pipelines/pix2pix) is fine-tuned from Stable Diffusion to support editing input images. It takes as inputs an image and a prompt describing an edit, and it outputs the edited image.
|
| 71 |
+
InstructPix2Pix has been explicitly trained to work well with [InstructGPT](https://openai.com/blog/instruction-following/)-like prompts.
|
| 72 |
+
|
| 73 |
+
## Attend and Excite
|
| 74 |
+
|
| 75 |
+
[Paper](https://huggingface.co/papers/2301.13826)
|
| 76 |
+
|
| 77 |
+
[Attend and Excite](../api/pipelines/attend_and_excite) allows subjects in the prompt to be faithfully represented in the final image.
|
| 78 |
+
|
| 79 |
+
A set of token indices are given as input, corresponding to the subjects in the prompt that need to be present in the image. During denoising, each token index is guaranteed to have a minimum attention threshold for at least one patch of the image. The intermediate latents are iteratively optimized during the denoising process to strengthen the attention of the most neglected subject token until the attention threshold is passed for all subject tokens.
|
| 80 |
+
|
| 81 |
+
Like Pix2Pix Zero, Attend and Excite also involves a mini optimization loop (leaving the pre-trained weights untouched) in its pipeline and can require more memory than the usual [StableDiffusionPipeline](../api/pipelines/stable_diffusion/text2img).
|
| 82 |
+
|
| 83 |
+
## Semantic Guidance (SEGA)
|
| 84 |
+
|
| 85 |
+
[Paper](https://huggingface.co/papers/2301.12247)
|
| 86 |
+
|
| 87 |
+
[SEGA](../api/pipelines/semantic_stable_diffusion) allows applying or removing one or more concepts from an image. The strength of the concept can also be controlled. I.e. the smile concept can be used to incrementally increase or decrease the smile of a portrait.
|
| 88 |
+
|
| 89 |
+
Similar to how classifier free guidance provides guidance via empty prompt inputs, SEGA provides guidance on conceptual prompts. Multiple of these conceptual prompts can be applied simultaneously. Each conceptual prompt can either add or remove their concept depending on if the guidance is applied positively or negatively.
|
| 90 |
+
|
| 91 |
+
Unlike Pix2Pix Zero or Attend and Excite, SEGA directly interacts with the diffusion process instead of performing any explicit gradient-based optimization.
|
| 92 |
+
|
| 93 |
+
## Self-attention Guidance (SAG)
|
| 94 |
+
|
| 95 |
+
[Paper](https://huggingface.co/papers/2210.00939)
|
| 96 |
+
|
| 97 |
+
[Self-attention Guidance](../api/pipelines/self_attention_guidance) improves the general quality of images.
|
| 98 |
+
|
| 99 |
+
SAG provides guidance from predictions not conditioned on high-frequency details to fully conditioned images. The high frequency details are extracted out of the UNet self-attention maps.
|
| 100 |
+
|
| 101 |
+
## Depth2Image
|
| 102 |
+
|
| 103 |
+
[Project](https://huggingface.co/stabilityai/stable-diffusion-2-depth)
|
| 104 |
+
|
| 105 |
+
[Depth2Image](../api/pipelines/stable_diffusion/depth2img) is fine-tuned from Stable Diffusion to better preserve semantics for text guided image variation.
|
| 106 |
+
|
| 107 |
+
It conditions on a monocular depth estimate of the original image.
|
| 108 |
+
|
| 109 |
+
## MultiDiffusion Panorama
|
| 110 |
+
|
| 111 |
+
[Paper](https://huggingface.co/papers/2302.08113)
|
| 112 |
+
|
| 113 |
+
[MultiDiffusion Panorama](../api/pipelines/panorama) defines a new generation process over a pre-trained diffusion model. This process binds together multiple diffusion generation methods that can be readily applied to generate high quality and diverse images. Results adhere to user-provided controls, such as desired aspect ratio (e.g., panorama), and spatial guiding signals, ranging from tight segmentation masks to bounding boxes.
|
| 114 |
+
MultiDiffusion Panorama allows to generate high-quality images at arbitrary aspect ratios (e.g., panoramas).
|
| 115 |
+
|
| 116 |
+
## Fine-tuning your own models
|
| 117 |
+
|
| 118 |
+
In addition to pre-trained models, Diffusers has training scripts for fine-tuning models on user-provided data.
|
| 119 |
+
|
| 120 |
+
## DreamBooth
|
| 121 |
+
|
| 122 |
+
[Project](https://dreambooth.github.io/)
|
| 123 |
+
|
| 124 |
+
[DreamBooth](../training/dreambooth) fine-tunes a model to teach it about a new subject. I.e. a few pictures of a person can be used to generate images of that person in different styles.
|
| 125 |
+
|
| 126 |
+
## Textual Inversion
|
| 127 |
+
|
| 128 |
+
[Paper](https://huggingface.co/papers/2208.01618)
|
| 129 |
+
|
| 130 |
+
[Textual Inversion](../training/text_inversion) fine-tunes a model to teach it about a new concept. I.e. a few pictures of a style of artwork can be used to generate images in that style.
|
| 131 |
+
|
| 132 |
+
## ControlNet
|
| 133 |
+
|
| 134 |
+
[Paper](https://huggingface.co/papers/2302.05543)
|
| 135 |
+
|
| 136 |
+
[ControlNet](../api/pipelines/controlnet) is an auxiliary network which adds an extra condition.
|
| 137 |
+
There are 8 canonical pre-trained ControlNets trained on different conditionings such as edge detection, scribbles,
|
| 138 |
+
depth maps, and semantic segmentations.
|
| 139 |
+
|
| 140 |
+
## Prompt Weighting
|
| 141 |
+
|
| 142 |
+
[Prompt weighting](../using-diffusers/weighted_prompts) is a simple technique that puts more attention weight on certain parts of the text
|
| 143 |
+
input.
|
| 144 |
+
|
| 145 |
+
## Custom Diffusion
|
| 146 |
+
|
| 147 |
+
[Paper](https://huggingface.co/papers/2212.04488)
|
| 148 |
+
|
| 149 |
+
[Custom Diffusion](../training/custom_diffusion) only fine-tunes the cross-attention maps of a pre-trained
|
| 150 |
+
text-to-image diffusion model. It also allows for additionally performing Textual Inversion. It supports
|
| 151 |
+
multi-concept training by design. Like DreamBooth and Textual Inversion, Custom Diffusion is also used to
|
| 152 |
+
teach a pre-trained text-to-image diffusion model about new concepts to generate outputs involving the
|
| 153 |
+
concept(s) of interest.
|
| 154 |
+
|
| 155 |
+
## DiffEdit
|
| 156 |
+
|
| 157 |
+
[Paper](https://huggingface.co/papers/2210.11427)
|
| 158 |
+
|
| 159 |
+
[DiffEdit](../api/pipelines/diffedit) allows for semantic editing of input images along with
|
| 160 |
+
input prompts while preserving the original input images as much as possible.
|
| 161 |
+
|
| 162 |
+
## T2I-Adapter
|
| 163 |
+
|
| 164 |
+
[Paper](https://huggingface.co/papers/2302.08453)
|
| 165 |
+
|
| 166 |
+
[T2I-Adapter](../api/pipelines/stable_diffusion/adapter) is an auxiliary network which adds an extra condition.
|
| 167 |
+
There are 8 canonical pre-trained adapters trained on different conditionings such as edge detection, sketch,
|
| 168 |
+
depth maps, and semantic segmentations.
|
| 169 |
+
|
| 170 |
+
## Fabric
|
| 171 |
+
|
| 172 |
+
[Paper](https://huggingface.co/papers/2307.10159)
|
| 173 |
+
|
| 174 |
+
[Fabric](https://github.com/huggingface/diffusers/tree/442017ccc877279bcf24fbe92f92d3d0def191b6/examples/community#stable-diffusion-fabric-pipeline) is a training-free
|
| 175 |
+
approach applicable to a wide range of popular diffusion models, which exploits
|
| 176 |
+
the self-attention layer present in the most widely used architectures to condition
|
| 177 |
+
the diffusion process on a set of feedback images.
|
tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/controlnet.md
ADDED
|
@@ -0,0 +1,346 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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://huggingface.co/papers/2302.05543) is an adapter that enables controllable generation such as generating an image of a cat in a *specific pose* or following the lines in a sketch of a *specific* cat. It works by adding a smaller network of "zero convolution" layers and progressively training these to avoid disrupting with the original model. The original model parameters are frozen to avoid retraining it.
|
| 16 |
+
|
| 17 |
+
A ControlNet is conditioned on extra visual information or "structural controls" (canny edge, depth maps, human pose, etc.) that can be combined with text prompts to generate images that are guided by the visual input.
|
| 18 |
+
|
| 19 |
+
> [!TIP]
|
| 20 |
+
> ControlNets are available to many models such as [Flux](../api/pipelines/controlnet_flux), [Hunyuan-DiT](../api/pipelines/controlnet_hunyuandit), [Stable Diffusion 3](../api/pipelines/controlnet_sd3), and more. The examples in this guide use Flux and Stable Diffusion XL.
|
| 21 |
+
|
| 22 |
+
Load a ControlNet conditioned on a specific control, such as canny edge, and pass it to the pipeline in [`~DiffusionPipeline.from_pretrained`].
|
| 23 |
+
|
| 24 |
+
<hfoptions id="usage">
|
| 25 |
+
<hfoption id="text-to-image">
|
| 26 |
+
|
| 27 |
+
Generate a canny image with [opencv-python](https://github.com/opencv/opencv-python).
|
| 28 |
+
|
| 29 |
+
```py
|
| 30 |
+
import cv2
|
| 31 |
+
import numpy as np
|
| 32 |
+
from PIL import Image
|
| 33 |
+
from diffusers.utils import load_image
|
| 34 |
+
|
| 35 |
+
original_image = load_image(
|
| 36 |
+
"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/non-enhanced-prompt.png"
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
image = np.array(original_image)
|
| 40 |
+
|
| 41 |
+
low_threshold = 100
|
| 42 |
+
high_threshold = 200
|
| 43 |
+
|
| 44 |
+
image = cv2.Canny(image, low_threshold, high_threshold)
|
| 45 |
+
image = image[:, :, None]
|
| 46 |
+
image = np.concatenate([image, image, image], axis=2)
|
| 47 |
+
canny_image = Image.fromarray(image)
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
Pass the canny image to the pipeline. Use the `controlnet_conditioning_scale` parameter to determine how much weight to assign to the control.
|
| 51 |
+
|
| 52 |
+
```py
|
| 53 |
+
import torch
|
| 54 |
+
from diffusers.utils import load_image
|
| 55 |
+
from diffusers import FluxControlNetPipeline, FluxControlNetModel
|
| 56 |
+
|
| 57 |
+
controlnet = FluxControlNetModel.from_pretrained(
|
| 58 |
+
"InstantX/FLUX.1-dev-Controlnet-Canny", torch_dtype=torch.bfloat16
|
| 59 |
+
)
|
| 60 |
+
pipeline = FluxControlNetPipeline.from_pretrained(
|
| 61 |
+
"black-forest-labs/FLUX.1-dev", controlnet=controlnet, torch_dtype=torch.bfloat16
|
| 62 |
+
).to("cuda")
|
| 63 |
+
|
| 64 |
+
prompt = """
|
| 65 |
+
A photorealistic overhead image of a cat reclining sideways in a flamingo pool floatie holding a margarita.
|
| 66 |
+
The cat is floating leisurely in the pool and completely relaxed and happy.
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
pipeline(
|
| 70 |
+
prompt,
|
| 71 |
+
control_image=canny_image,
|
| 72 |
+
controlnet_conditioning_scale=0.5,
|
| 73 |
+
num_inference_steps=50,
|
| 74 |
+
guidance_scale=3.5,
|
| 75 |
+
).images[0]
|
| 76 |
+
```
|
| 77 |
+
|
| 78 |
+
<div style="display: flex; gap: 10px; justify-content: space-around; align-items: flex-end;">
|
| 79 |
+
<figure>
|
| 80 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/non-enhanced-prompt.png" width="300" alt="Generated image (prompt only)"/>
|
| 81 |
+
<figcaption style="text-align: center;">original image</figcaption>
|
| 82 |
+
</figure>
|
| 83 |
+
<figure>
|
| 84 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/canny-cat.png" width="300" alt="Control image (Canny edges)"/>
|
| 85 |
+
<figcaption style="text-align: center;">canny image</figcaption>
|
| 86 |
+
</figure>
|
| 87 |
+
<figure>
|
| 88 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/canny-cat-generated.png" width="300" alt="Generated image (ControlNet + prompt)"/>
|
| 89 |
+
<figcaption style="text-align: center;">generated image</figcaption>
|
| 90 |
+
</figure>
|
| 91 |
+
</div>
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
</hfoption>
|
| 95 |
+
<hfoption id="image-to-image">
|
| 96 |
+
|
| 97 |
+
Generate a depth map with a depth estimation pipeline from Transformers.
|
| 98 |
+
|
| 99 |
+
```py
|
| 100 |
+
import torch
|
| 101 |
+
import numpy as np
|
| 102 |
+
from PIL import Image
|
| 103 |
+
from transformers import DPTImageProcessor, DPTForDepthEstimation
|
| 104 |
+
from diffusers import ControlNetModel, StableDiffusionXLControlNetImg2ImgPipeline, AutoencoderKL
|
| 105 |
+
from diffusers.utils import load_image
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
depth_estimator = DPTForDepthEstimation.from_pretrained("Intel/dpt-hybrid-midas").to("cuda")
|
| 109 |
+
feature_extractor = DPTImageProcessor.from_pretrained("Intel/dpt-hybrid-midas")
|
| 110 |
+
|
| 111 |
+
def get_depth_map(image):
|
| 112 |
+
image = feature_extractor(images=image, return_tensors="pt").pixel_values.to("cuda")
|
| 113 |
+
with torch.no_grad(), torch.autocast("cuda"):
|
| 114 |
+
depth_map = depth_estimator(image).predicted_depth
|
| 115 |
+
|
| 116 |
+
depth_map = torch.nn.functional.interpolate(
|
| 117 |
+
depth_map.unsqueeze(1),
|
| 118 |
+
size=(1024, 1024),
|
| 119 |
+
mode="bicubic",
|
| 120 |
+
align_corners=False,
|
| 121 |
+
)
|
| 122 |
+
depth_min = torch.amin(depth_map, dim=[1, 2, 3], keepdim=True)
|
| 123 |
+
depth_max = torch.amax(depth_map, dim=[1, 2, 3], keepdim=True)
|
| 124 |
+
depth_map = (depth_map - depth_min) / (depth_max - depth_min)
|
| 125 |
+
image = torch.cat([depth_map] * 3, dim=1)
|
| 126 |
+
image = image.permute(0, 2, 3, 1).cpu().numpy()[0]
|
| 127 |
+
image = Image.fromarray((image * 255.0).clip(0, 255).astype(np.uint8))
|
| 128 |
+
return image
|
| 129 |
+
|
| 130 |
+
depth_image = get_depth_map(image)
|
| 131 |
+
```
|
| 132 |
+
|
| 133 |
+
Pass the depth map to the pipeline. Use the `controlnet_conditioning_scale` parameter to determine how much weight to assign to the control.
|
| 134 |
+
|
| 135 |
+
```py
|
| 136 |
+
controlnet = ControlNetModel.from_pretrained(
|
| 137 |
+
"diffusers/controlnet-depth-sdxl-1.0-small",
|
| 138 |
+
torch_dtype=torch.float16,
|
| 139 |
+
)
|
| 140 |
+
vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
|
| 141 |
+
pipeline = StableDiffusionXLControlNetImg2ImgPipeline.from_pretrained(
|
| 142 |
+
"stabilityai/stable-diffusion-xl-base-1.0",
|
| 143 |
+
controlnet=controlnet,
|
| 144 |
+
vae=vae,
|
| 145 |
+
torch_dtype=torch.float16,
|
| 146 |
+
).to("cuda")
|
| 147 |
+
|
| 148 |
+
prompt = """
|
| 149 |
+
A photorealistic overhead image of a cat reclining sideways in a flamingo pool floatie holding a margarita.
|
| 150 |
+
The cat is floating leisurely in the pool and completely relaxed and happy.
|
| 151 |
+
"""
|
| 152 |
+
image = load_image(
|
| 153 |
+
"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/non-enhanced-prompt.png"
|
| 154 |
+
).resize((1024, 1024))
|
| 155 |
+
controlnet_conditioning_scale = 0.5
|
| 156 |
+
pipeline(
|
| 157 |
+
prompt,
|
| 158 |
+
image=image,
|
| 159 |
+
control_image=depth_image,
|
| 160 |
+
controlnet_conditioning_scale=controlnet_conditioning_scale,
|
| 161 |
+
strength=0.99,
|
| 162 |
+
num_inference_steps=100,
|
| 163 |
+
).images[0]
|
| 164 |
+
```
|
| 165 |
+
|
| 166 |
+
<div style="display: flex; gap: 10px; justify-content: space-around; align-items: flex-end;">
|
| 167 |
+
<figure>
|
| 168 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/non-enhanced-prompt.png" width="300" alt="Generated image (prompt only)"/>
|
| 169 |
+
<figcaption style="text-align: center;">original image</figcaption>
|
| 170 |
+
</figure>
|
| 171 |
+
<figure>
|
| 172 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/sdxl_depth_image.png" width="300" alt="Control image (Canny edges)"/>
|
| 173 |
+
<figcaption style="text-align: center;">depth map</figcaption>
|
| 174 |
+
</figure>
|
| 175 |
+
<figure>
|
| 176 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/sdxl_depth_cat.png" width="300" alt="Generated image (ControlNet + prompt)"/>
|
| 177 |
+
<figcaption style="text-align: center;">generated image</figcaption>
|
| 178 |
+
</figure>
|
| 179 |
+
</div>
|
| 180 |
+
|
| 181 |
+
</hfoption>
|
| 182 |
+
<hfoption id="inpainting">
|
| 183 |
+
|
| 184 |
+
Generate a mask image and convert it to a tensor to mark the pixels in the original image as masked if the corresponding pixel in the mask image is over a certain threshold.
|
| 185 |
+
|
| 186 |
+
```py
|
| 187 |
+
import cv2
|
| 188 |
+
import torch
|
| 189 |
+
import numpy as np
|
| 190 |
+
from PIL import Image
|
| 191 |
+
from diffusers.utils import load_image
|
| 192 |
+
from diffusers import StableDiffusionXLControlNetInpaintPipeline, ControlNetModel
|
| 193 |
+
|
| 194 |
+
init_image = load_image(
|
| 195 |
+
"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/non-enhanced-prompt.png"
|
| 196 |
+
)
|
| 197 |
+
init_image = init_image.resize((1024, 1024))
|
| 198 |
+
mask_image = load_image(
|
| 199 |
+
"/content/cat_mask.png"
|
| 200 |
+
)
|
| 201 |
+
mask_image = mask_image.resize((1024, 1024))
|
| 202 |
+
|
| 203 |
+
def make_canny_condition(image):
|
| 204 |
+
image = np.array(image)
|
| 205 |
+
image = cv2.Canny(image, 100, 200)
|
| 206 |
+
image = image[:, :, None]
|
| 207 |
+
image = np.concatenate([image, image, image], axis=2)
|
| 208 |
+
image = Image.fromarray(image)
|
| 209 |
+
return image
|
| 210 |
+
|
| 211 |
+
control_image = make_canny_condition(init_image)
|
| 212 |
+
```
|
| 213 |
+
|
| 214 |
+
Pass the mask and control image to the pipeline. Use the `controlnet_conditioning_scale` parameter to determine how much weight to assign to the control.
|
| 215 |
+
|
| 216 |
+
```py
|
| 217 |
+
controlnet = ControlNetModel.from_pretrained(
|
| 218 |
+
"diffusers/controlnet-canny-sdxl-1.0", torch_dtype=torch.float16
|
| 219 |
+
)
|
| 220 |
+
pipeline = StableDiffusionXLControlNetInpaintPipeline.from_pretrained(
|
| 221 |
+
"stabilityai/stable-diffusion-xl-base-1.0", controlnet=controlnet, torch_dtype=torch.float16
|
| 222 |
+
)
|
| 223 |
+
pipeline(
|
| 224 |
+
"a cute and fluffy bunny rabbit",
|
| 225 |
+
num_inference_steps=100,
|
| 226 |
+
strength=0.99,
|
| 227 |
+
controlnet_conditioning_scale=0.5,
|
| 228 |
+
image=init_image,
|
| 229 |
+
mask_image=mask_image,
|
| 230 |
+
control_image=control_image,
|
| 231 |
+
).images[0]
|
| 232 |
+
```
|
| 233 |
+
|
| 234 |
+
<div style="display: flex; gap: 10px; justify-content: space-around; align-items: flex-end;">
|
| 235 |
+
<figure>
|
| 236 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/non-enhanced-prompt.png" width="300" alt="Generated image (prompt only)"/>
|
| 237 |
+
<figcaption style="text-align: center;">original image</figcaption>
|
| 238 |
+
</figure>
|
| 239 |
+
<figure>
|
| 240 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/cat_mask.png" width="300" alt="Control image (Canny edges)"/>
|
| 241 |
+
<figcaption style="text-align: center;">mask image</figcaption>
|
| 242 |
+
</figure>
|
| 243 |
+
<figure>
|
| 244 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/sdxl_rabbit_inpaint.png" width="300" alt="Generated image (ControlNet + prompt)"/>
|
| 245 |
+
<figcaption style="text-align: center;">generated image</figcaption>
|
| 246 |
+
</figure>
|
| 247 |
+
</div>
|
| 248 |
+
|
| 249 |
+
</hfoption>
|
| 250 |
+
</hfoptions>
|
| 251 |
+
|
| 252 |
+
## Multi-ControlNet
|
| 253 |
+
|
| 254 |
+
You can compose multiple ControlNet conditionings, such as canny image and a depth map, to create a *MultiControlNet*. For the best rersults, you should mask conditionings so they don't overlap and experiment with different `controlnet_conditioning_scale` parameters to adjust how much weight is assigned to each control input.
|
| 255 |
+
|
| 256 |
+
The example below composes a canny image and depth map.
|
| 257 |
+
|
| 258 |
+
Pass the ControlNets as a list to the pipeline and resize the images to the expected input size.
|
| 259 |
+
|
| 260 |
+
```py
|
| 261 |
+
import torch
|
| 262 |
+
from diffusers import StableDiffusionXLControlNetPipeline, ControlNetModel, AutoencoderKL
|
| 263 |
+
|
| 264 |
+
controlnets = [
|
| 265 |
+
ControlNetModel.from_pretrained(
|
| 266 |
+
"diffusers/controlnet-depth-sdxl-1.0-small", torch_dtype=torch.float16
|
| 267 |
+
),
|
| 268 |
+
ControlNetModel.from_pretrained(
|
| 269 |
+
"diffusers/controlnet-canny-sdxl-1.0", torch_dtype=torch.float16,
|
| 270 |
+
),
|
| 271 |
+
]
|
| 272 |
+
|
| 273 |
+
vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
|
| 274 |
+
pipeline = StableDiffusionXLControlNetPipeline.from_pretrained(
|
| 275 |
+
"stabilityai/stable-diffusion-xl-base-1.0", controlnet=controlnets, vae=vae, torch_dtype=torch.float16
|
| 276 |
+
).to("cuda")
|
| 277 |
+
|
| 278 |
+
prompt = """
|
| 279 |
+
a relaxed rabbit sitting on a striped towel next to a pool with a tropical drink nearby,
|
| 280 |
+
bright sunny day, vacation scene, 35mm photograph, film, professional, 4k, highly detailed
|
| 281 |
+
"""
|
| 282 |
+
negative_prompt = "lowres, bad anatomy, worst quality, low quality, deformed, ugly"
|
| 283 |
+
|
| 284 |
+
images = [canny_image.resize((1024, 1024)), depth_image.resize((1024, 1024))]
|
| 285 |
+
|
| 286 |
+
pipeline(
|
| 287 |
+
prompt,
|
| 288 |
+
negative_prompt=negative_prompt,
|
| 289 |
+
image=images,
|
| 290 |
+
num_inference_steps=100,
|
| 291 |
+
controlnet_conditioning_scale=[0.5, 0.5],
|
| 292 |
+
strength=0.7,
|
| 293 |
+
).images[0]
|
| 294 |
+
```
|
| 295 |
+
|
| 296 |
+
<div style="display: flex; gap: 10px; justify-content: space-around; align-items: flex-end;">
|
| 297 |
+
<figure>
|
| 298 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/canny-cat.png" width="300" alt="Generated image (prompt only)"/>
|
| 299 |
+
<figcaption style="text-align: center;">canny image</figcaption>
|
| 300 |
+
</figure>
|
| 301 |
+
<figure>
|
| 302 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/multicontrolnet_depth.png" width="300" alt="Control image (Canny edges)"/>
|
| 303 |
+
<figcaption style="text-align: center;">depth map</figcaption>
|
| 304 |
+
</figure>
|
| 305 |
+
<figure>
|
| 306 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/sdxl_multi_controlnet.png" width="300" alt="Generated image (ControlNet + prompt)"/>
|
| 307 |
+
<figcaption style="text-align: center;">generated image</figcaption>
|
| 308 |
+
</figure>
|
| 309 |
+
</div>
|
| 310 |
+
|
| 311 |
+
## guess_mode
|
| 312 |
+
|
| 313 |
+
[Guess mode](https://github.com/lllyasviel/ControlNet/discussions/188) generates an image from **only** the control input (canny edge, depth map, pose, etc.) and without guidance from a prompt. It adjusts the scale of the ControlNet's output residuals by a fixed ratio depending on block depth. The earlier `DownBlock` is only scaled by `0.1` and the `MidBlock` is fully scaled by `1.0`.
|
| 314 |
+
|
| 315 |
+
```py
|
| 316 |
+
import torch
|
| 317 |
+
from diffusers.utils import load_iamge
|
| 318 |
+
from diffusers import StableDiffusionXLControlNetPipeline, ControlNetModel
|
| 319 |
+
|
| 320 |
+
controlnet = ControlNetModel.from_pretrained(
|
| 321 |
+
"diffusers/controlnet-canny-sdxl-1.0", torch_dtype=torch.float16
|
| 322 |
+
)
|
| 323 |
+
pipeline = StableDiffusionXLControlNetPipeline.from_pretrained(
|
| 324 |
+
"stabilityai/stable-diffusion-xl-base-1.0",
|
| 325 |
+
controlnet=controlnet,
|
| 326 |
+
torch_dtype=torch.float16
|
| 327 |
+
).to("cuda")
|
| 328 |
+
|
| 329 |
+
canny_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/canny-cat.png")
|
| 330 |
+
pipeline(
|
| 331 |
+
"",
|
| 332 |
+
image=canny_image,
|
| 333 |
+
guess_mode=True
|
| 334 |
+
).images[0]
|
| 335 |
+
```
|
| 336 |
+
|
| 337 |
+
<div style="display: flex; gap: 10px; justify-content: space-around; align-items: flex-end;">
|
| 338 |
+
<figure>
|
| 339 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/canny-cat.png" width="300" alt="Control image (Canny edges)"/>
|
| 340 |
+
<figcaption style="text-align: center;">canny image</figcaption>
|
| 341 |
+
</figure>
|
| 342 |
+
<figure>
|
| 343 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/guess_mode.png" width="300" alt="Generated image (Guess mode)"/>
|
| 344 |
+
<figcaption style="text-align: center;">generated image</figcaption>
|
| 345 |
+
</figure>
|
| 346 |
+
</div>
|
tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/create_a_server.md
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
# Create a server
|
| 3 |
+
|
| 4 |
+
Diffusers' pipelines can be used as an inference engine for a server. It supports concurrent and multithreaded requests to generate images that may be requested by multiple users at the same time.
|
| 5 |
+
|
| 6 |
+
This guide will show you how to use the [`StableDiffusion3Pipeline`] in a server, but feel free to use any pipeline you want.
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
Start by navigating to the `examples/server` folder and installing all of the dependencies.
|
| 10 |
+
|
| 11 |
+
```py
|
| 12 |
+
pip install .
|
| 13 |
+
pip install -f requirements.txt
|
| 14 |
+
```
|
| 15 |
+
|
| 16 |
+
Launch the server with the following command.
|
| 17 |
+
|
| 18 |
+
```py
|
| 19 |
+
python server.py
|
| 20 |
+
```
|
| 21 |
+
|
| 22 |
+
The server is accessed at http://localhost:8000. You can curl this model with the following command.
|
| 23 |
+
```
|
| 24 |
+
curl -X POST -H "Content-Type: application/json" --data '{"model": "something", "prompt": "a kitten in front of a fireplace"}' http://localhost:8000/v1/images/generations
|
| 25 |
+
```
|
| 26 |
+
|
| 27 |
+
If you need to upgrade some dependencies, you can use either [pip-tools](https://github.com/jazzband/pip-tools) or [uv](https://github.com/astral-sh/uv). For example, upgrade the dependencies with `uv` using the following command.
|
| 28 |
+
|
| 29 |
+
```
|
| 30 |
+
uv pip compile requirements.in -o requirements.txt
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
The server is built with [FastAPI](https://fastapi.tiangolo.com/async/). The endpoint for `v1/images/generations` is shown below.
|
| 35 |
+
```py
|
| 36 |
+
@app.post("/v1/images/generations")
|
| 37 |
+
async def generate_image(image_input: TextToImageInput):
|
| 38 |
+
try:
|
| 39 |
+
loop = asyncio.get_event_loop()
|
| 40 |
+
scheduler = shared_pipeline.pipeline.scheduler.from_config(shared_pipeline.pipeline.scheduler.config)
|
| 41 |
+
pipeline = StableDiffusion3Pipeline.from_pipe(shared_pipeline.pipeline, scheduler=scheduler)
|
| 42 |
+
generator = torch.Generator(device="cuda")
|
| 43 |
+
generator.manual_seed(random.randint(0, 10000000))
|
| 44 |
+
output = await loop.run_in_executor(None, lambda: pipeline(image_input.prompt, generator = generator))
|
| 45 |
+
logger.info(f"output: {output}")
|
| 46 |
+
image_url = save_image(output.images[0])
|
| 47 |
+
return {"data": [{"url": image_url}]}
|
| 48 |
+
except Exception as e:
|
| 49 |
+
if isinstance(e, HTTPException):
|
| 50 |
+
raise e
|
| 51 |
+
elif hasattr(e, 'message'):
|
| 52 |
+
raise HTTPException(status_code=500, detail=e.message + traceback.format_exc())
|
| 53 |
+
raise HTTPException(status_code=500, detail=str(e) + traceback.format_exc())
|
| 54 |
+
```
|
| 55 |
+
The `generate_image` function is defined as asynchronous with the [async](https://fastapi.tiangolo.com/async/) keyword so that FastAPI knows that whatever is happening in this function won't necessarily return a result right away. Once it hits some point in the function that it needs to await some other [Task](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task), the main thread goes back to answering other HTTP requests. This is shown in the code below with the [await](https://fastapi.tiangolo.com/async/#async-and-await) keyword.
|
| 56 |
+
```py
|
| 57 |
+
output = await loop.run_in_executor(None, lambda: pipeline(image_input.prompt, generator = generator))
|
| 58 |
+
```
|
| 59 |
+
At this point, the execution of the pipeline function is placed onto a [new thread](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.run_in_executor), and the main thread performs other things until a result is returned from the `pipeline`.
|
| 60 |
+
|
| 61 |
+
Another important aspect of this implementation is creating a `pipeline` from `shared_pipeline`. The goal behind this is to avoid loading the underlying model more than once onto the GPU while still allowing for each new request that is running on a separate thread to have its own generator and scheduler. The scheduler, in particular, is not thread-safe, and it will cause errors like: `IndexError: index 21 is out of bounds for dimension 0 with size 21` if you try to use the same scheduler across multiple threads.
|
tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/custom_pipeline_overview.md
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# Community pipelines and components
|
| 16 |
+
|
| 17 |
+
Community pipelines are [`DiffusionPipeline`] classes that are different from the original paper implementation. They provide additional functionality or extend the original pipeline implementation.
|
| 18 |
+
|
| 19 |
+
> [!TIP]
|
| 20 |
+
> Check out the community pipelines in [diffusers/examples/community](https://github.com/huggingface/diffusers/tree/main/examples/community) with inference and training examples for how to use them.
|
| 21 |
+
|
| 22 |
+
Community pipelines are either stored on the Hub or the Diffusers' GitHub repository. Hub pipelines are completely customizable (scheduler, models, pipeline code, etc.) while GitHub pipelines are limited to only the custom pipeline code. Further compare the two community pipeline types in the table below.
|
| 23 |
+
|
| 24 |
+
| | GitHub | Hub |
|
| 25 |
+
|---|---|---|
|
| 26 |
+
| Usage | Same. | Same. |
|
| 27 |
+
| Review process | Open a Pull Request on GitHub and undergo a review process from the Diffusers team before merging. This option is slower. | Upload directly to a Hub repository without a review. This is the fastest option. |
|
| 28 |
+
| Visibility | Included in the official Diffusers repository and docs. | Included on your Hub profile and relies on your own usage and promotion to gain visibility. |
|
| 29 |
+
|
| 30 |
+
## custom_pipeline
|
| 31 |
+
|
| 32 |
+
Load either community pipeline types by passing the `custom_pipeline` argument to [`~DiffusionPipeline.from_pretrained`].
|
| 33 |
+
|
| 34 |
+
```py
|
| 35 |
+
import torch
|
| 36 |
+
from diffusers import DiffusionPipeline
|
| 37 |
+
|
| 38 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
| 39 |
+
"stabilityai/stable-diffusion-3-medium-diffusers",
|
| 40 |
+
custom_pipeline="pipeline_stable_diffusion_3_instruct_pix2pix",
|
| 41 |
+
torch_dtype=torch.float16,
|
| 42 |
+
device_map="cuda"
|
| 43 |
+
)
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
Add the `custom_revision` argument to [`~DiffusionPipeline.from_pretrained`] to load a community pipeline from a specific version (for example, `v0.30.0` or `main`). By default, community pipelines are loaded from the latest stable version of Diffusers.
|
| 47 |
+
|
| 48 |
+
```py
|
| 49 |
+
import torch
|
| 50 |
+
from diffusers import DiffusionPipeline
|
| 51 |
+
|
| 52 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
| 53 |
+
"stabilityai/stable-diffusion-3-medium-diffusers",
|
| 54 |
+
custom_pipeline="pipeline_stable_diffusion_3_instruct_pix2pix",
|
| 55 |
+
custom_revision="main"
|
| 56 |
+
torch_dtype=torch.float16,
|
| 57 |
+
device_map="cuda"
|
| 58 |
+
)
|
| 59 |
+
```
|
| 60 |
+
|
| 61 |
+
> [!WARNING]
|
| 62 |
+
> While the Hugging Face Hub [scans](https://huggingface.co/docs/hub/security-malware) files, you should still inspect the Hub pipeline code and make sure it is safe.
|
| 63 |
+
|
| 64 |
+
There are a few ways to load a community pipeline.
|
| 65 |
+
|
| 66 |
+
- Pass a path to `custom_pipeline` to load a local community pipeline. The directory must contain a `pipeline.py` file containing the pipeline class.
|
| 67 |
+
|
| 68 |
+
```py
|
| 69 |
+
import torch
|
| 70 |
+
from diffusers import DiffusionPipeline
|
| 71 |
+
|
| 72 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
| 73 |
+
"stabilityai/stable-diffusion-3-medium-diffusers",
|
| 74 |
+
custom_pipeline="path/to/pipeline_directory",
|
| 75 |
+
torch_dtype=torch.float16,
|
| 76 |
+
device_map="cuda"
|
| 77 |
+
)
|
| 78 |
+
```
|
| 79 |
+
|
| 80 |
+
- The `custom_pipeline` argument is also supported by [`~DiffusionPipeline.from_pipe`], which is useful for [reusing pipelines](./loading#reuse-a-pipeline) without using additional memory. It limits the memory usage to only the largest pipeline loaded.
|
| 81 |
+
|
| 82 |
+
```py
|
| 83 |
+
import torch
|
| 84 |
+
from diffusers import DiffusionPipeline
|
| 85 |
+
|
| 86 |
+
pipeline_sd = DiffusionPipeline.from_pretrained("emilianJR/CyberRealistic_V3", torch_dtype=torch.float16, device_map="cuda")
|
| 87 |
+
pipeline_lpw = DiffusionPipeline.from_pipe(
|
| 88 |
+
pipeline_sd, custom_pipeline="lpw_stable_diffusion", device_map="cuda"
|
| 89 |
+
)
|
| 90 |
+
```
|
| 91 |
+
|
| 92 |
+
The [`~DiffusionPipeline.from_pipe`] method is especially useful for loading community pipelines because many of them don't have pretrained weights. Community pipelines generally add a feature on top of an existing pipeline.
|
| 93 |
+
|
| 94 |
+
## Community components
|
| 95 |
+
|
| 96 |
+
Community components let users build pipelines with custom transformers, UNets, VAEs, and schedulers not supported by Diffusers. These components require Python module implementations.
|
| 97 |
+
|
| 98 |
+
This section shows how users can use community components to build a community pipeline using [showlab/show-1-base](https://huggingface.co/showlab/show-1-base) as an example.
|
| 99 |
+
|
| 100 |
+
1. Load the required components, the scheduler and image processor. The text encoder is generally imported from [Transformers](https://huggingface.co/docs/transformers/index).
|
| 101 |
+
|
| 102 |
+
```python
|
| 103 |
+
from transformers import T5Tokenizer, T5EncoderModel, CLIPImageProcessor
|
| 104 |
+
from diffusers import DPMSolverMultistepScheduler
|
| 105 |
+
|
| 106 |
+
pipeline_id = "showlab/show-1-base"
|
| 107 |
+
tokenizer = T5Tokenizer.from_pretrained(pipeline_id, subfolder="tokenizer")
|
| 108 |
+
text_encoder = T5EncoderModel.from_pretrained(pipeline_id, subfolder="text_encoder")
|
| 109 |
+
scheduler = DPMSolverMultistepScheduler.from_pretrained(pipe_id, subfolder="scheduler")
|
| 110 |
+
feature_extractor = CLIPImageProcessor.from_pretrained(pipe_id, subfolder="feature_extractor")
|
| 111 |
+
```
|
| 112 |
+
|
| 113 |
+
> [!WARNING]
|
| 114 |
+
> In steps 2 and 3, the custom [UNet](https://github.com/showlab/Show-1/blob/main/showone/models/unet_3d_condition.py) and [pipeline](https://huggingface.co/sayakpaul/show-1-base-with-code/blob/main/unet/showone_unet_3d_condition.py) implementation must match the format shown in their files for this example to work.
|
| 115 |
+
|
| 116 |
+
2. Load a [custom UNet](https://github.com/showlab/Show-1/blob/main/showone/models/unet_3d_condition.py) which is already implemented in [showone_unet_3d_condition.py](https://huggingface.co/sayakpaul/show-1-base-with-code/blob/main/unet/showone_unet_3d_condition.py). The [`UNet3DConditionModel`] class name is renamed to the custom implementation, `ShowOneUNet3DConditionModel`, because [`UNet3DConditionModel`] already exists in Diffusers. Any components required for `ShowOneUNet3DConditionModel` class should be placed in `showone_unet_3d_condition.py`.
|
| 117 |
+
|
| 118 |
+
```python
|
| 119 |
+
from showone_unet_3d_condition import ShowOneUNet3DConditionModel
|
| 120 |
+
|
| 121 |
+
unet = ShowOneUNet3DConditionModel.from_pretrained(pipeline_id, subfolder="unet")
|
| 122 |
+
```
|
| 123 |
+
|
| 124 |
+
3. Load the custom pipeline code (already implemented in [pipeline_t2v_base_pixel.py](https://huggingface.co/sayakpaul/show-1-base-with-code/blob/main/pipeline_t2v_base_pixel.py)). This script contains a custom `TextToVideoIFPipeline` class for generating videos from text. Like the custom UNet, any code required for `TextToVideIFPipeline` should be placed in `pipeline_t2v_base_pixel.py`.
|
| 125 |
+
|
| 126 |
+
Initialize `TextToVideoIFPipeline` with `ShowOneUNet3DConditionModel`.
|
| 127 |
+
|
| 128 |
+
```python
|
| 129 |
+
import torch
|
| 130 |
+
from pipeline_t2v_base_pixel import TextToVideoIFPipeline
|
| 131 |
+
|
| 132 |
+
pipeline = TextToVideoIFPipeline(
|
| 133 |
+
unet=unet,
|
| 134 |
+
text_encoder=text_encoder,
|
| 135 |
+
tokenizer=tokenizer,
|
| 136 |
+
scheduler=scheduler,
|
| 137 |
+
feature_extractor=feature_extractor,
|
| 138 |
+
device_map="cuda",
|
| 139 |
+
torch_dtype=torch.float16
|
| 140 |
+
)
|
| 141 |
+
```
|
| 142 |
+
|
| 143 |
+
4. Push the pipeline to the Hub to share with the community.
|
| 144 |
+
|
| 145 |
+
```python
|
| 146 |
+
pipeline.push_to_hub("custom-t2v-pipeline")
|
| 147 |
+
```
|
| 148 |
+
|
| 149 |
+
After the pipeline is successfully pushed, make the following changes.
|
| 150 |
+
|
| 151 |
+
- Change the `_class_name` attribute in [model_index.json](https://huggingface.co/sayakpaul/show-1-base-with-code/blob/main/model_index.json#L2) to `"pipeline_t2v_base_pixel"` and `"TextToVideoIFPipeline"`.
|
| 152 |
+
- Upload `showone_unet_3d_condition.py` to the [unet](https://huggingface.co/sayakpaul/show-1-base-with-code/blob/main/unet/showone_unet_3d_condition.py) subfolder.
|
| 153 |
+
- Upload `pipeline_t2v_base_pixel.py` to the pipeline [repository](https://huggingface.co/sayakpaul/show-1-base-with-code/tree/main).
|
| 154 |
+
|
| 155 |
+
To run inference, add the `trust_remote_code` argument while initializing the pipeline to handle all the "magic" behind the scenes.
|
| 156 |
+
|
| 157 |
+
```python
|
| 158 |
+
import torch
|
| 159 |
+
from diffusers import DiffusionPipeline
|
| 160 |
+
|
| 161 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
| 162 |
+
"<change-username>/<change-id>", trust_remote_code=True, torch_dtype=torch.float16
|
| 163 |
+
)
|
| 164 |
+
```
|
| 165 |
+
|
| 166 |
+
> [!WARNING]
|
| 167 |
+
> As an additional precaution with `trust_remote_code=True`, we strongly encourage passing a commit hash to the `revision` argument in [`~DiffusionPipeline.from_pretrained`] to make sure the code hasn't been updated with new malicious code (unless you fully trust the model owners).
|
| 168 |
+
|
| 169 |
+
## Resources
|
| 170 |
+
|
| 171 |
+
- Take a look at Issue [#841](https://github.com/huggingface/diffusers/issues/841) for more context about why we're adding community pipelines to help everyone easily share their work without being slowed down.
|
| 172 |
+
- Check out the [stabilityai/japanese-stable-diffusion-xl](https://huggingface.co/stabilityai/japanese-stable-diffusion-xl/) repository for an additional example of a community pipeline that also uses the `trust_remote_code` feature.
|
tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/depth2img.md
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# Text-guided depth-to-image generation
|
| 14 |
+
|
| 15 |
+
[[open-in-colab]]
|
| 16 |
+
|
| 17 |
+
The [`StableDiffusionDepth2ImgPipeline`] lets you pass a text prompt and an initial image to condition the generation of new images. In addition, you can also pass a `depth_map` to preserve the image structure. If no `depth_map` is provided, the pipeline automatically predicts the depth via an integrated [depth-estimation model](https://github.com/isl-org/MiDaS).
|
| 18 |
+
|
| 19 |
+
Start by creating an instance of the [`StableDiffusionDepth2ImgPipeline`]:
|
| 20 |
+
|
| 21 |
+
```python
|
| 22 |
+
import torch
|
| 23 |
+
from diffusers import StableDiffusionDepth2ImgPipeline
|
| 24 |
+
from diffusers.utils import load_image, make_image_grid
|
| 25 |
+
|
| 26 |
+
pipeline = StableDiffusionDepth2ImgPipeline.from_pretrained(
|
| 27 |
+
"stabilityai/stable-diffusion-2-depth",
|
| 28 |
+
torch_dtype=torch.float16,
|
| 29 |
+
use_safetensors=True,
|
| 30 |
+
).to("cuda")
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
Now pass your prompt to the pipeline. You can also pass a `negative_prompt` to prevent certain words from guiding how an image is generated:
|
| 34 |
+
|
| 35 |
+
```python
|
| 36 |
+
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 37 |
+
init_image = load_image(url)
|
| 38 |
+
prompt = "two tigers"
|
| 39 |
+
negative_prompt = "bad, deformed, ugly, bad anatomy"
|
| 40 |
+
image = pipeline(prompt=prompt, image=init_image, negative_prompt=negative_prompt, strength=0.7).images[0]
|
| 41 |
+
make_image_grid([init_image, image], rows=1, cols=2)
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
| Input | Output |
|
| 45 |
+
|---------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------|
|
| 46 |
+
| <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/coco-cats.png" width="500"/> | <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/depth2img-tigers.png" width="500"/> |
|
tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/diffedit.md
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# DiffEdit
|
| 14 |
+
|
| 15 |
+
[[open-in-colab]]
|
| 16 |
+
|
| 17 |
+
Image editing typically requires providing a mask of the area to be edited. DiffEdit automatically generates the mask for you based on a text query, making it easier overall to create a mask without image editing software. The DiffEdit algorithm works in three steps:
|
| 18 |
+
|
| 19 |
+
1. the diffusion model denoises an image conditioned on some query text and reference text which produces different noise estimates for different areas of the image; the difference is used to infer a mask to identify which area of the image needs to be changed to match the query text
|
| 20 |
+
2. the input image is encoded into latent space with DDIM
|
| 21 |
+
3. the latents are decoded with the diffusion model conditioned on the text query, using the mask as a guide such that pixels outside the mask remain the same as in the input image
|
| 22 |
+
|
| 23 |
+
This guide will show you how to use DiffEdit to edit images without manually creating a mask.
|
| 24 |
+
|
| 25 |
+
Before you begin, make sure you have the following libraries installed:
|
| 26 |
+
|
| 27 |
+
```py
|
| 28 |
+
# uncomment to install the necessary libraries in Colab
|
| 29 |
+
#!pip install -q diffusers transformers accelerate
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
The [`StableDiffusionDiffEditPipeline`] requires an image mask and a set of partially inverted latents. The image mask is generated from the [`~StableDiffusionDiffEditPipeline.generate_mask`] function, and includes two parameters, `source_prompt` and `target_prompt`. These parameters determine what to edit in the image. For example, if you want to change a bowl of *fruits* to a bowl of *pears*, then:
|
| 33 |
+
|
| 34 |
+
```py
|
| 35 |
+
source_prompt = "a bowl of fruits"
|
| 36 |
+
target_prompt = "a bowl of pears"
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
The partially inverted latents are generated from the [`~StableDiffusionDiffEditPipeline.invert`] function, and it is generally a good idea to include a `prompt` or *caption* describing the image to help guide the inverse latent sampling process. The caption can often be your `source_prompt`, but feel free to experiment with other text descriptions!
|
| 40 |
+
|
| 41 |
+
Let's load the pipeline, scheduler, inverse scheduler, and enable some optimizations to reduce memory usage:
|
| 42 |
+
|
| 43 |
+
```py
|
| 44 |
+
import torch
|
| 45 |
+
from diffusers import DDIMScheduler, DDIMInverseScheduler, StableDiffusionDiffEditPipeline
|
| 46 |
+
|
| 47 |
+
pipeline = StableDiffusionDiffEditPipeline.from_pretrained(
|
| 48 |
+
"stabilityai/stable-diffusion-2-1",
|
| 49 |
+
torch_dtype=torch.float16,
|
| 50 |
+
safety_checker=None,
|
| 51 |
+
use_safetensors=True,
|
| 52 |
+
)
|
| 53 |
+
pipeline.scheduler = DDIMScheduler.from_config(pipeline.scheduler.config)
|
| 54 |
+
pipeline.inverse_scheduler = DDIMInverseScheduler.from_config(pipeline.scheduler.config)
|
| 55 |
+
pipeline.enable_model_cpu_offload()
|
| 56 |
+
pipeline.enable_vae_slicing()
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
Load the image to edit:
|
| 60 |
+
|
| 61 |
+
```py
|
| 62 |
+
from diffusers.utils import load_image, make_image_grid
|
| 63 |
+
|
| 64 |
+
img_url = "https://github.com/Xiang-cd/DiffEdit-stable-diffusion/raw/main/assets/origin.png"
|
| 65 |
+
raw_image = load_image(img_url).resize((768, 768))
|
| 66 |
+
raw_image
|
| 67 |
+
```
|
| 68 |
+
|
| 69 |
+
Use the [`~StableDiffusionDiffEditPipeline.generate_mask`] function to generate the image mask. You'll need to pass it the `source_prompt` and `target_prompt` to specify what to edit in the image:
|
| 70 |
+
|
| 71 |
+
```py
|
| 72 |
+
from PIL import Image
|
| 73 |
+
|
| 74 |
+
source_prompt = "a bowl of fruits"
|
| 75 |
+
target_prompt = "a basket of pears"
|
| 76 |
+
mask_image = pipeline.generate_mask(
|
| 77 |
+
image=raw_image,
|
| 78 |
+
source_prompt=source_prompt,
|
| 79 |
+
target_prompt=target_prompt,
|
| 80 |
+
)
|
| 81 |
+
Image.fromarray((mask_image.squeeze()*255).astype("uint8"), "L").resize((768, 768))
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
Next, create the inverted latents and pass it a caption describing the image:
|
| 85 |
+
|
| 86 |
+
```py
|
| 87 |
+
inv_latents = pipeline.invert(prompt=source_prompt, image=raw_image).latents
|
| 88 |
+
```
|
| 89 |
+
|
| 90 |
+
Finally, pass the image mask and inverted latents to the pipeline. The `target_prompt` becomes the `prompt` now, and the `source_prompt` is used as the `negative_prompt`:
|
| 91 |
+
|
| 92 |
+
```py
|
| 93 |
+
output_image = pipeline(
|
| 94 |
+
prompt=target_prompt,
|
| 95 |
+
mask_image=mask_image,
|
| 96 |
+
image_latents=inv_latents,
|
| 97 |
+
negative_prompt=source_prompt,
|
| 98 |
+
).images[0]
|
| 99 |
+
mask_image = Image.fromarray((mask_image.squeeze()*255).astype("uint8"), "L").resize((768, 768))
|
| 100 |
+
make_image_grid([raw_image, mask_image, output_image], rows=1, cols=3)
|
| 101 |
+
```
|
| 102 |
+
|
| 103 |
+
<div class="flex gap-4">
|
| 104 |
+
<div>
|
| 105 |
+
<img class="rounded-xl" src="https://github.com/Xiang-cd/DiffEdit-stable-diffusion/raw/main/assets/origin.png"/>
|
| 106 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">original image</figcaption>
|
| 107 |
+
</div>
|
| 108 |
+
<div>
|
| 109 |
+
<img class="rounded-xl" src="https://github.com/Xiang-cd/DiffEdit-stable-diffusion/blob/main/assets/target.png?raw=true"/>
|
| 110 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">edited image</figcaption>
|
| 111 |
+
</div>
|
| 112 |
+
</div>
|
| 113 |
+
|
| 114 |
+
## Generate source and target embeddings
|
| 115 |
+
|
| 116 |
+
The source and target embeddings can be automatically generated with the [Flan-T5](https://huggingface.co/docs/transformers/model_doc/flan-t5) model instead of creating them manually.
|
| 117 |
+
|
| 118 |
+
Load the Flan-T5 model and tokenizer from the 🤗 Transformers library:
|
| 119 |
+
|
| 120 |
+
```py
|
| 121 |
+
import torch
|
| 122 |
+
from transformers import AutoTokenizer, T5ForConditionalGeneration
|
| 123 |
+
|
| 124 |
+
tokenizer = AutoTokenizer.from_pretrained("google/flan-t5-large")
|
| 125 |
+
model = T5ForConditionalGeneration.from_pretrained("google/flan-t5-large", device_map="auto", torch_dtype=torch.float16)
|
| 126 |
+
```
|
| 127 |
+
|
| 128 |
+
Provide some initial text to prompt the model to generate the source and target prompts.
|
| 129 |
+
|
| 130 |
+
```py
|
| 131 |
+
source_concept = "bowl"
|
| 132 |
+
target_concept = "basket"
|
| 133 |
+
|
| 134 |
+
source_text = f"Provide a caption for images containing a {source_concept}. "
|
| 135 |
+
"The captions should be in English and should be no longer than 150 characters."
|
| 136 |
+
|
| 137 |
+
target_text = f"Provide a caption for images containing a {target_concept}. "
|
| 138 |
+
"The captions should be in English and should be no longer than 150 characters."
|
| 139 |
+
```
|
| 140 |
+
|
| 141 |
+
Next, create a utility function to generate the prompts:
|
| 142 |
+
|
| 143 |
+
```py
|
| 144 |
+
@torch.no_grad()
|
| 145 |
+
def generate_prompts(input_prompt):
|
| 146 |
+
input_ids = tokenizer(input_prompt, return_tensors="pt").input_ids.to("cuda")
|
| 147 |
+
|
| 148 |
+
outputs = model.generate(
|
| 149 |
+
input_ids, temperature=0.8, num_return_sequences=16, do_sample=True, max_new_tokens=128, top_k=10
|
| 150 |
+
)
|
| 151 |
+
return tokenizer.batch_decode(outputs, skip_special_tokens=True)
|
| 152 |
+
|
| 153 |
+
source_prompts = generate_prompts(source_text)
|
| 154 |
+
target_prompts = generate_prompts(target_text)
|
| 155 |
+
print(source_prompts)
|
| 156 |
+
print(target_prompts)
|
| 157 |
+
```
|
| 158 |
+
|
| 159 |
+
> [!TIP]
|
| 160 |
+
> Check out the [generation strategy](https://huggingface.co/docs/transformers/main/en/generation_strategies) guide if you're interested in learning more about strategies for generating different quality text.
|
| 161 |
+
|
| 162 |
+
Load the text encoder model used by the [`StableDiffusionDiffEditPipeline`] to encode the text. You'll use the text encoder to compute the text embeddings:
|
| 163 |
+
|
| 164 |
+
```py
|
| 165 |
+
import torch
|
| 166 |
+
from diffusers import StableDiffusionDiffEditPipeline
|
| 167 |
+
|
| 168 |
+
pipeline = StableDiffusionDiffEditPipeline.from_pretrained(
|
| 169 |
+
"stabilityai/stable-diffusion-2-1", torch_dtype=torch.float16, use_safetensors=True
|
| 170 |
+
)
|
| 171 |
+
pipeline.enable_model_cpu_offload()
|
| 172 |
+
pipeline.enable_vae_slicing()
|
| 173 |
+
|
| 174 |
+
@torch.no_grad()
|
| 175 |
+
def embed_prompts(sentences, tokenizer, text_encoder, device="cuda"):
|
| 176 |
+
embeddings = []
|
| 177 |
+
for sent in sentences:
|
| 178 |
+
text_inputs = tokenizer(
|
| 179 |
+
sent,
|
| 180 |
+
padding="max_length",
|
| 181 |
+
max_length=tokenizer.model_max_length,
|
| 182 |
+
truncation=True,
|
| 183 |
+
return_tensors="pt",
|
| 184 |
+
)
|
| 185 |
+
text_input_ids = text_inputs.input_ids
|
| 186 |
+
prompt_embeds = text_encoder(text_input_ids.to(device), attention_mask=None)[0]
|
| 187 |
+
embeddings.append(prompt_embeds)
|
| 188 |
+
return torch.concatenate(embeddings, dim=0).mean(dim=0).unsqueeze(0)
|
| 189 |
+
|
| 190 |
+
source_embeds = embed_prompts(source_prompts, pipeline.tokenizer, pipeline.text_encoder)
|
| 191 |
+
target_embeds = embed_prompts(target_prompts, pipeline.tokenizer, pipeline.text_encoder)
|
| 192 |
+
```
|
| 193 |
+
|
| 194 |
+
Finally, pass the embeddings to the [`~StableDiffusionDiffEditPipeline.generate_mask`] and [`~StableDiffusionDiffEditPipeline.invert`] functions, and pipeline to generate the image:
|
| 195 |
+
|
| 196 |
+
```diff
|
| 197 |
+
from diffusers import DDIMInverseScheduler, DDIMScheduler
|
| 198 |
+
from diffusers.utils import load_image, make_image_grid
|
| 199 |
+
from PIL import Image
|
| 200 |
+
|
| 201 |
+
pipeline.scheduler = DDIMScheduler.from_config(pipeline.scheduler.config)
|
| 202 |
+
pipeline.inverse_scheduler = DDIMInverseScheduler.from_config(pipeline.scheduler.config)
|
| 203 |
+
|
| 204 |
+
img_url = "https://github.com/Xiang-cd/DiffEdit-stable-diffusion/raw/main/assets/origin.png"
|
| 205 |
+
raw_image = load_image(img_url).resize((768, 768))
|
| 206 |
+
|
| 207 |
+
mask_image = pipeline.generate_mask(
|
| 208 |
+
image=raw_image,
|
| 209 |
+
- source_prompt=source_prompt,
|
| 210 |
+
- target_prompt=target_prompt,
|
| 211 |
+
+ source_prompt_embeds=source_embeds,
|
| 212 |
+
+ target_prompt_embeds=target_embeds,
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
inv_latents = pipeline.invert(
|
| 216 |
+
- prompt=source_prompt,
|
| 217 |
+
+ prompt_embeds=source_embeds,
|
| 218 |
+
image=raw_image,
|
| 219 |
+
).latents
|
| 220 |
+
|
| 221 |
+
output_image = pipeline(
|
| 222 |
+
mask_image=mask_image,
|
| 223 |
+
image_latents=inv_latents,
|
| 224 |
+
- prompt=target_prompt,
|
| 225 |
+
- negative_prompt=source_prompt,
|
| 226 |
+
+ prompt_embeds=target_embeds,
|
| 227 |
+
+ negative_prompt_embeds=source_embeds,
|
| 228 |
+
).images[0]
|
| 229 |
+
mask_image = Image.fromarray((mask_image.squeeze()*255).astype("uint8"), "L")
|
| 230 |
+
make_image_grid([raw_image, mask_image, output_image], rows=1, cols=3)
|
| 231 |
+
```
|
| 232 |
+
|
| 233 |
+
## Generate a caption for inversion
|
| 234 |
+
|
| 235 |
+
While you can use the `source_prompt` as a caption to help generate the partially inverted latents, you can also use the [BLIP](https://huggingface.co/docs/transformers/model_doc/blip) model to automatically generate a caption.
|
| 236 |
+
|
| 237 |
+
Load the BLIP model and processor from the 🤗 Transformers library:
|
| 238 |
+
|
| 239 |
+
```py
|
| 240 |
+
import torch
|
| 241 |
+
from transformers import BlipForConditionalGeneration, BlipProcessor
|
| 242 |
+
|
| 243 |
+
processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
|
| 244 |
+
model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base", torch_dtype=torch.float16, low_cpu_mem_usage=True)
|
| 245 |
+
```
|
| 246 |
+
|
| 247 |
+
Create a utility function to generate a caption from the input image:
|
| 248 |
+
|
| 249 |
+
```py
|
| 250 |
+
@torch.no_grad()
|
| 251 |
+
def generate_caption(images, caption_generator, caption_processor):
|
| 252 |
+
text = "a photograph of"
|
| 253 |
+
|
| 254 |
+
inputs = caption_processor(images, text, return_tensors="pt").to(device="cuda", dtype=caption_generator.dtype)
|
| 255 |
+
caption_generator.to("cuda")
|
| 256 |
+
outputs = caption_generator.generate(**inputs, max_new_tokens=128)
|
| 257 |
+
|
| 258 |
+
# offload caption generator
|
| 259 |
+
caption_generator.to("cpu")
|
| 260 |
+
|
| 261 |
+
caption = caption_processor.batch_decode(outputs, skip_special_tokens=True)[0]
|
| 262 |
+
return caption
|
| 263 |
+
```
|
| 264 |
+
|
| 265 |
+
Load an input image and generate a caption for it using the `generate_caption` function:
|
| 266 |
+
|
| 267 |
+
```py
|
| 268 |
+
from diffusers.utils import load_image
|
| 269 |
+
|
| 270 |
+
img_url = "https://github.com/Xiang-cd/DiffEdit-stable-diffusion/raw/main/assets/origin.png"
|
| 271 |
+
raw_image = load_image(img_url).resize((768, 768))
|
| 272 |
+
caption = generate_caption(raw_image, model, processor)
|
| 273 |
+
```
|
| 274 |
+
|
| 275 |
+
<div class="flex justify-center">
|
| 276 |
+
<figure>
|
| 277 |
+
<img class="rounded-xl" src="https://github.com/Xiang-cd/DiffEdit-stable-diffusion/raw/main/assets/origin.png"/>
|
| 278 |
+
<figcaption class="text-center">generated caption: "a photograph of a bowl of fruit on a table"</figcaption>
|
| 279 |
+
</figure>
|
| 280 |
+
</div>
|
| 281 |
+
|
| 282 |
+
Now you can drop the caption into the [`~StableDiffusionDiffEditPipeline.invert`] function to generate the partially inverted latents!
|
tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/dreambooth.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 |
+
# DreamBooth
|
| 14 |
+
|
| 15 |
+
[DreamBooth](https://huggingface.co/papers/2208.12242) is a method for generating personalized images of a specific instance. It works by fine-tuning the model on 3-5 images of the subject (for example, a cat) that is associated with a unique identifier (`sks cat`). This allows you to use `sks cat` in your prompt to trigger the model to generate images of your cat in different settings, lighting, poses, and styles.
|
| 16 |
+
|
| 17 |
+
DreamBooth checkpoints are typically a few GBs in size because it contains the full model weights.
|
| 18 |
+
|
| 19 |
+
Load the DreamBooth checkpoint with [`~DiffusionPipeline.from_pretrained`] and include the unique identifier in the prompt to activate its generation.
|
| 20 |
+
|
| 21 |
+
```py
|
| 22 |
+
import torch
|
| 23 |
+
from diffusers import AutoPipelineForText2Image
|
| 24 |
+
|
| 25 |
+
pipeline = AutoPipelineForText2Image.from_pretrained(
|
| 26 |
+
"sd-dreambooth-library/herge-style",
|
| 27 |
+
torch_dtype=torch.float16
|
| 28 |
+
).to("cuda")
|
| 29 |
+
prompt = "A cute sks herge_style brown bear eating a slice of pizza, stunning color scheme, masterpiece, illustration"
|
| 30 |
+
pipeline(prompt).images[0]
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
<div class="flex justify-center">
|
| 34 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/load_dreambooth.png" />
|
| 35 |
+
</div>
|
tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/guiders.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 |
+
# 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 the [`~ComponentSpec.create`] method and [`~ModularPipeline.update_components`]. The example below changes the `guidance_scale` value.
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
```py
|
| 96 |
+
guider_spec = t2i_pipeline.get_component_spec("guider")
|
| 97 |
+
guider = guider_spec.create(guidance_scale=10)
|
| 98 |
+
t2i_pipeline.update_components(guider=guider)
|
| 99 |
+
```
|
| 100 |
+
|
| 101 |
+
## Uploading custom guiders
|
| 102 |
+
|
| 103 |
+
Call the [`~utils.PushToHubMixin.push_to_hub`] method on a custom guider to share it to the Hub.
|
| 104 |
+
|
| 105 |
+
```py
|
| 106 |
+
guider.push_to_hub("YiYiXu/modular-loader-t2i-guider", subfolder="pag_guider")
|
| 107 |
+
```
|
| 108 |
+
|
| 109 |
+
To make this guider available to the pipeline, either modify the `modular_model_index.json` file or use the [`~ModularPipeline.update_components`] method.
|
| 110 |
+
|
| 111 |
+
<hfoptions id="upload">
|
| 112 |
+
<hfoption id="modular_model_index.json">
|
| 113 |
+
|
| 114 |
+
Edit the `modular_model_index.json` file and add a loading specification for the guider by pointing to a folder containing the guider config.
|
| 115 |
+
|
| 116 |
+
```json
|
| 117 |
+
{
|
| 118 |
+
"guider": [
|
| 119 |
+
"diffusers",
|
| 120 |
+
"PerturbedAttentionGuidance",
|
| 121 |
+
{
|
| 122 |
+
"repo": "YiYiXu/modular-loader-t2i-guider",
|
| 123 |
+
"revision": null,
|
| 124 |
+
"subfolder": "pag_guider",
|
| 125 |
+
"type_hint": [
|
| 126 |
+
"diffusers",
|
| 127 |
+
"PerturbedAttentionGuidance"
|
| 128 |
+
],
|
| 129 |
+
"variant": null
|
| 130 |
+
}
|
| 131 |
+
],
|
| 132 |
+
```
|
| 133 |
+
|
| 134 |
+
</hfoption>
|
| 135 |
+
<hfoption id="update_components">
|
| 136 |
+
|
| 137 |
+
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.
|
| 138 |
+
|
| 139 |
+
> [!TIP]
|
| 140 |
+
> Changing the creation method will return text letting you know you're changing the creation type to `from_pretrained`.
|
| 141 |
+
> ```bash
|
| 142 |
+
> ModularPipeline.update_components: changing the default_creation_method of guider from from_config to from_pretrained.
|
| 143 |
+
> ```
|
| 144 |
+
|
| 145 |
+
```py
|
| 146 |
+
guider_spec = t2i_pipeline.get_component_spec("guider")
|
| 147 |
+
guider_spec.default_creation_method="from_pretrained"
|
| 148 |
+
guider_spec.pretrained_model_name_or_path="YiYiXu/modular-loader-t2i-guider"
|
| 149 |
+
guider_spec.subfolder="pag_guider"
|
| 150 |
+
pag_guider = guider_spec.load()
|
| 151 |
+
t2i_pipeline.update_components(guider=pag_guider)
|
| 152 |
+
```
|
| 153 |
+
|
| 154 |
+
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.
|
| 155 |
+
|
| 156 |
+
```py
|
| 157 |
+
t2i_pipeline.push_to_hub("YiYiXu/modular-doc-guider")
|
| 158 |
+
```
|
| 159 |
+
|
| 160 |
+
</hfoption>
|
| 161 |
+
</hfoptions>
|
tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/helios.md
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# Helios
|
| 13 |
+
|
| 14 |
+
[Helios](https://github.com/PKU-YuanGroup/Helios) is the first 14B video generation model that runs at 19.5 FPS on a single NVIDIA H100 GPU and supports minute-scale generation while matching the quality of a strong baseline, natively integrating T2V, I2V, and V2V tasks within a unified architecture. The main features of Helios are:
|
| 15 |
+
|
| 16 |
+
- Without commonly used anti-drifting strategies (eg, self-forcing, error-banks, keyframe sampling, or inverted sampling), Helios generates minute-scale videos with high quality and strong coherence.
|
| 17 |
+
- Without standard acceleration techniques (eg, KV-cache, causal masking, sparse/linear attention, TinyVAE, progressive noise schedules, hidden-state caching, or quantization), Helios achieves 19.5 FPS in end-to-end inference for a 14B video generation model on a single H100 GPU.
|
| 18 |
+
- Introducing optimizations that improve both training and inference throughput while reducing memory consumption. These changes enable training a 14B video generation model without parallelism or sharding infrastructure, with batch sizes comparable to image models.
|
| 19 |
+
|
| 20 |
+
This guide will walk you through using Helios for use cases.
|
| 21 |
+
|
| 22 |
+
## Load Model Checkpoints
|
| 23 |
+
|
| 24 |
+
Model weights may be stored in separate subfolders on the Hub or locally, in which case, you should use the [`~DiffusionPipeline.from_pretrained`] method.
|
| 25 |
+
|
| 26 |
+
```python
|
| 27 |
+
import torch
|
| 28 |
+
from diffusers import HeliosPipeline, HeliosPyramidPipeline
|
| 29 |
+
from huggingface_hub import snapshot_download
|
| 30 |
+
|
| 31 |
+
# For Best Quality
|
| 32 |
+
snapshot_download(repo_id="BestWishYsh/Helios-Base", local_dir="BestWishYsh/Helios-Base")
|
| 33 |
+
pipe = HeliosPipeline.from_pretrained("BestWishYsh/Helios-Base", torch_dtype=torch.bfloat16)
|
| 34 |
+
pipe.to("cuda")
|
| 35 |
+
|
| 36 |
+
# Intermediate Weight
|
| 37 |
+
snapshot_download(repo_id="BestWishYsh/Helios-Mid", local_dir="BestWishYsh/Helios-Mid")
|
| 38 |
+
pipe = HeliosPyramidPipeline.from_pretrained("BestWishYsh/Helios-Mid", torch_dtype=torch.bfloat16)
|
| 39 |
+
pipe.to("cuda")
|
| 40 |
+
|
| 41 |
+
# For Best Efficiency
|
| 42 |
+
snapshot_download(repo_id="BestWishYsh/Helios-Distilled", local_dir="BestWishYsh/Helios-Distilled")
|
| 43 |
+
pipe = HeliosPyramidPipeline.from_pretrained("BestWishYsh/Helios-Distilled", torch_dtype=torch.bfloat16)
|
| 44 |
+
pipe.to("cuda")
|
| 45 |
+
```
|
| 46 |
+
|
| 47 |
+
## Text-to-Video Showcases
|
| 48 |
+
|
| 49 |
+
<table>
|
| 50 |
+
<tr>
|
| 51 |
+
<th style="text-align: center;">Prompt</th>
|
| 52 |
+
<th style="text-align: center;">Generated Video</th>
|
| 53 |
+
</tr>
|
| 54 |
+
<tr>
|
| 55 |
+
<td><small>A Viking warrior driving a modern city bus filled with passengers. The Viking has long blonde hair tied back, a beard, and is adorned with a fur-lined helmet and armor. He wears a traditional tunic and trousers, but also sports a seatbelt as he focuses on navigating the busy streets. The interior of the bus is typical, with rows of seats occupied by diverse passengers going about their daily routines. The exterior shots show the bustling urban environment, including tall buildings and traffic. Medium shot focusing on the Viking at the wheel, with occasional close-ups of his determined expression.
|
| 56 |
+
</small></td>
|
| 57 |
+
<td>
|
| 58 |
+
<video width="4000" controls>
|
| 59 |
+
<source src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/helios/t2v_showcases1.mp4" type="video/mp4">
|
| 60 |
+
</video>
|
| 61 |
+
</td>
|
| 62 |
+
</tr>
|
| 63 |
+
<tr>
|
| 64 |
+
<td><small>A documentary-style nature photography shot from a camera truck moving to the left, capturing a crab quickly scurrying into its burrow. The crab has a hard, greenish-brown shell and long claws, moving with determined speed across the sandy ground. Its body is slightly arched as it burrows into the sand, leaving a small trail behind. The background shows a shallow beach with scattered rocks and seashells, and the horizon features a gentle curve of the coastline. The photo has a natural and realistic texture, emphasizing the crab's natural movement and the texture of the sand. A close-up shot from a slightly elevated angle.
|
| 65 |
+
</small></td>
|
| 66 |
+
<td>
|
| 67 |
+
<video width="4000" controls>
|
| 68 |
+
<source src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/helios/t2v_showcases2.mp4" type="video/mp4">
|
| 69 |
+
</video>
|
| 70 |
+
</td>
|
| 71 |
+
</tr>
|
| 72 |
+
</table>
|
| 73 |
+
|
| 74 |
+
## Image-to-Video Showcases
|
| 75 |
+
|
| 76 |
+
<table>
|
| 77 |
+
<tr>
|
| 78 |
+
<th style="text-align: center;">Image</th>
|
| 79 |
+
<th style="text-align: center;">Prompt</th>
|
| 80 |
+
<th style="text-align: center;">Generated Video</th>
|
| 81 |
+
</tr>
|
| 82 |
+
<tr>
|
| 83 |
+
<td><img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/helios/i2v_showcases1.jpg" style="height: auto; width: 300px;"></td>
|
| 84 |
+
<td><small>A sleek red Kia car speeds along a rural road under a cloudy sky, its modern design and dynamic movement emphasized by the blurred motion of the surrounding fields and trees stretching into the distance. The car's glossy exterior reflects the overcast sky, highlighting its aerodynamic shape and sporty stance. The license plate reads "KIA 626," and the vehicle's headlights are on, adding to the sense of motion and energy. The road curves gently, with the car positioned slightly off-center, creating a sense of forward momentum. A dynamic front three-quarter view captures the car's powerful presence against the serene backdrop of rolling hills and scattered trees.
|
| 85 |
+
</small></td>
|
| 86 |
+
<td>
|
| 87 |
+
<video width="2000" controls>
|
| 88 |
+
<source src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/helios/i2v_showcases1.mp4" type="video/mp4">
|
| 89 |
+
</video>
|
| 90 |
+
</td>
|
| 91 |
+
</tr>
|
| 92 |
+
<tr>
|
| 93 |
+
<td><img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/helios/i2v_showcases2.jpg" style="height: auto; width: 300px;"></td>
|
| 94 |
+
<td><small>A close-up captures a fluffy orange cat with striking green eyes and white whiskers, gazing intently towards the camera. The cat's fur is soft and well-groomed, with a mix of warm orange and cream tones. Its large, expressive eyes are a vivid green, reflecting curiosity and alertness. The cat's nose is small and pink, and its mouth is slightly open, revealing a hint of its pink tongue. The background is softly blurred, suggesting a cozy indoor setting with neutral tones. The photo has a shallow depth of field, focusing sharply on the cat's face while the background remains out of focus. A close-up shot from a slightly elevated perspective.
|
| 95 |
+
</small></td>
|
| 96 |
+
<td>
|
| 97 |
+
<video width="2000" controls>
|
| 98 |
+
<source src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/helios/i2v_showcases2.mp4" type="video/mp4">
|
| 99 |
+
</video>
|
| 100 |
+
</td>
|
| 101 |
+
</tr>
|
| 102 |
+
</table>
|
| 103 |
+
|
| 104 |
+
## Interactive-Video Showcases
|
| 105 |
+
|
| 106 |
+
<table>
|
| 107 |
+
<tr>
|
| 108 |
+
<th style="text-align: center;">Prompt</th>
|
| 109 |
+
<th style="text-align: center;">Generated Video</th>
|
| 110 |
+
</tr>
|
| 111 |
+
<tr>
|
| 112 |
+
<td><small>The prompt can be found <a href="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/helios/interactive_showcases1.txt">here</a></small></td>
|
| 113 |
+
<td>
|
| 114 |
+
<video width="680" controls>
|
| 115 |
+
<source src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/helios/interactive_showcases1.mp4" type="video/mp4">
|
| 116 |
+
</video>
|
| 117 |
+
</td>
|
| 118 |
+
</tr>
|
| 119 |
+
<tr>
|
| 120 |
+
<td><small>The prompt can be found <a href="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/helios/interactive_showcases2.txt">here</a></small></td>
|
| 121 |
+
<td>
|
| 122 |
+
<video width="680" controls>
|
| 123 |
+
<source src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/helios/interactive_showcases2.mp4" type="video/mp4">
|
| 124 |
+
</video>
|
| 125 |
+
</td>
|
| 126 |
+
</tr>
|
| 127 |
+
</table>
|
| 128 |
+
|
| 129 |
+
## Resources
|
| 130 |
+
|
| 131 |
+
Learn more about Helios with the following resources.
|
| 132 |
+
- Watch [video1](https://www.youtube.com/watch?v=vd_AgHtOUFQ) and [video2](https://www.youtube.com/watch?v=1GeIU2Dn7UY) for a demonstration of Helios's key features.
|
| 133 |
+
- The research paper, [Helios: Real Real-Time Long Video Generation Model](https://huggingface.co/papers/2603.04379) for more details.
|
tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/image_quality.md
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# FreeU
|
| 14 |
+
|
| 15 |
+
[FreeU](https://hf.co/papers/2309.11497) improves image details by rebalancing the UNet's backbone and skip connection weights. The skip connections can cause the model to overlook some of the backbone semantics which may lead to unnatural image details in the generated image. This technique does not require any additional training and can be applied on the fly during inference for tasks like image-to-image and text-to-video.
|
| 16 |
+
|
| 17 |
+
Use the [`~pipelines.StableDiffusionMixin.enable_freeu`] method on your pipeline and configure the scaling factors for the backbone (`b1` and `b2`) and skip connections (`s1` and `s2`). The number after each scaling factor corresponds to the stage in the UNet where the factor is applied. Take a look at the [FreeU](https://github.com/ChenyangSi/FreeU#parameters) repository for reference hyperparameters for different models.
|
| 18 |
+
|
| 19 |
+
<hfoptions id="freeu">
|
| 20 |
+
<hfoption id="Stable Diffusion v1-5">
|
| 21 |
+
|
| 22 |
+
```py
|
| 23 |
+
import torch
|
| 24 |
+
from diffusers import DiffusionPipeline
|
| 25 |
+
|
| 26 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
| 27 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16, safety_checker=None
|
| 28 |
+
).to("cuda")
|
| 29 |
+
pipeline.enable_freeu(s1=0.9, s2=0.2, b1=1.5, b2=1.6)
|
| 30 |
+
generator = torch.Generator(device="cpu").manual_seed(33)
|
| 31 |
+
prompt = ""
|
| 32 |
+
image = pipeline(prompt, generator=generator).images[0]
|
| 33 |
+
image
|
| 34 |
+
```
|
| 35 |
+
|
| 36 |
+
<div class="flex gap-4">
|
| 37 |
+
<div>
|
| 38 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/sdv15-no-freeu.png"/>
|
| 39 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">FreeU disabled</figcaption>
|
| 40 |
+
</div>
|
| 41 |
+
<div>
|
| 42 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/sdv15-freeu.png"/>
|
| 43 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">FreeU enabled</figcaption>
|
| 44 |
+
</div>
|
| 45 |
+
</div>
|
| 46 |
+
|
| 47 |
+
</hfoption>
|
| 48 |
+
<hfoption id="Stable Diffusion v2-1">
|
| 49 |
+
|
| 50 |
+
```py
|
| 51 |
+
import torch
|
| 52 |
+
from diffusers import DiffusionPipeline
|
| 53 |
+
|
| 54 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
| 55 |
+
"stabilityai/stable-diffusion-2-1", torch_dtype=torch.float16, safety_checker=None
|
| 56 |
+
).to("cuda")
|
| 57 |
+
pipeline.enable_freeu(s1=0.9, s2=0.2, b1=1.4, b2=1.6)
|
| 58 |
+
generator = torch.Generator(device="cpu").manual_seed(80)
|
| 59 |
+
prompt = "A squirrel eating a burger"
|
| 60 |
+
image = pipeline(prompt, generator=generator).images[0]
|
| 61 |
+
image
|
| 62 |
+
```
|
| 63 |
+
|
| 64 |
+
<div class="flex gap-4">
|
| 65 |
+
<div>
|
| 66 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/sdv21-no-freeu.png"/>
|
| 67 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">FreeU disabled</figcaption>
|
| 68 |
+
</div>
|
| 69 |
+
<div>
|
| 70 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/sdv21-freeu.png"/>
|
| 71 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">FreeU enabled</figcaption>
|
| 72 |
+
</div>
|
| 73 |
+
</div>
|
| 74 |
+
|
| 75 |
+
</hfoption>
|
| 76 |
+
<hfoption id="Stable Diffusion XL">
|
| 77 |
+
|
| 78 |
+
```py
|
| 79 |
+
import torch
|
| 80 |
+
from diffusers import DiffusionPipeline
|
| 81 |
+
|
| 82 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
| 83 |
+
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16,
|
| 84 |
+
).to("cuda")
|
| 85 |
+
pipeline.enable_freeu(s1=0.9, s2=0.2, b1=1.3, b2=1.4)
|
| 86 |
+
generator = torch.Generator(device="cpu").manual_seed(13)
|
| 87 |
+
prompt = "A squirrel eating a burger"
|
| 88 |
+
image = pipeline(prompt, generator=generator).images[0]
|
| 89 |
+
image
|
| 90 |
+
```
|
| 91 |
+
|
| 92 |
+
<div class="flex gap-4">
|
| 93 |
+
<div>
|
| 94 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/sdxl-no-freeu.png"/>
|
| 95 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">FreeU disabled</figcaption>
|
| 96 |
+
</div>
|
| 97 |
+
<div>
|
| 98 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/sdxl-freeu.png"/>
|
| 99 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">FreeU enabled</figcaption>
|
| 100 |
+
</div>
|
| 101 |
+
</div>
|
| 102 |
+
|
| 103 |
+
</hfoption>
|
| 104 |
+
<hfoption id="Zeroscope">
|
| 105 |
+
|
| 106 |
+
```py
|
| 107 |
+
import torch
|
| 108 |
+
from diffusers import DiffusionPipeline
|
| 109 |
+
from diffusers.utils import export_to_video
|
| 110 |
+
|
| 111 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
| 112 |
+
"damo-vilab/text-to-video-ms-1.7b", torch_dtype=torch.float16
|
| 113 |
+
).to("cuda")
|
| 114 |
+
# values come from https://github.com/lyn-rgb/FreeU_Diffusers#video-pipelines
|
| 115 |
+
pipeline.enable_freeu(b1=1.2, b2=1.4, s1=0.9, s2=0.2)
|
| 116 |
+
prompt = "Confident teddy bear surfer rides the wave in the tropics"
|
| 117 |
+
generator = torch.Generator(device="cpu").manual_seed(47)
|
| 118 |
+
video_frames = pipeline(prompt, generator=generator).frames[0]
|
| 119 |
+
export_to_video(video_frames, "teddy_bear.mp4", fps=10)
|
| 120 |
+
```
|
| 121 |
+
|
| 122 |
+
<div class="flex gap-4">
|
| 123 |
+
<div>
|
| 124 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/video-no-freeu.gif"/>
|
| 125 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">FreeU disabled</figcaption>
|
| 126 |
+
</div>
|
| 127 |
+
<div>
|
| 128 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/video-freeu.gif"/>
|
| 129 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">FreeU enabled</figcaption>
|
| 130 |
+
</div>
|
| 131 |
+
</div>
|
| 132 |
+
|
| 133 |
+
</hfoption>
|
| 134 |
+
</hfoptions>
|
| 135 |
+
|
| 136 |
+
Call the [`~pipelines.StableDiffusionMixin.disable_freeu`] method to disable FreeU.
|
| 137 |
+
|
| 138 |
+
```py
|
| 139 |
+
pipeline.disable_freeu()
|
| 140 |
+
```
|
tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/img2img.md
ADDED
|
@@ -0,0 +1,596 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# Image-to-image
|
| 14 |
+
|
| 15 |
+
[[open-in-colab]]
|
| 16 |
+
|
| 17 |
+
Image-to-image is similar to [text-to-image](conditional_image_generation), but in addition to a prompt, you can also pass an initial image as a starting point for the diffusion process. The initial image is encoded to latent space and noise is added to it. Then the latent diffusion model takes a prompt and the noisy latent image, predicts the added noise, and removes the predicted noise from the initial latent image to get the new latent image. Lastly, a decoder decodes the new latent image back into an image.
|
| 18 |
+
|
| 19 |
+
With 🤗 Diffusers, this is as easy as 1-2-3:
|
| 20 |
+
|
| 21 |
+
1. Load a checkpoint into the [`AutoPipelineForImage2Image`] class; this pipeline automatically handles loading the correct pipeline class based on the checkpoint:
|
| 22 |
+
|
| 23 |
+
```py
|
| 24 |
+
import torch
|
| 25 |
+
from diffusers import AutoPipelineForImage2Image
|
| 26 |
+
from diffusers.utils import load_image, make_image_grid
|
| 27 |
+
|
| 28 |
+
pipeline = AutoPipelineForImage2Image.from_pretrained(
|
| 29 |
+
"kandinsky-community/kandinsky-2-2-decoder", torch_dtype=torch.float16, use_safetensors=True
|
| 30 |
+
)
|
| 31 |
+
pipeline.enable_model_cpu_offload()
|
| 32 |
+
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
|
| 33 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 34 |
+
```
|
| 35 |
+
|
| 36 |
+
> [!TIP]
|
| 37 |
+
> You'll notice throughout the guide, we use [`~DiffusionPipeline.enable_model_cpu_offload`] and [`~DiffusionPipeline.enable_xformers_memory_efficient_attention`], to save memory and increase inference speed. If you're using PyTorch 2.0, then you don't need to call [`~DiffusionPipeline.enable_xformers_memory_efficient_attention`] on your pipeline because it'll already be using PyTorch 2.0's native [scaled-dot product attention](../optimization/fp16#scaled-dot-product-attention).
|
| 38 |
+
|
| 39 |
+
2. Load an image to pass to the pipeline:
|
| 40 |
+
|
| 41 |
+
```py
|
| 42 |
+
init_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/cat.png")
|
| 43 |
+
```
|
| 44 |
+
|
| 45 |
+
3. Pass a prompt and image to the pipeline to generate an image:
|
| 46 |
+
|
| 47 |
+
```py
|
| 48 |
+
prompt = "cat wizard, gandalf, lord of the rings, detailed, fantasy, cute, adorable, Pixar, Disney, 8k"
|
| 49 |
+
image = pipeline(prompt, image=init_image).images[0]
|
| 50 |
+
make_image_grid([init_image, image], rows=1, cols=2)
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
<div class="flex gap-4">
|
| 54 |
+
<div>
|
| 55 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/cat.png"/>
|
| 56 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">initial image</figcaption>
|
| 57 |
+
</div>
|
| 58 |
+
<div>
|
| 59 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img.png"/>
|
| 60 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">generated image</figcaption>
|
| 61 |
+
</div>
|
| 62 |
+
</div>
|
| 63 |
+
|
| 64 |
+
## Popular models
|
| 65 |
+
|
| 66 |
+
The most popular image-to-image models are [Stable Diffusion v1.5](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5), [Stable Diffusion XL (SDXL)](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0), and [Kandinsky 2.2](https://huggingface.co/kandinsky-community/kandinsky-2-2-decoder). The results from the Stable Diffusion and Kandinsky models vary due to their architecture differences and training process; you can generally expect SDXL to produce higher quality images than Stable Diffusion v1.5. Let's take a quick look at how to use each of these models and compare their results.
|
| 67 |
+
|
| 68 |
+
### Stable Diffusion v1.5
|
| 69 |
+
|
| 70 |
+
Stable Diffusion v1.5 is a latent diffusion model initialized from an earlier checkpoint, and further finetuned for 595K steps on 512x512 images. To use this pipeline for image-to-image, you'll need to prepare an initial image to pass to the pipeline. Then you can pass a prompt and the image to the pipeline to generate a new image:
|
| 71 |
+
|
| 72 |
+
```py
|
| 73 |
+
import torch
|
| 74 |
+
from diffusers import AutoPipelineForImage2Image
|
| 75 |
+
from diffusers.utils import make_image_grid, load_image
|
| 76 |
+
|
| 77 |
+
pipeline = AutoPipelineForImage2Image.from_pretrained(
|
| 78 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16, variant="fp16", use_safetensors=True
|
| 79 |
+
)
|
| 80 |
+
pipeline.enable_model_cpu_offload()
|
| 81 |
+
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
|
| 82 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 83 |
+
|
| 84 |
+
# prepare image
|
| 85 |
+
url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-init.png"
|
| 86 |
+
init_image = load_image(url)
|
| 87 |
+
|
| 88 |
+
prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
|
| 89 |
+
|
| 90 |
+
# pass prompt and image to pipeline
|
| 91 |
+
image = pipeline(prompt, image=init_image).images[0]
|
| 92 |
+
make_image_grid([init_image, image], rows=1, cols=2)
|
| 93 |
+
```
|
| 94 |
+
|
| 95 |
+
<div class="flex gap-4">
|
| 96 |
+
<div>
|
| 97 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-init.png"/>
|
| 98 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">initial image</figcaption>
|
| 99 |
+
</div>
|
| 100 |
+
<div>
|
| 101 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-sdv1.5.png"/>
|
| 102 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">generated image</figcaption>
|
| 103 |
+
</div>
|
| 104 |
+
</div>
|
| 105 |
+
|
| 106 |
+
### Stable Diffusion XL (SDXL)
|
| 107 |
+
|
| 108 |
+
SDXL is a more powerful version of the Stable Diffusion model. It uses a larger base model, and an additional refiner model to increase the quality of the base model's output. Read the [SDXL](sdxl) guide for a more detailed walkthrough of how to use this model, and other techniques it uses to produce high quality images.
|
| 109 |
+
|
| 110 |
+
```py
|
| 111 |
+
import torch
|
| 112 |
+
from diffusers import AutoPipelineForImage2Image
|
| 113 |
+
from diffusers.utils import make_image_grid, load_image
|
| 114 |
+
|
| 115 |
+
pipeline = AutoPipelineForImage2Image.from_pretrained(
|
| 116 |
+
"stabilityai/stable-diffusion-xl-refiner-1.0", torch_dtype=torch.float16, variant="fp16", use_safetensors=True
|
| 117 |
+
)
|
| 118 |
+
pipeline.enable_model_cpu_offload()
|
| 119 |
+
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
|
| 120 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 121 |
+
|
| 122 |
+
# prepare image
|
| 123 |
+
url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-sdxl-init.png"
|
| 124 |
+
init_image = load_image(url)
|
| 125 |
+
|
| 126 |
+
prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
|
| 127 |
+
|
| 128 |
+
# pass prompt and image to pipeline
|
| 129 |
+
image = pipeline(prompt, image=init_image, strength=0.5).images[0]
|
| 130 |
+
make_image_grid([init_image, image], rows=1, cols=2)
|
| 131 |
+
```
|
| 132 |
+
|
| 133 |
+
<div class="flex gap-4">
|
| 134 |
+
<div>
|
| 135 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-sdxl-init.png"/>
|
| 136 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">initial image</figcaption>
|
| 137 |
+
</div>
|
| 138 |
+
<div>
|
| 139 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-sdxl.png"/>
|
| 140 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">generated image</figcaption>
|
| 141 |
+
</div>
|
| 142 |
+
</div>
|
| 143 |
+
|
| 144 |
+
### Kandinsky 2.2
|
| 145 |
+
|
| 146 |
+
The Kandinsky model is different from the Stable Diffusion models because it uses an image prior model to create image embeddings. The embeddings help create a better alignment between text and images, allowing the latent diffusion model to generate better images.
|
| 147 |
+
|
| 148 |
+
The simplest way to use Kandinsky 2.2 is:
|
| 149 |
+
|
| 150 |
+
```py
|
| 151 |
+
import torch
|
| 152 |
+
from diffusers import AutoPipelineForImage2Image
|
| 153 |
+
from diffusers.utils import make_image_grid, load_image
|
| 154 |
+
|
| 155 |
+
pipeline = AutoPipelineForImage2Image.from_pretrained(
|
| 156 |
+
"kandinsky-community/kandinsky-2-2-decoder", torch_dtype=torch.float16, use_safetensors=True
|
| 157 |
+
)
|
| 158 |
+
pipeline.enable_model_cpu_offload()
|
| 159 |
+
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
|
| 160 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 161 |
+
|
| 162 |
+
# prepare image
|
| 163 |
+
url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-init.png"
|
| 164 |
+
init_image = load_image(url)
|
| 165 |
+
|
| 166 |
+
prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
|
| 167 |
+
|
| 168 |
+
# pass prompt and image to pipeline
|
| 169 |
+
image = pipeline(prompt, image=init_image).images[0]
|
| 170 |
+
make_image_grid([init_image, image], rows=1, cols=2)
|
| 171 |
+
```
|
| 172 |
+
|
| 173 |
+
<div class="flex gap-4">
|
| 174 |
+
<div>
|
| 175 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-init.png"/>
|
| 176 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">initial image</figcaption>
|
| 177 |
+
</div>
|
| 178 |
+
<div>
|
| 179 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-kandinsky.png"/>
|
| 180 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">generated image</figcaption>
|
| 181 |
+
</div>
|
| 182 |
+
</div>
|
| 183 |
+
|
| 184 |
+
## Configure pipeline parameters
|
| 185 |
+
|
| 186 |
+
There are several important parameters you can configure in the pipeline that'll affect the image generation process and image quality. Let's take a closer look at what these parameters do and how changing them affects the output.
|
| 187 |
+
|
| 188 |
+
### Strength
|
| 189 |
+
|
| 190 |
+
`strength` is one of the most important parameters to consider and it'll have a huge impact on your generated image. It determines how much the generated image resembles the initial image. In other words:
|
| 191 |
+
|
| 192 |
+
- 📈 a higher `strength` value gives the model more "creativity" to generate an image that's different from the initial image; a `strength` value of 1.0 means the initial image is more or less ignored
|
| 193 |
+
- 📉 a lower `strength` value means the generated image is more similar to the initial image
|
| 194 |
+
|
| 195 |
+
The `strength` and `num_inference_steps` parameters are related because `strength` determines the number of noise steps to add. For example, if the `num_inference_steps` is 50 and `strength` is 0.8, then this means adding 40 (50 * 0.8) steps of noise to the initial image and then denoising for 40 steps to get the newly generated image.
|
| 196 |
+
|
| 197 |
+
```py
|
| 198 |
+
import torch
|
| 199 |
+
from diffusers import AutoPipelineForImage2Image
|
| 200 |
+
from diffusers.utils import make_image_grid, load_image
|
| 201 |
+
|
| 202 |
+
pipeline = AutoPipelineForImage2Image.from_pretrained(
|
| 203 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16, variant="fp16", use_safetensors=True
|
| 204 |
+
)
|
| 205 |
+
pipeline.enable_model_cpu_offload()
|
| 206 |
+
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
|
| 207 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 208 |
+
|
| 209 |
+
# prepare image
|
| 210 |
+
url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-init.png"
|
| 211 |
+
init_image = load_image(url)
|
| 212 |
+
|
| 213 |
+
prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
|
| 214 |
+
|
| 215 |
+
# pass prompt and image to pipeline
|
| 216 |
+
image = pipeline(prompt, image=init_image, strength=0.8).images[0]
|
| 217 |
+
make_image_grid([init_image, image], rows=1, cols=2)
|
| 218 |
+
```
|
| 219 |
+
|
| 220 |
+
<div class="flex flex-row gap-4">
|
| 221 |
+
<div class="flex-1">
|
| 222 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-strength-0.4.png"/>
|
| 223 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">strength = 0.4</figcaption>
|
| 224 |
+
</div>
|
| 225 |
+
<div class="flex-1">
|
| 226 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-strength-0.6.png"/>
|
| 227 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">strength = 0.6</figcaption>
|
| 228 |
+
</div>
|
| 229 |
+
<div class="flex-1">
|
| 230 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-strength-1.0.png"/>
|
| 231 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">strength = 1.0</figcaption>
|
| 232 |
+
</div>
|
| 233 |
+
</div>
|
| 234 |
+
|
| 235 |
+
### Guidance scale
|
| 236 |
+
|
| 237 |
+
The `guidance_scale` parameter is used to control how closely aligned the generated image and text prompt are. A higher `guidance_scale` value means your generated image is more aligned with the prompt, while a lower `guidance_scale` value means your generated image has more space to deviate from the prompt.
|
| 238 |
+
|
| 239 |
+
You can combine `guidance_scale` with `strength` for even more precise control over how expressive the model is. For example, combine a high `strength + guidance_scale` for maximum creativity or use a combination of low `strength` and low `guidance_scale` to generate an image that resembles the initial image but is not as strictly bound to the prompt.
|
| 240 |
+
|
| 241 |
+
```py
|
| 242 |
+
import torch
|
| 243 |
+
from diffusers import AutoPipelineForImage2Image
|
| 244 |
+
from diffusers.utils import make_image_grid, load_image
|
| 245 |
+
|
| 246 |
+
pipeline = AutoPipelineForImage2Image.from_pretrained(
|
| 247 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16, variant="fp16", use_safetensors=True
|
| 248 |
+
)
|
| 249 |
+
pipeline.enable_model_cpu_offload()
|
| 250 |
+
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
|
| 251 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 252 |
+
|
| 253 |
+
# prepare image
|
| 254 |
+
url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-init.png"
|
| 255 |
+
init_image = load_image(url)
|
| 256 |
+
|
| 257 |
+
prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
|
| 258 |
+
|
| 259 |
+
# pass prompt and image to pipeline
|
| 260 |
+
image = pipeline(prompt, image=init_image, guidance_scale=8.0).images[0]
|
| 261 |
+
make_image_grid([init_image, image], rows=1, cols=2)
|
| 262 |
+
```
|
| 263 |
+
|
| 264 |
+
<div class="flex flex-row gap-4">
|
| 265 |
+
<div class="flex-1">
|
| 266 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-guidance-0.1.png"/>
|
| 267 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">guidance_scale = 0.1</figcaption>
|
| 268 |
+
</div>
|
| 269 |
+
<div class="flex-1">
|
| 270 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-guidance-3.0.png"/>
|
| 271 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">guidance_scale = 5.0</figcaption>
|
| 272 |
+
</div>
|
| 273 |
+
<div class="flex-1">
|
| 274 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-guidance-7.5.png"/>
|
| 275 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">guidance_scale = 10.0</figcaption>
|
| 276 |
+
</div>
|
| 277 |
+
</div>
|
| 278 |
+
|
| 279 |
+
### Negative prompt
|
| 280 |
+
|
| 281 |
+
A negative prompt conditions the model to *not* include things in an image, and it can be used to improve image quality or modify an image. For example, you can improve image quality by including negative prompts like "poor details" or "blurry" to encourage the model to generate a higher quality image. Or you can modify an image by specifying things to exclude from an image.
|
| 282 |
+
|
| 283 |
+
```py
|
| 284 |
+
import torch
|
| 285 |
+
from diffusers import AutoPipelineForImage2Image
|
| 286 |
+
from diffusers.utils import make_image_grid, load_image
|
| 287 |
+
|
| 288 |
+
pipeline = AutoPipelineForImage2Image.from_pretrained(
|
| 289 |
+
"stabilityai/stable-diffusion-xl-refiner-1.0", torch_dtype=torch.float16, variant="fp16", use_safetensors=True
|
| 290 |
+
)
|
| 291 |
+
pipeline.enable_model_cpu_offload()
|
| 292 |
+
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
|
| 293 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 294 |
+
|
| 295 |
+
# prepare image
|
| 296 |
+
url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-init.png"
|
| 297 |
+
init_image = load_image(url)
|
| 298 |
+
|
| 299 |
+
prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
|
| 300 |
+
negative_prompt = "ugly, deformed, disfigured, poor details, bad anatomy"
|
| 301 |
+
|
| 302 |
+
# pass prompt and image to pipeline
|
| 303 |
+
image = pipeline(prompt, negative_prompt=negative_prompt, image=init_image).images[0]
|
| 304 |
+
make_image_grid([init_image, image], rows=1, cols=2)
|
| 305 |
+
```
|
| 306 |
+
|
| 307 |
+
<div class="flex flex-row gap-4">
|
| 308 |
+
<div class="flex-1">
|
| 309 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-negative-1.png"/>
|
| 310 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">negative_prompt = "ugly, deformed, disfigured, poor details, bad anatomy"</figcaption>
|
| 311 |
+
</div>
|
| 312 |
+
<div class="flex-1">
|
| 313 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-negative-2.png"/>
|
| 314 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">negative_prompt = "jungle"</figcaption>
|
| 315 |
+
</div>
|
| 316 |
+
</div>
|
| 317 |
+
|
| 318 |
+
## Chained image-to-image pipelines
|
| 319 |
+
|
| 320 |
+
There are some other interesting ways you can use an image-to-image pipeline aside from just generating an image (although that is pretty cool too). You can take it a step further and chain it with other pipelines.
|
| 321 |
+
|
| 322 |
+
### Text-to-image-to-image
|
| 323 |
+
|
| 324 |
+
Chaining a text-to-image and image-to-image pipeline allows you to generate an image from text and use the generated image as the initial image for the image-to-image pipeline. This is useful if you want to generate an image entirely from scratch. For example, let's chain a Stable Diffusion and a Kandinsky model.
|
| 325 |
+
|
| 326 |
+
Start by generating an image with the text-to-image pipeline:
|
| 327 |
+
|
| 328 |
+
```py
|
| 329 |
+
from diffusers import AutoPipelineForText2Image, AutoPipelineForImage2Image
|
| 330 |
+
import torch
|
| 331 |
+
from diffusers.utils import make_image_grid
|
| 332 |
+
|
| 333 |
+
pipeline = AutoPipelineForText2Image.from_pretrained(
|
| 334 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16, variant="fp16", use_safetensors=True
|
| 335 |
+
)
|
| 336 |
+
pipeline.enable_model_cpu_offload()
|
| 337 |
+
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
|
| 338 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 339 |
+
|
| 340 |
+
text2image = pipeline("Astronaut in a jungle, cold color palette, muted colors, detailed, 8k").images[0]
|
| 341 |
+
text2image
|
| 342 |
+
```
|
| 343 |
+
|
| 344 |
+
Now you can pass this generated image to the image-to-image pipeline:
|
| 345 |
+
|
| 346 |
+
```py
|
| 347 |
+
pipeline = AutoPipelineForImage2Image.from_pretrained(
|
| 348 |
+
"kandinsky-community/kandinsky-2-2-decoder", torch_dtype=torch.float16, use_safetensors=True
|
| 349 |
+
)
|
| 350 |
+
pipeline.enable_model_cpu_offload()
|
| 351 |
+
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
|
| 352 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 353 |
+
|
| 354 |
+
image2image = pipeline("Astronaut in a jungle, cold color palette, muted colors, detailed, 8k", image=text2image).images[0]
|
| 355 |
+
make_image_grid([text2image, image2image], rows=1, cols=2)
|
| 356 |
+
```
|
| 357 |
+
|
| 358 |
+
### Image-to-image-to-image
|
| 359 |
+
|
| 360 |
+
You can also chain multiple image-to-image pipelines together to create more interesting images. This can be useful for iteratively performing style transfer on an image, generating short GIFs, restoring color to an image, or restoring missing areas of an image.
|
| 361 |
+
|
| 362 |
+
Start by generating an image:
|
| 363 |
+
|
| 364 |
+
```py
|
| 365 |
+
import torch
|
| 366 |
+
from diffusers import AutoPipelineForImage2Image
|
| 367 |
+
from diffusers.utils import make_image_grid, load_image
|
| 368 |
+
|
| 369 |
+
pipeline = AutoPipelineForImage2Image.from_pretrained(
|
| 370 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16, variant="fp16", use_safetensors=True
|
| 371 |
+
)
|
| 372 |
+
pipeline.enable_model_cpu_offload()
|
| 373 |
+
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
|
| 374 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 375 |
+
|
| 376 |
+
# prepare image
|
| 377 |
+
url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-init.png"
|
| 378 |
+
init_image = load_image(url)
|
| 379 |
+
|
| 380 |
+
prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
|
| 381 |
+
|
| 382 |
+
# pass prompt and image to pipeline
|
| 383 |
+
image = pipeline(prompt, image=init_image, output_type="latent").images[0]
|
| 384 |
+
```
|
| 385 |
+
|
| 386 |
+
> [!TIP]
|
| 387 |
+
> It is important to specify `output_type="latent"` in the pipeline to keep all the outputs in latent space to avoid an unnecessary decode-encode step. This only works if the chained pipelines are using the same VAE.
|
| 388 |
+
|
| 389 |
+
Pass the latent output from this pipeline to the next pipeline to generate an image in a [comic book art style](https://huggingface.co/ogkalu/Comic-Diffusion):
|
| 390 |
+
|
| 391 |
+
```py
|
| 392 |
+
pipeline = AutoPipelineForImage2Image.from_pretrained(
|
| 393 |
+
"ogkalu/Comic-Diffusion", torch_dtype=torch.float16
|
| 394 |
+
)
|
| 395 |
+
pipeline.enable_model_cpu_offload()
|
| 396 |
+
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
|
| 397 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 398 |
+
|
| 399 |
+
# need to include the token "charliebo artstyle" in the prompt to use this checkpoint
|
| 400 |
+
image = pipeline("Astronaut in a jungle, charliebo artstyle", image=image, output_type="latent").images[0]
|
| 401 |
+
```
|
| 402 |
+
|
| 403 |
+
Repeat one more time to generate the final image in a [pixel art style](https://huggingface.co/kohbanye/pixel-art-style):
|
| 404 |
+
|
| 405 |
+
```py
|
| 406 |
+
pipeline = AutoPipelineForImage2Image.from_pretrained(
|
| 407 |
+
"kohbanye/pixel-art-style", torch_dtype=torch.float16
|
| 408 |
+
)
|
| 409 |
+
pipeline.enable_model_cpu_offload()
|
| 410 |
+
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
|
| 411 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 412 |
+
|
| 413 |
+
# need to include the token "pixelartstyle" in the prompt to use this checkpoint
|
| 414 |
+
image = pipeline("Astronaut in a jungle, pixelartstyle", image=image).images[0]
|
| 415 |
+
make_image_grid([init_image, image], rows=1, cols=2)
|
| 416 |
+
```
|
| 417 |
+
|
| 418 |
+
### Image-to-upscaler-to-super-resolution
|
| 419 |
+
|
| 420 |
+
Another way you can chain your image-to-image pipeline is with an upscaler and super-resolution pipeline to really increase the level of details in an image.
|
| 421 |
+
|
| 422 |
+
Start with an image-to-image pipeline:
|
| 423 |
+
|
| 424 |
+
```py
|
| 425 |
+
import torch
|
| 426 |
+
from diffusers import AutoPipelineForImage2Image
|
| 427 |
+
from diffusers.utils import make_image_grid, load_image
|
| 428 |
+
|
| 429 |
+
pipeline = AutoPipelineForImage2Image.from_pretrained(
|
| 430 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16, variant="fp16", use_safetensors=True
|
| 431 |
+
)
|
| 432 |
+
pipeline.enable_model_cpu_offload()
|
| 433 |
+
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
|
| 434 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 435 |
+
|
| 436 |
+
# prepare image
|
| 437 |
+
url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-init.png"
|
| 438 |
+
init_image = load_image(url)
|
| 439 |
+
|
| 440 |
+
prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
|
| 441 |
+
|
| 442 |
+
# pass prompt and image to pipeline
|
| 443 |
+
image_1 = pipeline(prompt, image=init_image, output_type="latent").images[0]
|
| 444 |
+
```
|
| 445 |
+
|
| 446 |
+
> [!TIP]
|
| 447 |
+
> It is important to specify `output_type="latent"` in the pipeline to keep all the outputs in *latent* space to avoid an unnecessary decode-encode step. This only works if the chained pipelines are using the same VAE.
|
| 448 |
+
|
| 449 |
+
Chain it to an upscaler pipeline to increase the image resolution:
|
| 450 |
+
|
| 451 |
+
```py
|
| 452 |
+
from diffusers import StableDiffusionLatentUpscalePipeline
|
| 453 |
+
|
| 454 |
+
upscaler = StableDiffusionLatentUpscalePipeline.from_pretrained(
|
| 455 |
+
"stabilityai/sd-x2-latent-upscaler", torch_dtype=torch.float16, use_safetensors=True
|
| 456 |
+
)
|
| 457 |
+
upscaler.enable_model_cpu_offload()
|
| 458 |
+
upscaler.enable_xformers_memory_efficient_attention()
|
| 459 |
+
|
| 460 |
+
image_2 = upscaler(prompt, image=image_1).images[0]
|
| 461 |
+
```
|
| 462 |
+
|
| 463 |
+
Finally, chain it to a super-resolution pipeline to further enhance the resolution:
|
| 464 |
+
|
| 465 |
+
```py
|
| 466 |
+
from diffusers import StableDiffusionUpscalePipeline
|
| 467 |
+
|
| 468 |
+
super_res = StableDiffusionUpscalePipeline.from_pretrained(
|
| 469 |
+
"stabilityai/stable-diffusion-x4-upscaler", torch_dtype=torch.float16, variant="fp16", use_safetensors=True
|
| 470 |
+
)
|
| 471 |
+
super_res.enable_model_cpu_offload()
|
| 472 |
+
super_res.enable_xformers_memory_efficient_attention()
|
| 473 |
+
|
| 474 |
+
image_3 = super_res(prompt, image=image_2).images[0]
|
| 475 |
+
make_image_grid([init_image, image_3.resize((512, 512))], rows=1, cols=2)
|
| 476 |
+
```
|
| 477 |
+
|
| 478 |
+
## Control image generation
|
| 479 |
+
|
| 480 |
+
Trying to generate an image that looks exactly the way you want can be difficult, which is why controlled generation techniques and models are so useful. While you can use the `negative_prompt` to partially control image generation, there are more robust methods like prompt weighting and ControlNets.
|
| 481 |
+
|
| 482 |
+
### Prompt weighting
|
| 483 |
+
|
| 484 |
+
Prompt weighting allows you to scale the representation of each concept in a prompt. For example, in a prompt like "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k", you can choose to increase or decrease the embeddings of "astronaut" and "jungle". The [Compel](https://github.com/damian0815/compel) library provides a simple syntax for adjusting prompt weights and generating the embeddings. You can learn how to create the embeddings in the [Prompt weighting](weighted_prompts) guide.
|
| 485 |
+
|
| 486 |
+
[`AutoPipelineForImage2Image`] has a `prompt_embeds` (and `negative_prompt_embeds` if you're using a negative prompt) parameter where you can pass the embeddings which replaces the `prompt` parameter.
|
| 487 |
+
|
| 488 |
+
```py
|
| 489 |
+
from diffusers import AutoPipelineForImage2Image
|
| 490 |
+
import torch
|
| 491 |
+
|
| 492 |
+
pipeline = AutoPipelineForImage2Image.from_pretrained(
|
| 493 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16, variant="fp16", use_safetensors=True
|
| 494 |
+
)
|
| 495 |
+
pipeline.enable_model_cpu_offload()
|
| 496 |
+
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
|
| 497 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 498 |
+
|
| 499 |
+
image = pipeline(prompt_embeds=prompt_embeds, # generated from Compel
|
| 500 |
+
negative_prompt_embeds=negative_prompt_embeds, # generated from Compel
|
| 501 |
+
image=init_image,
|
| 502 |
+
).images[0]
|
| 503 |
+
```
|
| 504 |
+
|
| 505 |
+
### ControlNet
|
| 506 |
+
|
| 507 |
+
ControlNets provide a more flexible and accurate way to control image generation because you can use an additional conditioning image. The conditioning image can be a canny image, depth map, image segmentation, and even scribbles! Whatever type of conditioning image you choose, the ControlNet generates an image that preserves the information in it.
|
| 508 |
+
|
| 509 |
+
For example, let's condition an image with a depth map to keep the spatial information in the image.
|
| 510 |
+
|
| 511 |
+
```py
|
| 512 |
+
from diffusers.utils import load_image, make_image_grid
|
| 513 |
+
|
| 514 |
+
# prepare image
|
| 515 |
+
url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-init.png"
|
| 516 |
+
init_image = load_image(url)
|
| 517 |
+
init_image = init_image.resize((958, 960)) # resize to depth image dimensions
|
| 518 |
+
depth_image = load_image("https://huggingface.co/lllyasviel/control_v11f1p_sd15_depth/resolve/main/images/control.png")
|
| 519 |
+
make_image_grid([init_image, depth_image], rows=1, cols=2)
|
| 520 |
+
```
|
| 521 |
+
|
| 522 |
+
Load a ControlNet model conditioned on depth maps and the [`AutoPipelineForImage2Image`]:
|
| 523 |
+
|
| 524 |
+
```py
|
| 525 |
+
from diffusers import ControlNetModel, AutoPipelineForImage2Image
|
| 526 |
+
import torch
|
| 527 |
+
|
| 528 |
+
controlnet = ControlNetModel.from_pretrained("lllyasviel/control_v11f1p_sd15_depth", torch_dtype=torch.float16, variant="fp16", use_safetensors=True)
|
| 529 |
+
pipeline = AutoPipelineForImage2Image.from_pretrained(
|
| 530 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5", controlnet=controlnet, torch_dtype=torch.float16, variant="fp16", use_safetensors=True
|
| 531 |
+
)
|
| 532 |
+
pipeline.enable_model_cpu_offload()
|
| 533 |
+
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
|
| 534 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 535 |
+
```
|
| 536 |
+
|
| 537 |
+
Now generate a new image conditioned on the depth map, initial image, and prompt:
|
| 538 |
+
|
| 539 |
+
```py
|
| 540 |
+
prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
|
| 541 |
+
image_control_net = pipeline(prompt, image=init_image, control_image=depth_image).images[0]
|
| 542 |
+
make_image_grid([init_image, depth_image, image_control_net], rows=1, cols=3)
|
| 543 |
+
```
|
| 544 |
+
|
| 545 |
+
<div class="flex flex-row gap-4">
|
| 546 |
+
<div class="flex-1">
|
| 547 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-init.png"/>
|
| 548 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">initial image</figcaption>
|
| 549 |
+
</div>
|
| 550 |
+
<div class="flex-1">
|
| 551 |
+
<img class="rounded-xl" src="https://huggingface.co/lllyasviel/control_v11f1p_sd15_depth/resolve/main/images/control.png"/>
|
| 552 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">depth image</figcaption>
|
| 553 |
+
</div>
|
| 554 |
+
<div class="flex-1">
|
| 555 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-controlnet.png"/>
|
| 556 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">ControlNet image</figcaption>
|
| 557 |
+
</div>
|
| 558 |
+
</div>
|
| 559 |
+
|
| 560 |
+
Let's apply a new [style](https://huggingface.co/nitrosocke/elden-ring-diffusion) to the image generated from the ControlNet by chaining it with an image-to-image pipeline:
|
| 561 |
+
|
| 562 |
+
```py
|
| 563 |
+
pipeline = AutoPipelineForImage2Image.from_pretrained(
|
| 564 |
+
"nitrosocke/elden-ring-diffusion", torch_dtype=torch.float16,
|
| 565 |
+
)
|
| 566 |
+
pipeline.enable_model_cpu_offload()
|
| 567 |
+
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
|
| 568 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 569 |
+
|
| 570 |
+
prompt = "elden ring style astronaut in a jungle" # include the token "elden ring style" in the prompt
|
| 571 |
+
negative_prompt = "ugly, deformed, disfigured, poor details, bad anatomy"
|
| 572 |
+
|
| 573 |
+
image_elden_ring = pipeline(prompt, negative_prompt=negative_prompt, image=image_control_net, strength=0.45, guidance_scale=10.5).images[0]
|
| 574 |
+
make_image_grid([init_image, depth_image, image_control_net, image_elden_ring], rows=2, cols=2)
|
| 575 |
+
```
|
| 576 |
+
|
| 577 |
+
<div class="flex justify-center">
|
| 578 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-elden-ring.png">
|
| 579 |
+
</div>
|
| 580 |
+
|
| 581 |
+
## Optimize
|
| 582 |
+
|
| 583 |
+
Running diffusion models is computationally expensive and intensive, but with a few optimization tricks, it is entirely possible to run them on consumer and free-tier GPUs. For example, you can use a more memory-efficient form of attention such as PyTorch 2.0's [scaled-dot product attention](../optimization/fp16#scaled-dot-product-attention) or [xFormers](../optimization/xformers) (you can use one or the other, but there's no need to use both). You can also offload the model to the GPU while the other pipeline components wait on the CPU.
|
| 584 |
+
|
| 585 |
+
```diff
|
| 586 |
+
+ pipeline.enable_model_cpu_offload()
|
| 587 |
+
+ pipeline.enable_xformers_memory_efficient_attention()
|
| 588 |
+
```
|
| 589 |
+
|
| 590 |
+
With [`torch.compile`](../optimization/fp16#torchcompile), you can boost your inference speed even more by wrapping your UNet with it:
|
| 591 |
+
|
| 592 |
+
```py
|
| 593 |
+
pipeline.unet = torch.compile(pipeline.unet, mode="reduce-overhead", fullgraph=True)
|
| 594 |
+
```
|
| 595 |
+
|
| 596 |
+
To learn more, take a look at the [Reduce memory usage](../optimization/memory) and [Accelerate inference](../optimization/fp16) guides.
|
tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/inference_with_lcm.md
ADDED
|
@@ -0,0 +1,631 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# Latent Consistency Model
|
| 14 |
+
|
| 15 |
+
[[open-in-colab]]
|
| 16 |
+
|
| 17 |
+
[Latent Consistency Models (LCMs)](https://hf.co/papers/2310.04378) enable fast high-quality image generation by directly predicting the reverse diffusion process in the latent rather than pixel space. In other words, LCMs try to predict the noiseless image from the noisy image in contrast to typical diffusion models that iteratively remove noise from the noisy image. By avoiding the iterative sampling process, LCMs are able to generate high-quality images in 2-4 steps instead of 20-30 steps.
|
| 18 |
+
|
| 19 |
+
LCMs are distilled from pretrained models which requires ~32 hours of A100 compute. To speed this up, [LCM-LoRAs](https://hf.co/papers/2311.05556) train a [LoRA adapter](https://huggingface.co/docs/peft/conceptual_guides/adapter#low-rank-adaptation-lora) which have much fewer parameters to train compared to the full model. The LCM-LoRA can be plugged into a diffusion model once it has been trained.
|
| 20 |
+
|
| 21 |
+
This guide will show you how to use LCMs and LCM-LoRAs for fast inference on tasks and how to use them with other adapters like ControlNet or T2I-Adapter.
|
| 22 |
+
|
| 23 |
+
> [!TIP]
|
| 24 |
+
> LCMs and LCM-LoRAs are available for Stable Diffusion v1.5, Stable Diffusion XL, and the SSD-1B model. You can find their checkpoints on the [Latent Consistency](https://hf.co/collections/latent-consistency/latent-consistency-models-weights-654ce61a95edd6dffccef6a8) Collections.
|
| 25 |
+
|
| 26 |
+
## Text-to-image
|
| 27 |
+
|
| 28 |
+
<hfoptions id="lcm-text2img">
|
| 29 |
+
<hfoption id="LCM">
|
| 30 |
+
|
| 31 |
+
To use LCMs, you need to load the LCM checkpoint for your supported model into [`UNet2DConditionModel`] and replace the scheduler with the [`LCMScheduler`]. Then you can use the pipeline as usual, and pass a text prompt to generate an image in just 4 steps.
|
| 32 |
+
|
| 33 |
+
A couple of notes to keep in mind when using LCMs are:
|
| 34 |
+
|
| 35 |
+
* Typically, batch size is doubled inside the pipeline for classifier-free guidance. But LCM applies guidance with guidance embeddings and doesn't need to double the batch size, which leads to faster inference. The downside is that negative prompts don't work with LCM because they don't have any effect on the denoising process.
|
| 36 |
+
* The ideal range for `guidance_scale` is [3., 13.] because that is what the UNet was trained with. However, disabling `guidance_scale` with a value of 1.0 is also effective in most cases.
|
| 37 |
+
|
| 38 |
+
```python
|
| 39 |
+
from diffusers import StableDiffusionXLPipeline, UNet2DConditionModel, LCMScheduler
|
| 40 |
+
import torch
|
| 41 |
+
|
| 42 |
+
unet = UNet2DConditionModel.from_pretrained(
|
| 43 |
+
"latent-consistency/lcm-sdxl",
|
| 44 |
+
torch_dtype=torch.float16,
|
| 45 |
+
variant="fp16",
|
| 46 |
+
)
|
| 47 |
+
pipe = StableDiffusionXLPipeline.from_pretrained(
|
| 48 |
+
"stabilityai/stable-diffusion-xl-base-1.0", unet=unet, torch_dtype=torch.float16, variant="fp16",
|
| 49 |
+
).to("cuda")
|
| 50 |
+
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)
|
| 51 |
+
|
| 52 |
+
prompt = "Self-portrait oil painting, a beautiful cyborg with golden hair, 8k"
|
| 53 |
+
generator = torch.manual_seed(0)
|
| 54 |
+
image = pipe(
|
| 55 |
+
prompt=prompt, num_inference_steps=4, generator=generator, guidance_scale=8.0
|
| 56 |
+
).images[0]
|
| 57 |
+
image
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
<div class="flex justify-center">
|
| 61 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/lcm/lcm_full_sdxl_t2i.png"/>
|
| 62 |
+
</div>
|
| 63 |
+
|
| 64 |
+
</hfoption>
|
| 65 |
+
<hfoption id="LCM-LoRA">
|
| 66 |
+
|
| 67 |
+
To use LCM-LoRAs, you need to replace the scheduler with the [`LCMScheduler`] and load the LCM-LoRA weights with the [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] method. Then you can use the pipeline as usual, and pass a text prompt to generate an image in just 4 steps.
|
| 68 |
+
|
| 69 |
+
A couple of notes to keep in mind when using LCM-LoRAs are:
|
| 70 |
+
|
| 71 |
+
* Typically, batch size is doubled inside the pipeline for classifier-free guidance. But LCM applies guidance with guidance embeddings and doesn't need to double the batch size, which leads to faster inference. The downside is that negative prompts don't work with LCM because they don't have any effect on the denoising process.
|
| 72 |
+
* You could use guidance with LCM-LoRAs, but it is very sensitive to high `guidance_scale` values and can lead to artifacts in the generated image. The best values we've found are between [1.0, 2.0].
|
| 73 |
+
* Replace [stabilityai/stable-diffusion-xl-base-1.0](https://hf.co/stabilityai/stable-diffusion-xl-base-1.0) with any finetuned model. For example, try using the [animagine-xl](https://huggingface.co/Linaqruf/animagine-xl) checkpoint to generate anime images with SDXL.
|
| 74 |
+
|
| 75 |
+
```py
|
| 76 |
+
import torch
|
| 77 |
+
from diffusers import DiffusionPipeline, LCMScheduler
|
| 78 |
+
|
| 79 |
+
pipe = DiffusionPipeline.from_pretrained(
|
| 80 |
+
"stabilityai/stable-diffusion-xl-base-1.0",
|
| 81 |
+
variant="fp16",
|
| 82 |
+
torch_dtype=torch.float16
|
| 83 |
+
).to("cuda")
|
| 84 |
+
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)
|
| 85 |
+
pipe.load_lora_weights("latent-consistency/lcm-lora-sdxl")
|
| 86 |
+
|
| 87 |
+
prompt = "Self-portrait oil painting, a beautiful cyborg with golden hair, 8k"
|
| 88 |
+
generator = torch.manual_seed(42)
|
| 89 |
+
image = pipe(
|
| 90 |
+
prompt=prompt, num_inference_steps=4, generator=generator, guidance_scale=1.0
|
| 91 |
+
).images[0]
|
| 92 |
+
image
|
| 93 |
+
```
|
| 94 |
+
|
| 95 |
+
<div class="flex justify-center">
|
| 96 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/lcm/lcm_sdxl_t2i.png"/>
|
| 97 |
+
</div>
|
| 98 |
+
|
| 99 |
+
</hfoption>
|
| 100 |
+
</hfoptions>
|
| 101 |
+
|
| 102 |
+
## Image-to-image
|
| 103 |
+
|
| 104 |
+
<hfoptions id="lcm-img2img">
|
| 105 |
+
<hfoption id="LCM">
|
| 106 |
+
|
| 107 |
+
To use LCMs for image-to-image, you need to load the LCM checkpoint for your supported model into [`UNet2DConditionModel`] and replace the scheduler with the [`LCMScheduler`]. Then you can use the pipeline as usual, and pass a text prompt and initial image to generate an image in just 4 steps.
|
| 108 |
+
|
| 109 |
+
> [!TIP]
|
| 110 |
+
> Experiment with different values for `num_inference_steps`, `strength`, and `guidance_scale` to get the best results.
|
| 111 |
+
|
| 112 |
+
```python
|
| 113 |
+
import torch
|
| 114 |
+
from diffusers import AutoPipelineForImage2Image, UNet2DConditionModel, LCMScheduler
|
| 115 |
+
from diffusers.utils import load_image
|
| 116 |
+
|
| 117 |
+
unet = UNet2DConditionModel.from_pretrained(
|
| 118 |
+
"SimianLuo/LCM_Dreamshaper_v7",
|
| 119 |
+
subfolder="unet",
|
| 120 |
+
torch_dtype=torch.float16,
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
pipe = AutoPipelineForImage2Image.from_pretrained(
|
| 124 |
+
"Lykon/dreamshaper-7",
|
| 125 |
+
unet=unet,
|
| 126 |
+
torch_dtype=torch.float16,
|
| 127 |
+
variant="fp16",
|
| 128 |
+
).to("cuda")
|
| 129 |
+
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)
|
| 130 |
+
|
| 131 |
+
init_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-init.png")
|
| 132 |
+
prompt = "Astronauts in a jungle, cold color palette, muted colors, detailed, 8k"
|
| 133 |
+
generator = torch.manual_seed(0)
|
| 134 |
+
image = pipe(
|
| 135 |
+
prompt,
|
| 136 |
+
image=init_image,
|
| 137 |
+
num_inference_steps=4,
|
| 138 |
+
guidance_scale=7.5,
|
| 139 |
+
strength=0.5,
|
| 140 |
+
generator=generator
|
| 141 |
+
).images[0]
|
| 142 |
+
image
|
| 143 |
+
```
|
| 144 |
+
|
| 145 |
+
<div class="flex gap-4">
|
| 146 |
+
<div>
|
| 147 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-init.png"/>
|
| 148 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">initial image</figcaption>
|
| 149 |
+
</div>
|
| 150 |
+
<div>
|
| 151 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/lcm-img2img.png"/>
|
| 152 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">generated image</figcaption>
|
| 153 |
+
</div>
|
| 154 |
+
</div>
|
| 155 |
+
|
| 156 |
+
</hfoption>
|
| 157 |
+
<hfoption id="LCM-LoRA">
|
| 158 |
+
|
| 159 |
+
To use LCM-LoRAs for image-to-image, you need to replace the scheduler with the [`LCMScheduler`] and load the LCM-LoRA weights with the [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] method. Then you can use the pipeline as usual, and pass a text prompt and initial image to generate an image in just 4 steps.
|
| 160 |
+
|
| 161 |
+
> [!TIP]
|
| 162 |
+
> Experiment with different values for `num_inference_steps`, `strength`, and `guidance_scale` to get the best results.
|
| 163 |
+
|
| 164 |
+
```py
|
| 165 |
+
import torch
|
| 166 |
+
from diffusers import AutoPipelineForImage2Image, LCMScheduler
|
| 167 |
+
from diffusers.utils import make_image_grid, load_image
|
| 168 |
+
|
| 169 |
+
pipe = AutoPipelineForImage2Image.from_pretrained(
|
| 170 |
+
"Lykon/dreamshaper-7",
|
| 171 |
+
torch_dtype=torch.float16,
|
| 172 |
+
variant="fp16",
|
| 173 |
+
).to("cuda")
|
| 174 |
+
|
| 175 |
+
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)
|
| 176 |
+
|
| 177 |
+
pipe.load_lora_weights("latent-consistency/lcm-lora-sdv1-5")
|
| 178 |
+
|
| 179 |
+
init_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-init.png")
|
| 180 |
+
prompt = "Astronauts in a jungle, cold color palette, muted colors, detailed, 8k"
|
| 181 |
+
|
| 182 |
+
generator = torch.manual_seed(0)
|
| 183 |
+
image = pipe(
|
| 184 |
+
prompt,
|
| 185 |
+
image=init_image,
|
| 186 |
+
num_inference_steps=4,
|
| 187 |
+
guidance_scale=1,
|
| 188 |
+
strength=0.6,
|
| 189 |
+
generator=generator
|
| 190 |
+
).images[0]
|
| 191 |
+
image
|
| 192 |
+
```
|
| 193 |
+
|
| 194 |
+
<div class="flex gap-4">
|
| 195 |
+
<div>
|
| 196 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/img2img-init.png"/>
|
| 197 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">initial image</figcaption>
|
| 198 |
+
</div>
|
| 199 |
+
<div>
|
| 200 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/lcm-lora-img2img.png"/>
|
| 201 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">generated image</figcaption>
|
| 202 |
+
</div>
|
| 203 |
+
</div>
|
| 204 |
+
|
| 205 |
+
</hfoption>
|
| 206 |
+
</hfoptions>
|
| 207 |
+
|
| 208 |
+
## Inpainting
|
| 209 |
+
|
| 210 |
+
To use LCM-LoRAs for inpainting, you need to replace the scheduler with the [`LCMScheduler`] and load the LCM-LoRA weights with the [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] method. Then you can use the pipeline as usual, and pass a text prompt, initial image, and mask image to generate an image in just 4 steps.
|
| 211 |
+
|
| 212 |
+
```py
|
| 213 |
+
import torch
|
| 214 |
+
from diffusers import AutoPipelineForInpainting, LCMScheduler
|
| 215 |
+
from diffusers.utils import load_image, make_image_grid
|
| 216 |
+
|
| 217 |
+
pipe = AutoPipelineForInpainting.from_pretrained(
|
| 218 |
+
"stable-diffusion-v1-5/stable-diffusion-inpainting",
|
| 219 |
+
torch_dtype=torch.float16,
|
| 220 |
+
variant="fp16",
|
| 221 |
+
).to("cuda")
|
| 222 |
+
|
| 223 |
+
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)
|
| 224 |
+
|
| 225 |
+
pipe.load_lora_weights("latent-consistency/lcm-lora-sdv1-5")
|
| 226 |
+
|
| 227 |
+
init_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint.png")
|
| 228 |
+
mask_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint_mask.png")
|
| 229 |
+
|
| 230 |
+
prompt = "concept art digital painting of an elven castle, inspired by lord of the rings, highly detailed, 8k"
|
| 231 |
+
generator = torch.manual_seed(0)
|
| 232 |
+
image = pipe(
|
| 233 |
+
prompt=prompt,
|
| 234 |
+
image=init_image,
|
| 235 |
+
mask_image=mask_image,
|
| 236 |
+
generator=generator,
|
| 237 |
+
num_inference_steps=4,
|
| 238 |
+
guidance_scale=4,
|
| 239 |
+
).images[0]
|
| 240 |
+
image
|
| 241 |
+
```
|
| 242 |
+
|
| 243 |
+
<div class="flex gap-4">
|
| 244 |
+
<div>
|
| 245 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint.png"/>
|
| 246 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">initial image</figcaption>
|
| 247 |
+
</div>
|
| 248 |
+
<div>
|
| 249 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/lcm-lora-inpaint.png"/>
|
| 250 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">generated image</figcaption>
|
| 251 |
+
</div>
|
| 252 |
+
</div>
|
| 253 |
+
|
| 254 |
+
## Adapters
|
| 255 |
+
|
| 256 |
+
LCMs are compatible with adapters like LoRA, ControlNet, T2I-Adapter, and AnimateDiff. You can bring the speed of LCMs to these adapters to generate images in a certain style or condition the model on another input like a canny image.
|
| 257 |
+
|
| 258 |
+
### LoRA
|
| 259 |
+
|
| 260 |
+
[LoRA](../tutorials/using_peft_for_inference) adapters can be rapidly finetuned to learn a new style from just a few images and plugged into a pretrained model to generate images in that style.
|
| 261 |
+
|
| 262 |
+
<hfoptions id="lcm-lora">
|
| 263 |
+
<hfoption id="LCM">
|
| 264 |
+
|
| 265 |
+
Load the LCM checkpoint for your supported model into [`UNet2DConditionModel`] and replace the scheduler with the [`LCMScheduler`]. Then you can use the [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] method to load the LoRA weights into the LCM and generate a styled image in a few steps.
|
| 266 |
+
|
| 267 |
+
```python
|
| 268 |
+
from diffusers import StableDiffusionXLPipeline, UNet2DConditionModel, LCMScheduler
|
| 269 |
+
import torch
|
| 270 |
+
|
| 271 |
+
unet = UNet2DConditionModel.from_pretrained(
|
| 272 |
+
"latent-consistency/lcm-sdxl",
|
| 273 |
+
torch_dtype=torch.float16,
|
| 274 |
+
variant="fp16",
|
| 275 |
+
)
|
| 276 |
+
pipe = StableDiffusionXLPipeline.from_pretrained(
|
| 277 |
+
"stabilityai/stable-diffusion-xl-base-1.0", unet=unet, torch_dtype=torch.float16, variant="fp16",
|
| 278 |
+
).to("cuda")
|
| 279 |
+
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)
|
| 280 |
+
pipe.load_lora_weights("TheLastBen/Papercut_SDXL", weight_name="papercut.safetensors", adapter_name="papercut")
|
| 281 |
+
|
| 282 |
+
prompt = "papercut, a cute fox"
|
| 283 |
+
generator = torch.manual_seed(0)
|
| 284 |
+
image = pipe(
|
| 285 |
+
prompt=prompt, num_inference_steps=4, generator=generator, guidance_scale=8.0
|
| 286 |
+
).images[0]
|
| 287 |
+
image
|
| 288 |
+
```
|
| 289 |
+
|
| 290 |
+
<div class="flex justify-center">
|
| 291 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/lcm/lcm_full_sdx_lora_mix.png"/>
|
| 292 |
+
</div>
|
| 293 |
+
|
| 294 |
+
</hfoption>
|
| 295 |
+
<hfoption id="LCM-LoRA">
|
| 296 |
+
|
| 297 |
+
Replace the scheduler with the [`LCMScheduler`]. Then you can use the [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] method to load the LCM-LoRA weights and the style LoRA you want to use. Combine both LoRA adapters with the [`~loaders.UNet2DConditionLoadersMixin.set_adapters`] method and generate a styled image in a few steps.
|
| 298 |
+
|
| 299 |
+
```py
|
| 300 |
+
import torch
|
| 301 |
+
from diffusers import DiffusionPipeline, LCMScheduler
|
| 302 |
+
|
| 303 |
+
pipe = DiffusionPipeline.from_pretrained(
|
| 304 |
+
"stabilityai/stable-diffusion-xl-base-1.0",
|
| 305 |
+
variant="fp16",
|
| 306 |
+
torch_dtype=torch.float16
|
| 307 |
+
).to("cuda")
|
| 308 |
+
|
| 309 |
+
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)
|
| 310 |
+
|
| 311 |
+
pipe.load_lora_weights("latent-consistency/lcm-lora-sdxl", adapter_name="lcm")
|
| 312 |
+
pipe.load_lora_weights("TheLastBen/Papercut_SDXL", weight_name="papercut.safetensors", adapter_name="papercut")
|
| 313 |
+
|
| 314 |
+
pipe.set_adapters(["lcm", "papercut"], adapter_weights=[1.0, 0.8])
|
| 315 |
+
|
| 316 |
+
prompt = "papercut, a cute fox"
|
| 317 |
+
generator = torch.manual_seed(0)
|
| 318 |
+
image = pipe(prompt, num_inference_steps=4, guidance_scale=1, generator=generator).images[0]
|
| 319 |
+
image
|
| 320 |
+
```
|
| 321 |
+
|
| 322 |
+
<div class="flex justify-center">
|
| 323 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/lcm/lcm_sdx_lora_mix.png"/>
|
| 324 |
+
</div>
|
| 325 |
+
|
| 326 |
+
</hfoption>
|
| 327 |
+
</hfoptions>
|
| 328 |
+
|
| 329 |
+
### ControlNet
|
| 330 |
+
|
| 331 |
+
[ControlNet](./controlnet) are adapters that can be trained on a variety of inputs like canny edge, pose estimation, or depth. The ControlNet can be inserted into the pipeline to provide additional conditioning and control to the model for more accurate generation.
|
| 332 |
+
|
| 333 |
+
You can find additional ControlNet models trained on other inputs in [lllyasviel's](https://hf.co/lllyasviel) repository.
|
| 334 |
+
|
| 335 |
+
<hfoptions id="lcm-controlnet">
|
| 336 |
+
<hfoption id="LCM">
|
| 337 |
+
|
| 338 |
+
Load a ControlNet model trained on canny images and pass it to the [`ControlNetModel`]. Then you can load a LCM model into [`StableDiffusionControlNetPipeline`] and replace the scheduler with the [`LCMScheduler`]. Now pass the canny image to the pipeline and generate an image.
|
| 339 |
+
|
| 340 |
+
> [!TIP]
|
| 341 |
+
> Experiment with different values for `num_inference_steps`, `controlnet_conditioning_scale`, `cross_attention_kwargs`, and `guidance_scale` to get the best results.
|
| 342 |
+
|
| 343 |
+
```python
|
| 344 |
+
import torch
|
| 345 |
+
import cv2
|
| 346 |
+
import numpy as np
|
| 347 |
+
from PIL import Image
|
| 348 |
+
|
| 349 |
+
from diffusers import StableDiffusionControlNetPipeline, ControlNetModel, LCMScheduler
|
| 350 |
+
from diffusers.utils import load_image, make_image_grid
|
| 351 |
+
|
| 352 |
+
image = load_image(
|
| 353 |
+
"https://hf.co/datasets/huggingface/documentation-images/resolve/main/diffusers/input_image_vermeer.png"
|
| 354 |
+
).resize((512, 512))
|
| 355 |
+
|
| 356 |
+
image = np.array(image)
|
| 357 |
+
|
| 358 |
+
low_threshold = 100
|
| 359 |
+
high_threshold = 200
|
| 360 |
+
|
| 361 |
+
image = cv2.Canny(image, low_threshold, high_threshold)
|
| 362 |
+
image = image[:, :, None]
|
| 363 |
+
image = np.concatenate([image, image, image], axis=2)
|
| 364 |
+
canny_image = Image.fromarray(image)
|
| 365 |
+
|
| 366 |
+
controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny", torch_dtype=torch.float16)
|
| 367 |
+
pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
| 368 |
+
"SimianLuo/LCM_Dreamshaper_v7",
|
| 369 |
+
controlnet=controlnet,
|
| 370 |
+
torch_dtype=torch.float16,
|
| 371 |
+
safety_checker=None,
|
| 372 |
+
).to("cuda")
|
| 373 |
+
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)
|
| 374 |
+
|
| 375 |
+
generator = torch.manual_seed(0)
|
| 376 |
+
image = pipe(
|
| 377 |
+
"the mona lisa",
|
| 378 |
+
image=canny_image,
|
| 379 |
+
num_inference_steps=4,
|
| 380 |
+
generator=generator,
|
| 381 |
+
).images[0]
|
| 382 |
+
make_image_grid([canny_image, image], rows=1, cols=2)
|
| 383 |
+
```
|
| 384 |
+
|
| 385 |
+
<div class="flex justify-center">
|
| 386 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/lcm/lcm_full_sdv1-5_controlnet.png"/>
|
| 387 |
+
</div>
|
| 388 |
+
|
| 389 |
+
</hfoption>
|
| 390 |
+
<hfoption id="LCM-LoRA">
|
| 391 |
+
|
| 392 |
+
Load a ControlNet model trained on canny images and pass it to the [`ControlNetModel`]. Then you can load a Stable Diffusion v1.5 model into [`StableDiffusionControlNetPipeline`] and replace the scheduler with the [`LCMScheduler`]. Use the [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] method to load the LCM-LoRA weights, and pass the canny image to the pipeline and generate an image.
|
| 393 |
+
|
| 394 |
+
> [!TIP]
|
| 395 |
+
> Experiment with different values for `num_inference_steps`, `controlnet_conditioning_scale`, `cross_attention_kwargs`, and `guidance_scale` to get the best results.
|
| 396 |
+
|
| 397 |
+
```py
|
| 398 |
+
import torch
|
| 399 |
+
import cv2
|
| 400 |
+
import numpy as np
|
| 401 |
+
from PIL import Image
|
| 402 |
+
|
| 403 |
+
from diffusers import StableDiffusionControlNetPipeline, ControlNetModel, LCMScheduler
|
| 404 |
+
from diffusers.utils import load_image
|
| 405 |
+
|
| 406 |
+
image = load_image(
|
| 407 |
+
"https://hf.co/datasets/huggingface/documentation-images/resolve/main/diffusers/input_image_vermeer.png"
|
| 408 |
+
).resize((512, 512))
|
| 409 |
+
|
| 410 |
+
image = np.array(image)
|
| 411 |
+
|
| 412 |
+
low_threshold = 100
|
| 413 |
+
high_threshold = 200
|
| 414 |
+
|
| 415 |
+
image = cv2.Canny(image, low_threshold, high_threshold)
|
| 416 |
+
image = image[:, :, None]
|
| 417 |
+
image = np.concatenate([image, image, image], axis=2)
|
| 418 |
+
canny_image = Image.fromarray(image)
|
| 419 |
+
|
| 420 |
+
controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny", torch_dtype=torch.float16)
|
| 421 |
+
pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
| 422 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5",
|
| 423 |
+
controlnet=controlnet,
|
| 424 |
+
torch_dtype=torch.float16,
|
| 425 |
+
safety_checker=None,
|
| 426 |
+
variant="fp16"
|
| 427 |
+
).to("cuda")
|
| 428 |
+
|
| 429 |
+
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)
|
| 430 |
+
|
| 431 |
+
pipe.load_lora_weights("latent-consistency/lcm-lora-sdv1-5")
|
| 432 |
+
|
| 433 |
+
generator = torch.manual_seed(0)
|
| 434 |
+
image = pipe(
|
| 435 |
+
"the mona lisa",
|
| 436 |
+
image=canny_image,
|
| 437 |
+
num_inference_steps=4,
|
| 438 |
+
guidance_scale=1.5,
|
| 439 |
+
controlnet_conditioning_scale=0.8,
|
| 440 |
+
cross_attention_kwargs={"scale": 1},
|
| 441 |
+
generator=generator,
|
| 442 |
+
).images[0]
|
| 443 |
+
image
|
| 444 |
+
```
|
| 445 |
+
|
| 446 |
+
<div class="flex justify-center">
|
| 447 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/lcm/lcm_sdv1-5_controlnet.png"/>
|
| 448 |
+
</div>
|
| 449 |
+
|
| 450 |
+
</hfoption>
|
| 451 |
+
</hfoptions>
|
| 452 |
+
|
| 453 |
+
### T2I-Adapter
|
| 454 |
+
|
| 455 |
+
[T2I-Adapter](./t2i_adapter) is an even more lightweight adapter than ControlNet, that provides an additional input to condition a pretrained model with. It is faster than ControlNet but the results may be slightly worse.
|
| 456 |
+
|
| 457 |
+
You can find additional T2I-Adapter checkpoints trained on other inputs in [TencentArc's](https://hf.co/TencentARC) repository.
|
| 458 |
+
|
| 459 |
+
<hfoptions id="lcm-t2i">
|
| 460 |
+
<hfoption id="LCM">
|
| 461 |
+
|
| 462 |
+
Load a T2IAdapter trained on canny images and pass it to the [`StableDiffusionXLAdapterPipeline`]. Then load a LCM checkpoint into [`UNet2DConditionModel`] and replace the scheduler with the [`LCMScheduler`]. Now pass the canny image to the pipeline and generate an image.
|
| 463 |
+
|
| 464 |
+
```python
|
| 465 |
+
import torch
|
| 466 |
+
import cv2
|
| 467 |
+
import numpy as np
|
| 468 |
+
from PIL import Image
|
| 469 |
+
|
| 470 |
+
from diffusers import StableDiffusionXLAdapterPipeline, UNet2DConditionModel, T2IAdapter, LCMScheduler
|
| 471 |
+
from diffusers.utils import load_image, make_image_grid
|
| 472 |
+
|
| 473 |
+
# detect the canny map in low resolution to avoid high-frequency details
|
| 474 |
+
image = load_image(
|
| 475 |
+
"https://hf.co/datasets/huggingface/documentation-images/resolve/main/diffusers/input_image_vermeer.png"
|
| 476 |
+
).resize((384, 384))
|
| 477 |
+
|
| 478 |
+
image = np.array(image)
|
| 479 |
+
|
| 480 |
+
low_threshold = 100
|
| 481 |
+
high_threshold = 200
|
| 482 |
+
|
| 483 |
+
image = cv2.Canny(image, low_threshold, high_threshold)
|
| 484 |
+
image = image[:, :, None]
|
| 485 |
+
image = np.concatenate([image, image, image], axis=2)
|
| 486 |
+
canny_image = Image.fromarray(image).resize((1024, 1216))
|
| 487 |
+
|
| 488 |
+
adapter = T2IAdapter.from_pretrained("TencentARC/t2i-adapter-canny-sdxl-1.0", torch_dtype=torch.float16, variant="fp16").to("cuda")
|
| 489 |
+
|
| 490 |
+
unet = UNet2DConditionModel.from_pretrained(
|
| 491 |
+
"latent-consistency/lcm-sdxl",
|
| 492 |
+
torch_dtype=torch.float16,
|
| 493 |
+
variant="fp16",
|
| 494 |
+
)
|
| 495 |
+
pipe = StableDiffusionXLAdapterPipeline.from_pretrained(
|
| 496 |
+
"stabilityai/stable-diffusion-xl-base-1.0",
|
| 497 |
+
unet=unet,
|
| 498 |
+
adapter=adapter,
|
| 499 |
+
torch_dtype=torch.float16,
|
| 500 |
+
variant="fp16",
|
| 501 |
+
).to("cuda")
|
| 502 |
+
|
| 503 |
+
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)
|
| 504 |
+
|
| 505 |
+
prompt = "the mona lisa, 4k picture, high quality"
|
| 506 |
+
negative_prompt = "extra digit, fewer digits, cropped, worst quality, low quality, glitch, deformed, mutated, ugly, disfigured"
|
| 507 |
+
|
| 508 |
+
generator = torch.manual_seed(0)
|
| 509 |
+
image = pipe(
|
| 510 |
+
prompt=prompt,
|
| 511 |
+
negative_prompt=negative_prompt,
|
| 512 |
+
image=canny_image,
|
| 513 |
+
num_inference_steps=4,
|
| 514 |
+
guidance_scale=5,
|
| 515 |
+
adapter_conditioning_scale=0.8,
|
| 516 |
+
adapter_conditioning_factor=1,
|
| 517 |
+
generator=generator,
|
| 518 |
+
).images[0]
|
| 519 |
+
```
|
| 520 |
+
|
| 521 |
+
<div class="flex justify-center">
|
| 522 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/lcm-t2i.png"/>
|
| 523 |
+
</div>
|
| 524 |
+
|
| 525 |
+
</hfoption>
|
| 526 |
+
<hfoption id="LCM-LoRA">
|
| 527 |
+
|
| 528 |
+
Load a T2IAdapter trained on canny images and pass it to the [`StableDiffusionXLAdapterPipeline`]. Replace the scheduler with the [`LCMScheduler`], and use the [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] method to load the LCM-LoRA weights. Pass the canny image to the pipeline and generate an image.
|
| 529 |
+
|
| 530 |
+
```py
|
| 531 |
+
import torch
|
| 532 |
+
import cv2
|
| 533 |
+
import numpy as np
|
| 534 |
+
from PIL import Image
|
| 535 |
+
|
| 536 |
+
from diffusers import StableDiffusionXLAdapterPipeline, UNet2DConditionModel, T2IAdapter, LCMScheduler
|
| 537 |
+
from diffusers.utils import load_image, make_image_grid
|
| 538 |
+
|
| 539 |
+
# detect the canny map in low resolution to avoid high-frequency details
|
| 540 |
+
image = load_image(
|
| 541 |
+
"https://hf.co/datasets/huggingface/documentation-images/resolve/main/diffusers/input_image_vermeer.png"
|
| 542 |
+
).resize((384, 384))
|
| 543 |
+
|
| 544 |
+
image = np.array(image)
|
| 545 |
+
|
| 546 |
+
low_threshold = 100
|
| 547 |
+
high_threshold = 200
|
| 548 |
+
|
| 549 |
+
image = cv2.Canny(image, low_threshold, high_threshold)
|
| 550 |
+
image = image[:, :, None]
|
| 551 |
+
image = np.concatenate([image, image, image], axis=2)
|
| 552 |
+
canny_image = Image.fromarray(image).resize((1024, 1024))
|
| 553 |
+
|
| 554 |
+
adapter = T2IAdapter.from_pretrained("TencentARC/t2i-adapter-canny-sdxl-1.0", torch_dtype=torch.float16, variant="fp16").to("cuda")
|
| 555 |
+
|
| 556 |
+
pipe = StableDiffusionXLAdapterPipeline.from_pretrained(
|
| 557 |
+
"stabilityai/stable-diffusion-xl-base-1.0",
|
| 558 |
+
adapter=adapter,
|
| 559 |
+
torch_dtype=torch.float16,
|
| 560 |
+
variant="fp16",
|
| 561 |
+
).to("cuda")
|
| 562 |
+
|
| 563 |
+
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)
|
| 564 |
+
|
| 565 |
+
pipe.load_lora_weights("latent-consistency/lcm-lora-sdxl")
|
| 566 |
+
|
| 567 |
+
prompt = "the mona lisa, 4k picture, high quality"
|
| 568 |
+
negative_prompt = "extra digit, fewer digits, cropped, worst quality, low quality, glitch, deformed, mutated, ugly, disfigured"
|
| 569 |
+
|
| 570 |
+
generator = torch.manual_seed(0)
|
| 571 |
+
image = pipe(
|
| 572 |
+
prompt=prompt,
|
| 573 |
+
negative_prompt=negative_prompt,
|
| 574 |
+
image=canny_image,
|
| 575 |
+
num_inference_steps=4,
|
| 576 |
+
guidance_scale=1.5,
|
| 577 |
+
adapter_conditioning_scale=0.8,
|
| 578 |
+
adapter_conditioning_factor=1,
|
| 579 |
+
generator=generator,
|
| 580 |
+
).images[0]
|
| 581 |
+
```
|
| 582 |
+
|
| 583 |
+
<div class="flex justify-center">
|
| 584 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/lcm-lora-t2i.png"/>
|
| 585 |
+
</div>
|
| 586 |
+
|
| 587 |
+
</hfoption>
|
| 588 |
+
</hfoptions>
|
| 589 |
+
|
| 590 |
+
### AnimateDiff
|
| 591 |
+
|
| 592 |
+
[AnimateDiff](../api/pipelines/animatediff) is an adapter that adds motion to an image. It can be used with most Stable Diffusion models, effectively turning them into "video generation" models. Generating good results with a video model usually requires generating multiple frames (16-24), which can be very slow with a regular Stable Diffusion model. LCM-LoRA can speed up this process by only taking 4-8 steps for each frame.
|
| 593 |
+
|
| 594 |
+
Load a [`AnimateDiffPipeline`] and pass a [`MotionAdapter`] to it. Then replace the scheduler with the [`LCMScheduler`], and combine both LoRA adapters with the [`~loaders.UNet2DConditionLoadersMixin.set_adapters`] method. Now you can pass a prompt to the pipeline and generate an animated image.
|
| 595 |
+
|
| 596 |
+
```py
|
| 597 |
+
import torch
|
| 598 |
+
from diffusers import MotionAdapter, AnimateDiffPipeline, DDIMScheduler, LCMScheduler
|
| 599 |
+
from diffusers.utils import export_to_gif
|
| 600 |
+
|
| 601 |
+
adapter = MotionAdapter.from_pretrained("guoyww/animatediff-motion-adapter-v1-5")
|
| 602 |
+
pipe = AnimateDiffPipeline.from_pretrained(
|
| 603 |
+
"frankjoshua/toonyou_beta6",
|
| 604 |
+
motion_adapter=adapter,
|
| 605 |
+
).to("cuda")
|
| 606 |
+
|
| 607 |
+
# set scheduler
|
| 608 |
+
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)
|
| 609 |
+
|
| 610 |
+
# load LCM-LoRA
|
| 611 |
+
pipe.load_lora_weights("latent-consistency/lcm-lora-sdv1-5", adapter_name="lcm")
|
| 612 |
+
pipe.load_lora_weights("guoyww/animatediff-motion-lora-zoom-in", weight_name="diffusion_pytorch_model.safetensors", adapter_name="motion-lora")
|
| 613 |
+
|
| 614 |
+
pipe.set_adapters(["lcm", "motion-lora"], adapter_weights=[0.55, 1.2])
|
| 615 |
+
|
| 616 |
+
prompt = "best quality, masterpiece, 1girl, looking at viewer, blurry background, upper body, contemporary, dress"
|
| 617 |
+
generator = torch.manual_seed(0)
|
| 618 |
+
frames = pipe(
|
| 619 |
+
prompt=prompt,
|
| 620 |
+
num_inference_steps=5,
|
| 621 |
+
guidance_scale=1.25,
|
| 622 |
+
cross_attention_kwargs={"scale": 1},
|
| 623 |
+
num_frames=24,
|
| 624 |
+
generator=generator
|
| 625 |
+
).frames[0]
|
| 626 |
+
export_to_gif(frames, "animation.gif")
|
| 627 |
+
```
|
| 628 |
+
|
| 629 |
+
<div class="flex justify-center">
|
| 630 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/lcm-lora-animatediff.gif"/>
|
| 631 |
+
</div>
|
tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/inference_with_tcd_lora.md
ADDED
|
@@ -0,0 +1,437 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# Trajectory Consistency Distillation-LoRA
|
| 16 |
+
|
| 17 |
+
Trajectory Consistency Distillation (TCD) enables a model to generate higher quality and more detailed images with fewer steps. Moreover, owing to the effective error mitigation during the distillation process, TCD demonstrates superior performance even under conditions of large inference steps.
|
| 18 |
+
|
| 19 |
+
The major advantages of TCD are:
|
| 20 |
+
|
| 21 |
+
- Better than Teacher: TCD demonstrates superior generative quality at both small and large inference steps and exceeds the performance of [DPM-Solver++(2S)](../api/schedulers/multistep_dpm_solver) with Stable Diffusion XL (SDXL). There is no additional discriminator or LPIPS supervision included during TCD training.
|
| 22 |
+
|
| 23 |
+
- Flexible Inference Steps: The inference steps for TCD sampling can be freely adjusted without adversely affecting the image quality.
|
| 24 |
+
|
| 25 |
+
- Freely change detail level: During inference, the level of detail in the image can be adjusted with a single hyperparameter, *gamma*.
|
| 26 |
+
|
| 27 |
+
> [!TIP]
|
| 28 |
+
> For more technical details of TCD, please refer to the [paper](https://huggingface.co/papers/2402.19159) or official [project page](https://mhh0318.github.io/tcd/).
|
| 29 |
+
|
| 30 |
+
For large models like SDXL, TCD is trained with [LoRA](https://huggingface.co/docs/peft/conceptual_guides/adapter#low-rank-adaptation-lora) to reduce memory usage. This is also useful because you can reuse LoRAs between different finetuned models, as long as they share the same base model, without further training.
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
This guide will show you how to perform inference with TCD-LoRAs for a variety of tasks like text-to-image and inpainting, as well as how you can easily combine TCD-LoRAs with other adapters. Choose one of the supported base model and it's corresponding TCD-LoRA checkpoint from the table below to get started.
|
| 35 |
+
|
| 36 |
+
| Base model | TCD-LoRA checkpoint |
|
| 37 |
+
|-------------------------------------------------------------------------------------------------|----------------------------------------------------------------|
|
| 38 |
+
| [stable-diffusion-v1-5](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5) | [TCD-SD15](https://huggingface.co/h1t/TCD-SD15-LoRA) |
|
| 39 |
+
| [stable-diffusion-2-1-base](https://huggingface.co/stabilityai/stable-diffusion-2-1-base) | [TCD-SD21-base](https://huggingface.co/h1t/TCD-SD21-base-LoRA) |
|
| 40 |
+
| [stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0) | [TCD-SDXL](https://huggingface.co/h1t/TCD-SDXL-LoRA) |
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
Make sure you have [PEFT](https://github.com/huggingface/peft) installed for better LoRA support.
|
| 44 |
+
|
| 45 |
+
```bash
|
| 46 |
+
pip install -U peft
|
| 47 |
+
```
|
| 48 |
+
|
| 49 |
+
## General tasks
|
| 50 |
+
|
| 51 |
+
In this guide, let's use the [`StableDiffusionXLPipeline`] and the [`TCDScheduler`]. Use the [`~StableDiffusionPipeline.load_lora_weights`] method to load the SDXL-compatible TCD-LoRA weights.
|
| 52 |
+
|
| 53 |
+
A few tips to keep in mind for TCD-LoRA inference are to:
|
| 54 |
+
|
| 55 |
+
- Keep the `num_inference_steps` between 4 and 50
|
| 56 |
+
- Set `eta` (used to control stochasticity at each step) between 0 and 1. You should use a higher `eta` when increasing the number of inference steps, but the downside is that a larger `eta` in [`TCDScheduler`] leads to blurrier images. A value of 0.3 is recommended to produce good results.
|
| 57 |
+
|
| 58 |
+
<hfoptions id="tasks">
|
| 59 |
+
<hfoption id="text-to-image">
|
| 60 |
+
|
| 61 |
+
```python
|
| 62 |
+
import torch
|
| 63 |
+
from diffusers import StableDiffusionXLPipeline, TCDScheduler
|
| 64 |
+
|
| 65 |
+
device = "cuda"
|
| 66 |
+
base_model_id = "stabilityai/stable-diffusion-xl-base-1.0"
|
| 67 |
+
tcd_lora_id = "h1t/TCD-SDXL-LoRA"
|
| 68 |
+
|
| 69 |
+
pipe = StableDiffusionXLPipeline.from_pretrained(base_model_id, torch_dtype=torch.float16, variant="fp16").to(device)
|
| 70 |
+
pipe.scheduler = TCDScheduler.from_config(pipe.scheduler.config)
|
| 71 |
+
|
| 72 |
+
pipe.load_lora_weights(tcd_lora_id)
|
| 73 |
+
pipe.fuse_lora()
|
| 74 |
+
|
| 75 |
+
prompt = "Painting of the orange cat Otto von Garfield, Count of Bismarck-Schönhausen, Duke of Lauenburg, Minister-President of Prussia. Depicted wearing a Prussian Pickelhaube and eating his favorite meal - lasagna."
|
| 76 |
+
|
| 77 |
+
image = pipe(
|
| 78 |
+
prompt=prompt,
|
| 79 |
+
num_inference_steps=4,
|
| 80 |
+
guidance_scale=0,
|
| 81 |
+
eta=0.3,
|
| 82 |
+
generator=torch.Generator(device=device).manual_seed(0),
|
| 83 |
+
).images[0]
|
| 84 |
+
```
|
| 85 |
+
|
| 86 |
+

|
| 87 |
+
|
| 88 |
+
</hfoption>
|
| 89 |
+
|
| 90 |
+
<hfoption id="inpainting">
|
| 91 |
+
|
| 92 |
+
```python
|
| 93 |
+
import torch
|
| 94 |
+
from diffusers import AutoPipelineForInpainting, TCDScheduler
|
| 95 |
+
from diffusers.utils import load_image, make_image_grid
|
| 96 |
+
|
| 97 |
+
device = "cuda"
|
| 98 |
+
base_model_id = "diffusers/stable-diffusion-xl-1.0-inpainting-0.1"
|
| 99 |
+
tcd_lora_id = "h1t/TCD-SDXL-LoRA"
|
| 100 |
+
|
| 101 |
+
pipe = AutoPipelineForInpainting.from_pretrained(base_model_id, torch_dtype=torch.float16, variant="fp16").to(device)
|
| 102 |
+
pipe.scheduler = TCDScheduler.from_config(pipe.scheduler.config)
|
| 103 |
+
|
| 104 |
+
pipe.load_lora_weights(tcd_lora_id)
|
| 105 |
+
pipe.fuse_lora()
|
| 106 |
+
|
| 107 |
+
img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
|
| 108 |
+
mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
|
| 109 |
+
|
| 110 |
+
init_image = load_image(img_url).resize((1024, 1024))
|
| 111 |
+
mask_image = load_image(mask_url).resize((1024, 1024))
|
| 112 |
+
|
| 113 |
+
prompt = "a tiger sitting on a park bench"
|
| 114 |
+
|
| 115 |
+
image = pipe(
|
| 116 |
+
prompt=prompt,
|
| 117 |
+
image=init_image,
|
| 118 |
+
mask_image=mask_image,
|
| 119 |
+
num_inference_steps=8,
|
| 120 |
+
guidance_scale=0,
|
| 121 |
+
eta=0.3,
|
| 122 |
+
strength=0.99, # make sure to use `strength` below 1.0
|
| 123 |
+
generator=torch.Generator(device=device).manual_seed(0),
|
| 124 |
+
).images[0]
|
| 125 |
+
|
| 126 |
+
grid_image = make_image_grid([init_image, mask_image, image], rows=1, cols=3)
|
| 127 |
+
```
|
| 128 |
+
|
| 129 |
+

|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
</hfoption>
|
| 133 |
+
</hfoptions>
|
| 134 |
+
|
| 135 |
+
## Community models
|
| 136 |
+
|
| 137 |
+
TCD-LoRA also works with many community finetuned models and plugins. For example, load the [animagine-xl-3.0](https://huggingface.co/cagliostrolab/animagine-xl-3.0) checkpoint which is a community finetuned version of SDXL for generating anime images.
|
| 138 |
+
|
| 139 |
+
```python
|
| 140 |
+
import torch
|
| 141 |
+
from diffusers import StableDiffusionXLPipeline, TCDScheduler
|
| 142 |
+
|
| 143 |
+
device = "cuda"
|
| 144 |
+
base_model_id = "cagliostrolab/animagine-xl-3.0"
|
| 145 |
+
tcd_lora_id = "h1t/TCD-SDXL-LoRA"
|
| 146 |
+
|
| 147 |
+
pipe = StableDiffusionXLPipeline.from_pretrained(base_model_id, torch_dtype=torch.float16, variant="fp16").to(device)
|
| 148 |
+
pipe.scheduler = TCDScheduler.from_config(pipe.scheduler.config)
|
| 149 |
+
|
| 150 |
+
pipe.load_lora_weights(tcd_lora_id)
|
| 151 |
+
pipe.fuse_lora()
|
| 152 |
+
|
| 153 |
+
prompt = "A man, clad in a meticulously tailored military uniform, stands with unwavering resolve. The uniform boasts intricate details, and his eyes gleam with determination. Strands of vibrant, windswept hair peek out from beneath the brim of his cap."
|
| 154 |
+
|
| 155 |
+
image = pipe(
|
| 156 |
+
prompt=prompt,
|
| 157 |
+
num_inference_steps=8,
|
| 158 |
+
guidance_scale=0,
|
| 159 |
+
eta=0.3,
|
| 160 |
+
generator=torch.Generator(device=device).manual_seed(0),
|
| 161 |
+
).images[0]
|
| 162 |
+
```
|
| 163 |
+
|
| 164 |
+

|
| 165 |
+
|
| 166 |
+
TCD-LoRA also supports other LoRAs trained on different styles. For example, let's load the [TheLastBen/Papercut_SDXL](https://huggingface.co/TheLastBen/Papercut_SDXL) LoRA and fuse it with the TCD-LoRA with the [`~loaders.UNet2DConditionLoadersMixin.set_adapters`] method.
|
| 167 |
+
|
| 168 |
+
> [!TIP]
|
| 169 |
+
> Check out the [Merge LoRAs](../tutorials/using_peft_for_inference#merge) guide to learn more about efficient merging methods.
|
| 170 |
+
|
| 171 |
+
```python
|
| 172 |
+
import torch
|
| 173 |
+
from diffusers import StableDiffusionXLPipeline
|
| 174 |
+
from scheduling_tcd import TCDScheduler
|
| 175 |
+
|
| 176 |
+
device = "cuda"
|
| 177 |
+
base_model_id = "stabilityai/stable-diffusion-xl-base-1.0"
|
| 178 |
+
tcd_lora_id = "h1t/TCD-SDXL-LoRA"
|
| 179 |
+
styled_lora_id = "TheLastBen/Papercut_SDXL"
|
| 180 |
+
|
| 181 |
+
pipe = StableDiffusionXLPipeline.from_pretrained(base_model_id, torch_dtype=torch.float16, variant="fp16").to(device)
|
| 182 |
+
pipe.scheduler = TCDScheduler.from_config(pipe.scheduler.config)
|
| 183 |
+
|
| 184 |
+
pipe.load_lora_weights(tcd_lora_id, adapter_name="tcd")
|
| 185 |
+
pipe.load_lora_weights(styled_lora_id, adapter_name="style")
|
| 186 |
+
pipe.set_adapters(["tcd", "style"], adapter_weights=[1.0, 1.0])
|
| 187 |
+
|
| 188 |
+
prompt = "papercut of a winter mountain, snow"
|
| 189 |
+
|
| 190 |
+
image = pipe(
|
| 191 |
+
prompt=prompt,
|
| 192 |
+
num_inference_steps=4,
|
| 193 |
+
guidance_scale=0,
|
| 194 |
+
eta=0.3,
|
| 195 |
+
generator=torch.Generator(device=device).manual_seed(0),
|
| 196 |
+
).images[0]
|
| 197 |
+
```
|
| 198 |
+
|
| 199 |
+

|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
## Adapters
|
| 203 |
+
|
| 204 |
+
TCD-LoRA is very versatile, and it can be combined with other adapter types like ControlNets, IP-Adapter, and AnimateDiff.
|
| 205 |
+
|
| 206 |
+
<hfoptions id="adapters">
|
| 207 |
+
<hfoption id="ControlNet">
|
| 208 |
+
|
| 209 |
+
### Depth ControlNet
|
| 210 |
+
|
| 211 |
+
```python
|
| 212 |
+
import torch
|
| 213 |
+
import numpy as np
|
| 214 |
+
from PIL import Image
|
| 215 |
+
from transformers import DPTImageProcessor, DPTForDepthEstimation
|
| 216 |
+
from diffusers import ControlNetModel, StableDiffusionXLControlNetPipeline
|
| 217 |
+
from diffusers.utils import load_image, make_image_grid
|
| 218 |
+
from scheduling_tcd import TCDScheduler
|
| 219 |
+
|
| 220 |
+
device = "cuda"
|
| 221 |
+
depth_estimator = DPTForDepthEstimation.from_pretrained("Intel/dpt-hybrid-midas").to(device)
|
| 222 |
+
feature_extractor = DPTImageProcessor.from_pretrained("Intel/dpt-hybrid-midas")
|
| 223 |
+
|
| 224 |
+
def get_depth_map(image):
|
| 225 |
+
image = feature_extractor(images=image, return_tensors="pt").pixel_values.to(device)
|
| 226 |
+
with torch.no_grad(), torch.autocast(device):
|
| 227 |
+
depth_map = depth_estimator(image).predicted_depth
|
| 228 |
+
|
| 229 |
+
depth_map = torch.nn.functional.interpolate(
|
| 230 |
+
depth_map.unsqueeze(1),
|
| 231 |
+
size=(1024, 1024),
|
| 232 |
+
mode="bicubic",
|
| 233 |
+
align_corners=False,
|
| 234 |
+
)
|
| 235 |
+
depth_min = torch.amin(depth_map, dim=[1, 2, 3], keepdim=True)
|
| 236 |
+
depth_max = torch.amax(depth_map, dim=[1, 2, 3], keepdim=True)
|
| 237 |
+
depth_map = (depth_map - depth_min) / (depth_max - depth_min)
|
| 238 |
+
image = torch.cat([depth_map] * 3, dim=1)
|
| 239 |
+
|
| 240 |
+
image = image.permute(0, 2, 3, 1).cpu().numpy()[0]
|
| 241 |
+
image = Image.fromarray((image * 255.0).clip(0, 255).astype(np.uint8))
|
| 242 |
+
return image
|
| 243 |
+
|
| 244 |
+
base_model_id = "stabilityai/stable-diffusion-xl-base-1.0"
|
| 245 |
+
controlnet_id = "diffusers/controlnet-depth-sdxl-1.0"
|
| 246 |
+
tcd_lora_id = "h1t/TCD-SDXL-LoRA"
|
| 247 |
+
|
| 248 |
+
controlnet = ControlNetModel.from_pretrained(
|
| 249 |
+
controlnet_id,
|
| 250 |
+
torch_dtype=torch.float16,
|
| 251 |
+
variant="fp16",
|
| 252 |
+
)
|
| 253 |
+
pipe = StableDiffusionXLControlNetPipeline.from_pretrained(
|
| 254 |
+
base_model_id,
|
| 255 |
+
controlnet=controlnet,
|
| 256 |
+
torch_dtype=torch.float16,
|
| 257 |
+
variant="fp16",
|
| 258 |
+
)
|
| 259 |
+
pipe.enable_model_cpu_offload()
|
| 260 |
+
|
| 261 |
+
pipe.scheduler = TCDScheduler.from_config(pipe.scheduler.config)
|
| 262 |
+
|
| 263 |
+
pipe.load_lora_weights(tcd_lora_id)
|
| 264 |
+
pipe.fuse_lora()
|
| 265 |
+
|
| 266 |
+
prompt = "stormtrooper lecture, photorealistic"
|
| 267 |
+
|
| 268 |
+
image = load_image("https://huggingface.co/lllyasviel/sd-controlnet-depth/resolve/main/images/stormtrooper.png")
|
| 269 |
+
depth_image = get_depth_map(image)
|
| 270 |
+
|
| 271 |
+
controlnet_conditioning_scale = 0.5 # recommended for good generalization
|
| 272 |
+
|
| 273 |
+
image = pipe(
|
| 274 |
+
prompt,
|
| 275 |
+
image=depth_image,
|
| 276 |
+
num_inference_steps=4,
|
| 277 |
+
guidance_scale=0,
|
| 278 |
+
eta=0.3,
|
| 279 |
+
controlnet_conditioning_scale=controlnet_conditioning_scale,
|
| 280 |
+
generator=torch.Generator(device=device).manual_seed(0),
|
| 281 |
+
).images[0]
|
| 282 |
+
|
| 283 |
+
grid_image = make_image_grid([depth_image, image], rows=1, cols=2)
|
| 284 |
+
```
|
| 285 |
+
|
| 286 |
+

|
| 287 |
+
|
| 288 |
+
### Canny ControlNet
|
| 289 |
+
```python
|
| 290 |
+
import torch
|
| 291 |
+
from diffusers import ControlNetModel, StableDiffusionXLControlNetPipeline
|
| 292 |
+
from diffusers.utils import load_image, make_image_grid
|
| 293 |
+
from scheduling_tcd import TCDScheduler
|
| 294 |
+
|
| 295 |
+
device = "cuda"
|
| 296 |
+
base_model_id = "stabilityai/stable-diffusion-xl-base-1.0"
|
| 297 |
+
controlnet_id = "diffusers/controlnet-canny-sdxl-1.0"
|
| 298 |
+
tcd_lora_id = "h1t/TCD-SDXL-LoRA"
|
| 299 |
+
|
| 300 |
+
controlnet = ControlNetModel.from_pretrained(
|
| 301 |
+
controlnet_id,
|
| 302 |
+
torch_dtype=torch.float16,
|
| 303 |
+
variant="fp16",
|
| 304 |
+
)
|
| 305 |
+
pipe = StableDiffusionXLControlNetPipeline.from_pretrained(
|
| 306 |
+
base_model_id,
|
| 307 |
+
controlnet=controlnet,
|
| 308 |
+
torch_dtype=torch.float16,
|
| 309 |
+
variant="fp16",
|
| 310 |
+
)
|
| 311 |
+
pipe.enable_model_cpu_offload()
|
| 312 |
+
|
| 313 |
+
pipe.scheduler = TCDScheduler.from_config(pipe.scheduler.config)
|
| 314 |
+
|
| 315 |
+
pipe.load_lora_weights(tcd_lora_id)
|
| 316 |
+
pipe.fuse_lora()
|
| 317 |
+
|
| 318 |
+
prompt = "ultrarealistic shot of a furry blue bird"
|
| 319 |
+
|
| 320 |
+
canny_image = load_image("https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png")
|
| 321 |
+
|
| 322 |
+
controlnet_conditioning_scale = 0.5 # recommended for good generalization
|
| 323 |
+
|
| 324 |
+
image = pipe(
|
| 325 |
+
prompt,
|
| 326 |
+
image=canny_image,
|
| 327 |
+
num_inference_steps=4,
|
| 328 |
+
guidance_scale=0,
|
| 329 |
+
eta=0.3,
|
| 330 |
+
controlnet_conditioning_scale=controlnet_conditioning_scale,
|
| 331 |
+
generator=torch.Generator(device=device).manual_seed(0),
|
| 332 |
+
).images[0]
|
| 333 |
+
|
| 334 |
+
grid_image = make_image_grid([canny_image, image], rows=1, cols=2)
|
| 335 |
+
```
|
| 336 |
+

|
| 337 |
+
|
| 338 |
+
> [!TIP]
|
| 339 |
+
> The inference parameters in this example might not work for all examples, so we recommend you to try different values for `num_inference_steps`, `guidance_scale`, `controlnet_conditioning_scale` and `cross_attention_kwargs` parameters and choose the best one.
|
| 340 |
+
|
| 341 |
+
</hfoption>
|
| 342 |
+
<hfoption id="IP-Adapter">
|
| 343 |
+
|
| 344 |
+
This example shows how to use the TCD-LoRA with the [IP-Adapter](https://github.com/tencent-ailab/IP-Adapter/tree/main) and SDXL.
|
| 345 |
+
|
| 346 |
+
```python
|
| 347 |
+
import torch
|
| 348 |
+
from diffusers import StableDiffusionXLPipeline
|
| 349 |
+
from diffusers.utils import load_image, make_image_grid
|
| 350 |
+
|
| 351 |
+
from ip_adapter import IPAdapterXL
|
| 352 |
+
from scheduling_tcd import TCDScheduler
|
| 353 |
+
|
| 354 |
+
device = "cuda"
|
| 355 |
+
base_model_path = "stabilityai/stable-diffusion-xl-base-1.0"
|
| 356 |
+
image_encoder_path = "sdxl_models/image_encoder"
|
| 357 |
+
ip_ckpt = "sdxl_models/ip-adapter_sdxl.bin"
|
| 358 |
+
tcd_lora_id = "h1t/TCD-SDXL-LoRA"
|
| 359 |
+
|
| 360 |
+
pipe = StableDiffusionXLPipeline.from_pretrained(
|
| 361 |
+
base_model_path,
|
| 362 |
+
torch_dtype=torch.float16,
|
| 363 |
+
variant="fp16"
|
| 364 |
+
)
|
| 365 |
+
pipe.scheduler = TCDScheduler.from_config(pipe.scheduler.config)
|
| 366 |
+
|
| 367 |
+
pipe.load_lora_weights(tcd_lora_id)
|
| 368 |
+
pipe.fuse_lora()
|
| 369 |
+
|
| 370 |
+
ip_model = IPAdapterXL(pipe, image_encoder_path, ip_ckpt, device)
|
| 371 |
+
|
| 372 |
+
ref_image = load_image("https://raw.githubusercontent.com/tencent-ailab/IP-Adapter/main/assets/images/woman.png").resize((512, 512))
|
| 373 |
+
|
| 374 |
+
prompt = "best quality, high quality, wearing sunglasses"
|
| 375 |
+
|
| 376 |
+
image = ip_model.generate(
|
| 377 |
+
pil_image=ref_image,
|
| 378 |
+
prompt=prompt,
|
| 379 |
+
scale=0.5,
|
| 380 |
+
num_samples=1,
|
| 381 |
+
num_inference_steps=4,
|
| 382 |
+
guidance_scale=0,
|
| 383 |
+
eta=0.3,
|
| 384 |
+
seed=0,
|
| 385 |
+
)[0]
|
| 386 |
+
|
| 387 |
+
grid_image = make_image_grid([ref_image, image], rows=1, cols=2)
|
| 388 |
+
```
|
| 389 |
+
|
| 390 |
+

|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
</hfoption>
|
| 395 |
+
<hfoption id="AnimateDiff">
|
| 396 |
+
|
| 397 |
+
[`AnimateDiff`] allows animating images using Stable Diffusion models. TCD-LoRA can substantially accelerate the process without degrading image quality. The quality of animation with TCD-LoRA and AnimateDiff has a more lucid outcome.
|
| 398 |
+
|
| 399 |
+
```python
|
| 400 |
+
import torch
|
| 401 |
+
from diffusers import MotionAdapter, AnimateDiffPipeline, DDIMScheduler
|
| 402 |
+
from scheduling_tcd import TCDScheduler
|
| 403 |
+
from diffusers.utils import export_to_gif
|
| 404 |
+
|
| 405 |
+
adapter = MotionAdapter.from_pretrained("guoyww/animatediff-motion-adapter-v1-5")
|
| 406 |
+
pipe = AnimateDiffPipeline.from_pretrained(
|
| 407 |
+
"frankjoshua/toonyou_beta6",
|
| 408 |
+
motion_adapter=adapter,
|
| 409 |
+
).to("cuda")
|
| 410 |
+
|
| 411 |
+
# set TCDScheduler
|
| 412 |
+
pipe.scheduler = TCDScheduler.from_config(pipe.scheduler.config)
|
| 413 |
+
|
| 414 |
+
# load TCD LoRA
|
| 415 |
+
pipe.load_lora_weights("h1t/TCD-SD15-LoRA", adapter_name="tcd")
|
| 416 |
+
pipe.load_lora_weights("guoyww/animatediff-motion-lora-zoom-in", weight_name="diffusion_pytorch_model.safetensors", adapter_name="motion-lora")
|
| 417 |
+
|
| 418 |
+
pipe.set_adapters(["tcd", "motion-lora"], adapter_weights=[1.0, 1.2])
|
| 419 |
+
|
| 420 |
+
prompt = "best quality, masterpiece, 1girl, looking at viewer, blurry background, upper body, contemporary, dress"
|
| 421 |
+
generator = torch.manual_seed(0)
|
| 422 |
+
frames = pipe(
|
| 423 |
+
prompt=prompt,
|
| 424 |
+
num_inference_steps=5,
|
| 425 |
+
guidance_scale=0,
|
| 426 |
+
cross_attention_kwargs={"scale": 1},
|
| 427 |
+
num_frames=24,
|
| 428 |
+
eta=0.3,
|
| 429 |
+
generator=generator
|
| 430 |
+
).frames[0]
|
| 431 |
+
export_to_gif(frames, "animation.gif")
|
| 432 |
+
```
|
| 433 |
+
|
| 434 |
+

|
| 435 |
+
|
| 436 |
+
</hfoption>
|
| 437 |
+
</hfoptions>
|
tasks/tasksmith-deb681b2c96c/tests/source/docs/source/en/using-diffusers/inpaint.md
ADDED
|
@@ -0,0 +1,800 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# Inpainting
|
| 14 |
+
|
| 15 |
+
[[open-in-colab]]
|
| 16 |
+
|
| 17 |
+
Inpainting replaces or edits specific areas of an image. This makes it a useful tool for image restoration like removing defects and artifacts, or even replacing an image area with something entirely new. Inpainting relies on a mask to determine which regions of an image to fill in; the area to inpaint is represented by white pixels and the area to keep is represented by black pixels. The white pixels are filled in by the prompt.
|
| 18 |
+
|
| 19 |
+
With 🤗 Diffusers, here is how you can do inpainting:
|
| 20 |
+
|
| 21 |
+
1. Load an inpainting checkpoint with the [`AutoPipelineForInpainting`] class. This'll automatically detect the appropriate pipeline class to load based on the checkpoint:
|
| 22 |
+
|
| 23 |
+
```py
|
| 24 |
+
import torch
|
| 25 |
+
from diffusers import AutoPipelineForInpainting
|
| 26 |
+
from diffusers.utils import load_image, make_image_grid
|
| 27 |
+
|
| 28 |
+
pipeline = AutoPipelineForInpainting.from_pretrained(
|
| 29 |
+
"kandinsky-community/kandinsky-2-2-decoder-inpaint", torch_dtype=torch.float16
|
| 30 |
+
)
|
| 31 |
+
pipeline.enable_model_cpu_offload()
|
| 32 |
+
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
|
| 33 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 34 |
+
```
|
| 35 |
+
|
| 36 |
+
> [!TIP]
|
| 37 |
+
> You'll notice throughout the guide, we use [`~DiffusionPipeline.enable_model_cpu_offload`] and [`~DiffusionPipeline.enable_xformers_memory_efficient_attention`], to save memory and increase inference speed. If you're using PyTorch 2.0, it's not necessary to call [`~DiffusionPipeline.enable_xformers_memory_efficient_attention`] on your pipeline because it'll already be using PyTorch 2.0's native [scaled-dot product attention](../optimization/fp16#scaled-dot-product-attention).
|
| 38 |
+
|
| 39 |
+
2. Load the base and mask images:
|
| 40 |
+
|
| 41 |
+
```py
|
| 42 |
+
init_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint.png")
|
| 43 |
+
mask_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint_mask.png")
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
3. Create a prompt to inpaint the image with and pass it to the pipeline with the base and mask images:
|
| 47 |
+
|
| 48 |
+
```py
|
| 49 |
+
prompt = "a black cat with glowing eyes, cute, adorable, disney, pixar, highly detailed, 8k"
|
| 50 |
+
negative_prompt = "bad anatomy, deformed, ugly, disfigured"
|
| 51 |
+
image = pipeline(prompt=prompt, negative_prompt=negative_prompt, image=init_image, mask_image=mask_image).images[0]
|
| 52 |
+
make_image_grid([init_image, mask_image, image], rows=1, cols=3)
|
| 53 |
+
```
|
| 54 |
+
|
| 55 |
+
<div class="flex gap-4">
|
| 56 |
+
<div>
|
| 57 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint.png"/>
|
| 58 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">base image</figcaption>
|
| 59 |
+
</div>
|
| 60 |
+
<div>
|
| 61 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint_mask.png"/>
|
| 62 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">mask image</figcaption>
|
| 63 |
+
</div>
|
| 64 |
+
<div>
|
| 65 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint-cat.png"/>
|
| 66 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">generated image</figcaption>
|
| 67 |
+
</div>
|
| 68 |
+
</div>
|
| 69 |
+
|
| 70 |
+
## Create a mask image
|
| 71 |
+
|
| 72 |
+
Throughout this guide, the mask image is provided in all of the code examples for convenience. You can inpaint on your own images, but you'll need to create a mask image for it. Use the Space below to easily create a mask image.
|
| 73 |
+
|
| 74 |
+
Upload a base image to inpaint on and use the sketch tool to draw a mask. Once you're done, click **Run** to generate and download the mask image.
|
| 75 |
+
|
| 76 |
+
<iframe
|
| 77 |
+
src="https://stevhliu-inpaint-mask-maker.hf.space"
|
| 78 |
+
frameborder="0"
|
| 79 |
+
width="850"
|
| 80 |
+
height="450"
|
| 81 |
+
></iframe>
|
| 82 |
+
|
| 83 |
+
### Mask blur
|
| 84 |
+
|
| 85 |
+
The [`~VaeImageProcessor.blur`] method provides an option for how to blend the original image and inpaint area. The amount of blur is determined by the `blur_factor` parameter. Increasing the `blur_factor` increases the amount of blur applied to the mask edges, softening the transition between the original image and inpaint area. A low or zero `blur_factor` preserves the sharper edges of the mask.
|
| 86 |
+
|
| 87 |
+
To use this, create a blurred mask with the image processor.
|
| 88 |
+
|
| 89 |
+
```py
|
| 90 |
+
import torch
|
| 91 |
+
from diffusers import AutoPipelineForInpainting
|
| 92 |
+
from diffusers.utils import load_image
|
| 93 |
+
from PIL import Image
|
| 94 |
+
|
| 95 |
+
pipeline = AutoPipelineForInpainting.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16).to('cuda')
|
| 96 |
+
|
| 97 |
+
mask = load_image("https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/seashore_mask.png")
|
| 98 |
+
blurred_mask = pipeline.mask_processor.blur(mask, blur_factor=33)
|
| 99 |
+
blurred_mask
|
| 100 |
+
```
|
| 101 |
+
|
| 102 |
+
<div class="flex gap-4">
|
| 103 |
+
<div>
|
| 104 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/seashore_mask.png"/>
|
| 105 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">mask with no blur</figcaption>
|
| 106 |
+
</div>
|
| 107 |
+
<div>
|
| 108 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/mask_blurred.png"/>
|
| 109 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">mask with blur applied</figcaption>
|
| 110 |
+
</div>
|
| 111 |
+
</div>
|
| 112 |
+
|
| 113 |
+
## Popular models
|
| 114 |
+
|
| 115 |
+
[Stable Diffusion Inpainting](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-inpainting), [Stable Diffusion XL (SDXL) Inpainting](https://huggingface.co/diffusers/stable-diffusion-xl-1.0-inpainting-0.1), and [Kandinsky 2.2 Inpainting](https://huggingface.co/kandinsky-community/kandinsky-2-2-decoder-inpaint) are among the most popular models for inpainting. SDXL typically produces higher resolution images than Stable Diffusion v1.5, and Kandinsky 2.2 is also capable of generating high-quality images.
|
| 116 |
+
|
| 117 |
+
### Stable Diffusion Inpainting
|
| 118 |
+
|
| 119 |
+
Stable Diffusion Inpainting is a latent diffusion model finetuned on 512x512 images on inpainting. It is a good starting point because it is relatively fast and generates good quality images. To use this model for inpainting, you'll need to pass a prompt, base and mask image to the pipeline:
|
| 120 |
+
|
| 121 |
+
```py
|
| 122 |
+
import torch
|
| 123 |
+
from diffusers import AutoPipelineForInpainting
|
| 124 |
+
from diffusers.utils import load_image, make_image_grid
|
| 125 |
+
|
| 126 |
+
pipeline = AutoPipelineForInpainting.from_pretrained(
|
| 127 |
+
"stable-diffusion-v1-5/stable-diffusion-inpainting", torch_dtype=torch.float16, variant="fp16"
|
| 128 |
+
)
|
| 129 |
+
pipeline.enable_model_cpu_offload()
|
| 130 |
+
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
|
| 131 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 132 |
+
|
| 133 |
+
# load base and mask image
|
| 134 |
+
init_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint.png")
|
| 135 |
+
mask_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint_mask.png")
|
| 136 |
+
|
| 137 |
+
generator = torch.Generator("cuda").manual_seed(92)
|
| 138 |
+
prompt = "concept art digital painting of an elven castle, inspired by lord of the rings, highly detailed, 8k"
|
| 139 |
+
image = pipeline(prompt=prompt, image=init_image, mask_image=mask_image, generator=generator).images[0]
|
| 140 |
+
make_image_grid([init_image, mask_image, image], rows=1, cols=3)
|
| 141 |
+
```
|
| 142 |
+
|
| 143 |
+
### Stable Diffusion XL (SDXL) Inpainting
|
| 144 |
+
|
| 145 |
+
SDXL is a larger and more powerful version of Stable Diffusion v1.5. This model can follow a two-stage model process (though each model can also be used alone); the base model generates an image, and a refiner model takes that image and further enhances its details and quality. Take a look at the [SDXL](sdxl) guide for a more comprehensive guide on how to use SDXL and configure it's parameters.
|
| 146 |
+
|
| 147 |
+
```py
|
| 148 |
+
import torch
|
| 149 |
+
from diffusers import AutoPipelineForInpainting
|
| 150 |
+
from diffusers.utils import load_image, make_image_grid
|
| 151 |
+
|
| 152 |
+
pipeline = AutoPipelineForInpainting.from_pretrained(
|
| 153 |
+
"diffusers/stable-diffusion-xl-1.0-inpainting-0.1", torch_dtype=torch.float16, variant="fp16"
|
| 154 |
+
)
|
| 155 |
+
pipeline.enable_model_cpu_offload()
|
| 156 |
+
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
|
| 157 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 158 |
+
|
| 159 |
+
# load base and mask image
|
| 160 |
+
init_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint.png")
|
| 161 |
+
mask_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint_mask.png")
|
| 162 |
+
|
| 163 |
+
generator = torch.Generator("cuda").manual_seed(92)
|
| 164 |
+
prompt = "concept art digital painting of an elven castle, inspired by lord of the rings, highly detailed, 8k"
|
| 165 |
+
image = pipeline(prompt=prompt, image=init_image, mask_image=mask_image, generator=generator).images[0]
|
| 166 |
+
make_image_grid([init_image, mask_image, image], rows=1, cols=3)
|
| 167 |
+
```
|
| 168 |
+
|
| 169 |
+
### Kandinsky 2.2 Inpainting
|
| 170 |
+
|
| 171 |
+
The Kandinsky model family is similar to SDXL because it uses two models as well; the image prior model creates image embeddings, and the diffusion model generates images from them. You can load the image prior and diffusion model separately, but the easiest way to use Kandinsky 2.2 is to load it into the [`AutoPipelineForInpainting`] class which uses the [`KandinskyV22InpaintCombinedPipeline`] under the hood.
|
| 172 |
+
|
| 173 |
+
```py
|
| 174 |
+
import torch
|
| 175 |
+
from diffusers import AutoPipelineForInpainting
|
| 176 |
+
from diffusers.utils import load_image, make_image_grid
|
| 177 |
+
|
| 178 |
+
pipeline = AutoPipelineForInpainting.from_pretrained(
|
| 179 |
+
"kandinsky-community/kandinsky-2-2-decoder-inpaint", torch_dtype=torch.float16
|
| 180 |
+
)
|
| 181 |
+
pipeline.enable_model_cpu_offload()
|
| 182 |
+
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
|
| 183 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 184 |
+
|
| 185 |
+
# load base and mask image
|
| 186 |
+
init_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint.png")
|
| 187 |
+
mask_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint_mask.png")
|
| 188 |
+
|
| 189 |
+
generator = torch.Generator("cuda").manual_seed(92)
|
| 190 |
+
prompt = "concept art digital painting of an elven castle, inspired by lord of the rings, highly detailed, 8k"
|
| 191 |
+
image = pipeline(prompt=prompt, image=init_image, mask_image=mask_image, generator=generator).images[0]
|
| 192 |
+
make_image_grid([init_image, mask_image, image], rows=1, cols=3)
|
| 193 |
+
```
|
| 194 |
+
|
| 195 |
+
<div class="flex flex-row gap-4">
|
| 196 |
+
<div class="flex-1">
|
| 197 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint.png"/>
|
| 198 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">base image</figcaption>
|
| 199 |
+
</div>
|
| 200 |
+
<div class="flex-1">
|
| 201 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint-sdv1.5.png"/>
|
| 202 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">Stable Diffusion Inpainting</figcaption>
|
| 203 |
+
</div>
|
| 204 |
+
<div class="flex-1">
|
| 205 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint-sdxl.png"/>
|
| 206 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">Stable Diffusion XL Inpainting</figcaption>
|
| 207 |
+
</div>
|
| 208 |
+
<div class="flex-1">
|
| 209 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint-kandinsky.png"/>
|
| 210 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">Kandinsky 2.2 Inpainting</figcaption>
|
| 211 |
+
</div>
|
| 212 |
+
</div>
|
| 213 |
+
|
| 214 |
+
## Non-inpaint specific checkpoints
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
So far, this guide has used inpaint specific checkpoints such as [stable-diffusion-v1-5/stable-diffusion-inpainting](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-inpainting). But you can also use regular checkpoints like [stable-diffusion-v1-5/stable-diffusion-v1-5](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5). Let's compare the results of the two checkpoints.
|
| 218 |
+
|
| 219 |
+
The image on the left is generated from a regular checkpoint, and the image on the right is from an inpaint checkpoint. You'll immediately notice the image on the left is not as clean, and you can still see the outline of the area the model is supposed to inpaint. The image on the right is much cleaner and the inpainted area appears more natural.
|
| 220 |
+
|
| 221 |
+
<hfoptions id="regular-specific">
|
| 222 |
+
<hfoption id="stable-diffusion-v1-5/stable-diffusion-v1-5">
|
| 223 |
+
|
| 224 |
+
```py
|
| 225 |
+
import torch
|
| 226 |
+
from diffusers import AutoPipelineForInpainting
|
| 227 |
+
from diffusers.utils import load_image, make_image_grid
|
| 228 |
+
|
| 229 |
+
pipeline = AutoPipelineForInpainting.from_pretrained(
|
| 230 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16, variant="fp16"
|
| 231 |
+
)
|
| 232 |
+
pipeline.enable_model_cpu_offload()
|
| 233 |
+
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
|
| 234 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 235 |
+
|
| 236 |
+
# load base and mask image
|
| 237 |
+
init_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint.png")
|
| 238 |
+
mask_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint_mask.png")
|
| 239 |
+
|
| 240 |
+
generator = torch.Generator("cuda").manual_seed(92)
|
| 241 |
+
prompt = "concept art digital painting of an elven castle, inspired by lord of the rings, highly detailed, 8k"
|
| 242 |
+
image = pipeline(prompt=prompt, image=init_image, mask_image=mask_image, generator=generator).images[0]
|
| 243 |
+
make_image_grid([init_image, image], rows=1, cols=2)
|
| 244 |
+
```
|
| 245 |
+
|
| 246 |
+
</hfoption>
|
| 247 |
+
<hfoption id="stable-diffusion-v1-5/stable-diffusion-inpainting">
|
| 248 |
+
|
| 249 |
+
```py
|
| 250 |
+
import torch
|
| 251 |
+
from diffusers import AutoPipelineForInpainting
|
| 252 |
+
from diffusers.utils import load_image, make_image_grid
|
| 253 |
+
|
| 254 |
+
pipeline = AutoPipelineForInpainting.from_pretrained(
|
| 255 |
+
"stable-diffusion-v1-5/stable-diffusion-inpainting", torch_dtype=torch.float16, variant="fp16"
|
| 256 |
+
)
|
| 257 |
+
pipeline.enable_model_cpu_offload()
|
| 258 |
+
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
|
| 259 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 260 |
+
|
| 261 |
+
# load base and mask image
|
| 262 |
+
init_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint.png")
|
| 263 |
+
mask_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint_mask.png")
|
| 264 |
+
|
| 265 |
+
generator = torch.Generator("cuda").manual_seed(92)
|
| 266 |
+
prompt = "concept art digital painting of an elven castle, inspired by lord of the rings, highly detailed, 8k"
|
| 267 |
+
image = pipeline(prompt=prompt, image=init_image, mask_image=mask_image, generator=generator).images[0]
|
| 268 |
+
make_image_grid([init_image, image], rows=1, cols=2)
|
| 269 |
+
```
|
| 270 |
+
|
| 271 |
+
</hfoption>
|
| 272 |
+
</hfoptions>
|
| 273 |
+
|
| 274 |
+
<div class="flex gap-4">
|
| 275 |
+
<div>
|
| 276 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/non-inpaint-specific.png"/>
|
| 277 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">stable-diffusion-v1-5/stable-diffusion-v1-5</figcaption>
|
| 278 |
+
</div>
|
| 279 |
+
<div>
|
| 280 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint-specific.png"/>
|
| 281 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">stable-diffusion-v1-5/stable-diffusion-inpainting</figcaption>
|
| 282 |
+
</div>
|
| 283 |
+
</div>
|
| 284 |
+
|
| 285 |
+
However, for more basic tasks like erasing an object from an image (like the rocks in the road for example), a regular checkpoint yields pretty good results. There isn't as noticeable of difference between the regular and inpaint checkpoint.
|
| 286 |
+
|
| 287 |
+
<hfoptions id="inpaint">
|
| 288 |
+
<hfoption id="stable-diffusion-v1-5/stable-diffusion-v1-5">
|
| 289 |
+
|
| 290 |
+
```py
|
| 291 |
+
import torch
|
| 292 |
+
from diffusers import AutoPipelineForInpainting
|
| 293 |
+
from diffusers.utils import load_image, make_image_grid
|
| 294 |
+
|
| 295 |
+
pipeline = AutoPipelineForInpainting.from_pretrained(
|
| 296 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16, variant="fp16"
|
| 297 |
+
)
|
| 298 |
+
pipeline.enable_model_cpu_offload()
|
| 299 |
+
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
|
| 300 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 301 |
+
|
| 302 |
+
# load base and mask image
|
| 303 |
+
init_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint.png")
|
| 304 |
+
mask_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/road-mask.png")
|
| 305 |
+
|
| 306 |
+
image = pipeline(prompt="road", image=init_image, mask_image=mask_image).images[0]
|
| 307 |
+
make_image_grid([init_image, image], rows=1, cols=2)
|
| 308 |
+
```
|
| 309 |
+
|
| 310 |
+
</hfoption>
|
| 311 |
+
<hfoption id="stable-diffusion-v1-5/stable-diffusion-inpaint">
|
| 312 |
+
|
| 313 |
+
```py
|
| 314 |
+
import torch
|
| 315 |
+
from diffusers import AutoPipelineForInpainting
|
| 316 |
+
from diffusers.utils import load_image, make_image_grid
|
| 317 |
+
|
| 318 |
+
pipeline = AutoPipelineForInpainting.from_pretrained(
|
| 319 |
+
"stable-diffusion-v1-5/stable-diffusion-inpainting", torch_dtype=torch.float16, variant="fp16"
|
| 320 |
+
)
|
| 321 |
+
pipeline.enable_model_cpu_offload()
|
| 322 |
+
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
|
| 323 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 324 |
+
|
| 325 |
+
# load base and mask image
|
| 326 |
+
init_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint.png")
|
| 327 |
+
mask_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/road-mask.png")
|
| 328 |
+
|
| 329 |
+
image = pipeline(prompt="road", image=init_image, mask_image=mask_image).images[0]
|
| 330 |
+
make_image_grid([init_image, image], rows=1, cols=2)
|
| 331 |
+
```
|
| 332 |
+
|
| 333 |
+
</hfoption>
|
| 334 |
+
</hfoptions>
|
| 335 |
+
|
| 336 |
+
<div class="flex gap-4">
|
| 337 |
+
<div>
|
| 338 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/regular-inpaint-basic.png"/>
|
| 339 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">stable-diffusion-v1-5/stable-diffusion-v1-5</figcaption>
|
| 340 |
+
</div>
|
| 341 |
+
<div>
|
| 342 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/specific-inpaint-basic.png"/>
|
| 343 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">stable-diffusion-v1-5/stable-diffusion-inpainting</figcaption>
|
| 344 |
+
</div>
|
| 345 |
+
</div>
|
| 346 |
+
|
| 347 |
+
The trade-off of using a non-inpaint specific checkpoint is the overall image quality may be lower, but it generally tends to preserve the mask area (that is why you can see the mask outline). The inpaint specific checkpoints are intentionally trained to generate higher quality inpainted images, and that includes creating a more natural transition between the masked and unmasked areas. As a result, these checkpoints are more likely to change your unmasked area.
|
| 348 |
+
|
| 349 |
+
If preserving the unmasked area is important for your task, you can use the [`VaeImageProcessor.apply_overlay`] method to force the unmasked area of an image to remain the same at the expense of some more unnatural transitions between the masked and unmasked areas.
|
| 350 |
+
|
| 351 |
+
```py
|
| 352 |
+
import PIL
|
| 353 |
+
import numpy as np
|
| 354 |
+
import torch
|
| 355 |
+
|
| 356 |
+
from diffusers import AutoPipelineForInpainting
|
| 357 |
+
from diffusers.utils import load_image, make_image_grid
|
| 358 |
+
|
| 359 |
+
device = "cuda"
|
| 360 |
+
pipeline = AutoPipelineForInpainting.from_pretrained(
|
| 361 |
+
"stable-diffusion-v1-5/stable-diffusion-inpainting",
|
| 362 |
+
torch_dtype=torch.float16,
|
| 363 |
+
variant="fp16"
|
| 364 |
+
)
|
| 365 |
+
pipeline = pipeline.to(device)
|
| 366 |
+
|
| 367 |
+
img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
|
| 368 |
+
mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
|
| 369 |
+
|
| 370 |
+
init_image = load_image(img_url).resize((512, 512))
|
| 371 |
+
mask_image = load_image(mask_url).resize((512, 512))
|
| 372 |
+
|
| 373 |
+
prompt = "Face of a yellow cat, high resolution, sitting on a park bench"
|
| 374 |
+
repainted_image = pipeline(prompt=prompt, image=init_image, mask_image=mask_image).images[0]
|
| 375 |
+
repainted_image.save("repainted_image.png")
|
| 376 |
+
|
| 377 |
+
unmasked_unchanged_image = pipeline.image_processor.apply_overlay(mask_image, init_image, repainted_image)
|
| 378 |
+
unmasked_unchanged_image.save("force_unmasked_unchanged.png")
|
| 379 |
+
make_image_grid([init_image, mask_image, repainted_image, unmasked_unchanged_image], rows=2, cols=2)
|
| 380 |
+
```
|
| 381 |
+
|
| 382 |
+
## Configure pipeline parameters
|
| 383 |
+
|
| 384 |
+
Image features - like quality and "creativity" - are dependent on pipeline parameters. Knowing what these parameters do is important for getting the results you want. Let's take a look at the most important parameters and see how changing them affects the output.
|
| 385 |
+
|
| 386 |
+
### Strength
|
| 387 |
+
|
| 388 |
+
`strength` is a measure of how much noise is added to the base image, which influences how similar the output is to the base image.
|
| 389 |
+
|
| 390 |
+
* 📈 a high `strength` value means more noise is added to an image and the denoising process takes longer, but you'll get higher quality images that are more different from the base image
|
| 391 |
+
* 📉 a low `strength` value means less noise is added to an image and the denoising process is faster, but the image quality may not be as great and the generated image resembles the base image more
|
| 392 |
+
|
| 393 |
+
```py
|
| 394 |
+
import torch
|
| 395 |
+
from diffusers import AutoPipelineForInpainting
|
| 396 |
+
from diffusers.utils import load_image, make_image_grid
|
| 397 |
+
|
| 398 |
+
pipeline = AutoPipelineForInpainting.from_pretrained(
|
| 399 |
+
"stable-diffusion-v1-5/stable-diffusion-inpainting", torch_dtype=torch.float16, variant="fp16"
|
| 400 |
+
)
|
| 401 |
+
pipeline.enable_model_cpu_offload()
|
| 402 |
+
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
|
| 403 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 404 |
+
|
| 405 |
+
# load base and mask image
|
| 406 |
+
init_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint.png")
|
| 407 |
+
mask_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint_mask.png")
|
| 408 |
+
|
| 409 |
+
prompt = "concept art digital painting of an elven castle, inspired by lord of the rings, highly detailed, 8k"
|
| 410 |
+
image = pipeline(prompt=prompt, image=init_image, mask_image=mask_image, strength=0.6).images[0]
|
| 411 |
+
make_image_grid([init_image, mask_image, image], rows=1, cols=3)
|
| 412 |
+
```
|
| 413 |
+
|
| 414 |
+
<div class="flex flex-row gap-4">
|
| 415 |
+
<div class="flex-1">
|
| 416 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint-strength-0.6.png"/>
|
| 417 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">strength = 0.6</figcaption>
|
| 418 |
+
</div>
|
| 419 |
+
<div class="flex-1">
|
| 420 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint-strength-0.8.png"/>
|
| 421 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">strength = 0.8</figcaption>
|
| 422 |
+
</div>
|
| 423 |
+
<div class="flex-1">
|
| 424 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint-strength-1.0.png"/>
|
| 425 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">strength = 1.0</figcaption>
|
| 426 |
+
</div>
|
| 427 |
+
</div>
|
| 428 |
+
|
| 429 |
+
### Guidance scale
|
| 430 |
+
|
| 431 |
+
`guidance_scale` affects how aligned the text prompt and generated image are.
|
| 432 |
+
|
| 433 |
+
* 📈 a high `guidance_scale` value means the prompt and generated image are closely aligned, so the output is a stricter interpretation of the prompt
|
| 434 |
+
* 📉 a low `guidance_scale` value means the prompt and generated image are more loosely aligned, so the output may be more varied from the prompt
|
| 435 |
+
|
| 436 |
+
You can use `strength` and `guidance_scale` together for more control over how expressive the model is. For example, a combination high `strength` and `guidance_scale` values gives the model the most creative freedom.
|
| 437 |
+
|
| 438 |
+
```py
|
| 439 |
+
import torch
|
| 440 |
+
from diffusers import AutoPipelineForInpainting
|
| 441 |
+
from diffusers.utils import load_image, make_image_grid
|
| 442 |
+
|
| 443 |
+
pipeline = AutoPipelineForInpainting.from_pretrained(
|
| 444 |
+
"stable-diffusion-v1-5/stable-diffusion-inpainting", torch_dtype=torch.float16, variant="fp16"
|
| 445 |
+
)
|
| 446 |
+
pipeline.enable_model_cpu_offload()
|
| 447 |
+
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
|
| 448 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 449 |
+
|
| 450 |
+
# load base and mask image
|
| 451 |
+
init_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint.png")
|
| 452 |
+
mask_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint_mask.png")
|
| 453 |
+
|
| 454 |
+
prompt = "concept art digital painting of an elven castle, inspired by lord of the rings, highly detailed, 8k"
|
| 455 |
+
image = pipeline(prompt=prompt, image=init_image, mask_image=mask_image, guidance_scale=2.5).images[0]
|
| 456 |
+
make_image_grid([init_image, mask_image, image], rows=1, cols=3)
|
| 457 |
+
```
|
| 458 |
+
|
| 459 |
+
<div class="flex flex-row gap-4">
|
| 460 |
+
<div class="flex-1">
|
| 461 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint-guidance-2.5.png"/>
|
| 462 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">guidance_scale = 2.5</figcaption>
|
| 463 |
+
</div>
|
| 464 |
+
<div class="flex-1">
|
| 465 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint-guidance-7.5.png"/>
|
| 466 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">guidance_scale = 7.5</figcaption>
|
| 467 |
+
</div>
|
| 468 |
+
<div class="flex-1">
|
| 469 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint-guidance-12.5.png"/>
|
| 470 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">guidance_scale = 12.5</figcaption>
|
| 471 |
+
</div>
|
| 472 |
+
</div>
|
| 473 |
+
|
| 474 |
+
### Negative prompt
|
| 475 |
+
|
| 476 |
+
A negative prompt assumes the opposite role of a prompt; it guides the model away from generating certain things in an image. This is useful for quickly improving image quality and preventing the model from generating things you don't want.
|
| 477 |
+
|
| 478 |
+
```py
|
| 479 |
+
import torch
|
| 480 |
+
from diffusers import AutoPipelineForInpainting
|
| 481 |
+
from diffusers.utils import load_image, make_image_grid
|
| 482 |
+
|
| 483 |
+
pipeline = AutoPipelineForInpainting.from_pretrained(
|
| 484 |
+
"stable-diffusion-v1-5/stable-diffusion-inpainting", torch_dtype=torch.float16, variant="fp16"
|
| 485 |
+
)
|
| 486 |
+
pipeline.enable_model_cpu_offload()
|
| 487 |
+
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
|
| 488 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 489 |
+
|
| 490 |
+
# load base and mask image
|
| 491 |
+
init_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint.png")
|
| 492 |
+
mask_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint_mask.png")
|
| 493 |
+
|
| 494 |
+
prompt = "concept art digital painting of an elven castle, inspired by lord of the rings, highly detailed, 8k"
|
| 495 |
+
negative_prompt = "bad architecture, unstable, poor details, blurry"
|
| 496 |
+
image = pipeline(prompt=prompt, negative_prompt=negative_prompt, image=init_image, mask_image=mask_image).images[0]
|
| 497 |
+
make_image_grid([init_image, mask_image, image], rows=1, cols=3)
|
| 498 |
+
```
|
| 499 |
+
|
| 500 |
+
<div class="flex justify-center">
|
| 501 |
+
<figure>
|
| 502 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint-negative.png" />
|
| 503 |
+
<figcaption class="text-center">negative_prompt = "bad architecture, unstable, poor details, blurry"</figcaption>
|
| 504 |
+
</figure>
|
| 505 |
+
</div>
|
| 506 |
+
|
| 507 |
+
### Padding mask crop
|
| 508 |
+
|
| 509 |
+
A method for increasing the inpainting image quality is to use the [`padding_mask_crop`](https://huggingface.co/docs/diffusers/v0.25.0/en/api/pipelines/stable_diffusion/inpaint#diffusers.StableDiffusionInpaintPipeline.__call__.padding_mask_crop) parameter. When enabled, this option crops the masked area with some user-specified padding and it'll also crop the same area from the original image. Both the image and mask are upscaled to a higher resolution for inpainting, and then overlaid on the original image. This is a quick and easy way to improve image quality without using a separate pipeline like [`StableDiffusionUpscalePipeline`].
|
| 510 |
+
|
| 511 |
+
Add the `padding_mask_crop` parameter to the pipeline call and set it to the desired padding value.
|
| 512 |
+
|
| 513 |
+
```py
|
| 514 |
+
import torch
|
| 515 |
+
from diffusers import AutoPipelineForInpainting
|
| 516 |
+
from diffusers.utils import load_image
|
| 517 |
+
from PIL import Image
|
| 518 |
+
|
| 519 |
+
generator = torch.Generator(device='cuda').manual_seed(0)
|
| 520 |
+
pipeline = AutoPipelineForInpainting.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16).to('cuda')
|
| 521 |
+
|
| 522 |
+
base = load_image("https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/seashore.png")
|
| 523 |
+
mask = load_image("https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/seashore_mask.png")
|
| 524 |
+
|
| 525 |
+
image = pipeline("boat", image=base, mask_image=mask, strength=0.75, generator=generator, padding_mask_crop=32).images[0]
|
| 526 |
+
image
|
| 527 |
+
```
|
| 528 |
+
|
| 529 |
+
<div class="flex gap-4">
|
| 530 |
+
<div>
|
| 531 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/baseline_inpaint.png"/>
|
| 532 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">default inpaint image</figcaption>
|
| 533 |
+
</div>
|
| 534 |
+
<div>
|
| 535 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/padding_mask_crop_inpaint.png"/>
|
| 536 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">inpaint image with `padding_mask_crop` enabled</figcaption>
|
| 537 |
+
</div>
|
| 538 |
+
</div>
|
| 539 |
+
|
| 540 |
+
## Chained inpainting pipelines
|
| 541 |
+
|
| 542 |
+
[`AutoPipelineForInpainting`] can be chained with other 🤗 Diffusers pipelines to edit their outputs. This is often useful for improving the output quality from your other diffusion pipelines, and if you're using multiple pipelines, it can be more memory-efficient to chain them together to keep the outputs in latent space and reuse the same pipeline components.
|
| 543 |
+
|
| 544 |
+
### Text-to-image-to-inpaint
|
| 545 |
+
|
| 546 |
+
Chaining a text-to-image and inpainting pipeline allows you to inpaint the generated image, and you don't have to provide a base image to begin with. This makes it convenient to edit your favorite text-to-image outputs without having to generate an entirely new image.
|
| 547 |
+
|
| 548 |
+
Start with the text-to-image pipeline to create a castle:
|
| 549 |
+
|
| 550 |
+
```py
|
| 551 |
+
import torch
|
| 552 |
+
from diffusers import AutoPipelineForText2Image, AutoPipelineForInpainting
|
| 553 |
+
from diffusers.utils import load_image, make_image_grid
|
| 554 |
+
|
| 555 |
+
pipeline = AutoPipelineForText2Image.from_pretrained(
|
| 556 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16, variant="fp16", use_safetensors=True
|
| 557 |
+
)
|
| 558 |
+
pipeline.enable_model_cpu_offload()
|
| 559 |
+
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
|
| 560 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 561 |
+
|
| 562 |
+
text2image = pipeline("concept art digital painting of an elven castle, inspired by lord of the rings, highly detailed, 8k").images[0]
|
| 563 |
+
```
|
| 564 |
+
|
| 565 |
+
Load the mask image of the output from above:
|
| 566 |
+
|
| 567 |
+
```py
|
| 568 |
+
mask_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint_text-chain-mask.png")
|
| 569 |
+
```
|
| 570 |
+
|
| 571 |
+
And let's inpaint the masked area with a waterfall:
|
| 572 |
+
|
| 573 |
+
```py
|
| 574 |
+
pipeline = AutoPipelineForInpainting.from_pretrained(
|
| 575 |
+
"kandinsky-community/kandinsky-2-2-decoder-inpaint", torch_dtype=torch.float16
|
| 576 |
+
)
|
| 577 |
+
pipeline.enable_model_cpu_offload()
|
| 578 |
+
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
|
| 579 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 580 |
+
|
| 581 |
+
prompt = "digital painting of a fantasy waterfall, cloudy"
|
| 582 |
+
image = pipeline(prompt=prompt, image=text2image, mask_image=mask_image).images[0]
|
| 583 |
+
make_image_grid([text2image, mask_image, image], rows=1, cols=3)
|
| 584 |
+
```
|
| 585 |
+
|
| 586 |
+
<div class="flex flex-row gap-4">
|
| 587 |
+
<div class="flex-1">
|
| 588 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint-text-chain.png"/>
|
| 589 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">text-to-image</figcaption>
|
| 590 |
+
</div>
|
| 591 |
+
<div class="flex-1">
|
| 592 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint-text-chain-out.png"/>
|
| 593 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">inpaint</figcaption>
|
| 594 |
+
</div>
|
| 595 |
+
</div>
|
| 596 |
+
|
| 597 |
+
### Inpaint-to-image-to-image
|
| 598 |
+
|
| 599 |
+
You can also chain an inpainting pipeline before another pipeline like image-to-image or an upscaler to improve the quality.
|
| 600 |
+
|
| 601 |
+
Begin by inpainting an image:
|
| 602 |
+
|
| 603 |
+
```py
|
| 604 |
+
import torch
|
| 605 |
+
from diffusers import AutoPipelineForInpainting, AutoPipelineForImage2Image
|
| 606 |
+
from diffusers.utils import load_image, make_image_grid
|
| 607 |
+
|
| 608 |
+
pipeline = AutoPipelineForInpainting.from_pretrained(
|
| 609 |
+
"stable-diffusion-v1-5/stable-diffusion-inpainting", torch_dtype=torch.float16, variant="fp16"
|
| 610 |
+
)
|
| 611 |
+
pipeline.enable_model_cpu_offload()
|
| 612 |
+
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
|
| 613 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 614 |
+
|
| 615 |
+
# load base and mask image
|
| 616 |
+
init_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint.png")
|
| 617 |
+
mask_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint_mask.png")
|
| 618 |
+
|
| 619 |
+
prompt = "concept art digital painting of an elven castle, inspired by lord of the rings, highly detailed, 8k"
|
| 620 |
+
image_inpainting = pipeline(prompt=prompt, image=init_image, mask_image=mask_image).images[0]
|
| 621 |
+
|
| 622 |
+
# resize image to 1024x1024 for SDXL
|
| 623 |
+
image_inpainting = image_inpainting.resize((1024, 1024))
|
| 624 |
+
```
|
| 625 |
+
|
| 626 |
+
Now let's pass the image to another inpainting pipeline with SDXL's refiner model to enhance the image details and quality:
|
| 627 |
+
|
| 628 |
+
```py
|
| 629 |
+
pipeline = AutoPipelineForInpainting.from_pretrained(
|
| 630 |
+
"stabilityai/stable-diffusion-xl-refiner-1.0", torch_dtype=torch.float16, variant="fp16"
|
| 631 |
+
)
|
| 632 |
+
pipeline.enable_model_cpu_offload()
|
| 633 |
+
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
|
| 634 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 635 |
+
|
| 636 |
+
image = pipeline(prompt=prompt, image=image_inpainting, mask_image=mask_image, output_type="latent").images[0]
|
| 637 |
+
```
|
| 638 |
+
|
| 639 |
+
> [!TIP]
|
| 640 |
+
> It is important to specify `output_type="latent"` in the pipeline to keep all the outputs in latent space to avoid an unnecessary decode-encode step. This only works if the chained pipelines are using the same VAE. For example, in the [Text-to-image-to-inpaint](#text-to-image-to-inpaint) section, Kandinsky 2.2 uses a different VAE class than the Stable Diffusion model so it won't work. But if you use Stable Diffusion v1.5 for both pipelines, then you can keep everything in latent space because they both use [`AutoencoderKL`].
|
| 641 |
+
|
| 642 |
+
Finally, you can pass this image to an image-to-image pipeline to put the finishing touches on it. It is more efficient to use the [`~AutoPipelineForImage2Image.from_pipe`] method to reuse the existing pipeline components, and avoid unnecessarily loading all the pipeline components into memory again.
|
| 643 |
+
|
| 644 |
+
```py
|
| 645 |
+
pipeline = AutoPipelineForImage2Image.from_pipe(pipeline)
|
| 646 |
+
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
|
| 647 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 648 |
+
|
| 649 |
+
image = pipeline(prompt=prompt, image=image).images[0]
|
| 650 |
+
make_image_grid([init_image, mask_image, image_inpainting, image], rows=2, cols=2)
|
| 651 |
+
```
|
| 652 |
+
|
| 653 |
+
<div class="flex flex-row gap-4">
|
| 654 |
+
<div class="flex-1">
|
| 655 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint.png"/>
|
| 656 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">initial image</figcaption>
|
| 657 |
+
</div>
|
| 658 |
+
<div class="flex-1">
|
| 659 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint-to-image-chain.png"/>
|
| 660 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">inpaint</figcaption>
|
| 661 |
+
</div>
|
| 662 |
+
<div class="flex-1">
|
| 663 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint-to-image-final.png"/>
|
| 664 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">image-to-image</figcaption>
|
| 665 |
+
</div>
|
| 666 |
+
</div>
|
| 667 |
+
|
| 668 |
+
Image-to-image and inpainting are actually very similar tasks. Image-to-image generates a new image that resembles the existing provided image. Inpainting does the same thing, but it only transforms the image area defined by the mask and the rest of the image is unchanged. You can think of inpainting as a more precise tool for making specific changes and image-to-image has a broader scope for making more sweeping changes.
|
| 669 |
+
|
| 670 |
+
## Control image generation
|
| 671 |
+
|
| 672 |
+
Getting an image to look exactly the way you want is challenging because the denoising process is random. While you can control certain aspects of generation by configuring parameters like `negative_prompt`, there are better and more efficient methods for controlling image generation.
|
| 673 |
+
|
| 674 |
+
### Prompt weighting
|
| 675 |
+
|
| 676 |
+
Prompt weighting provides a quantifiable way to scale the representation of concepts in a prompt. You can use it to increase or decrease the magnitude of the text embedding vector for each concept in the prompt, which subsequently determines how much of each concept is generated. The [Compel](https://github.com/damian0815/compel) library offers an intuitive syntax for scaling the prompt weights and generating the embeddings. Learn how to create the embeddings in the [Prompt weighting](../using-diffusers/weighted_prompts) guide.
|
| 677 |
+
|
| 678 |
+
Once you've generated the embeddings, pass them to the `prompt_embeds` (and `negative_prompt_embeds` if you're using a negative prompt) parameter in the [`AutoPipelineForInpainting`]. The embeddings replace the `prompt` parameter:
|
| 679 |
+
|
| 680 |
+
```py
|
| 681 |
+
import torch
|
| 682 |
+
from diffusers import AutoPipelineForInpainting
|
| 683 |
+
from diffusers.utils import make_image_grid
|
| 684 |
+
|
| 685 |
+
pipeline = AutoPipelineForInpainting.from_pretrained(
|
| 686 |
+
"stable-diffusion-v1-5/stable-diffusion-inpainting", torch_dtype=torch.float16,
|
| 687 |
+
)
|
| 688 |
+
pipeline.enable_model_cpu_offload()
|
| 689 |
+
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
|
| 690 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 691 |
+
|
| 692 |
+
image = pipeline(prompt_embeds=prompt_embeds, # generated from Compel
|
| 693 |
+
negative_prompt_embeds=negative_prompt_embeds, # generated from Compel
|
| 694 |
+
image=init_image,
|
| 695 |
+
mask_image=mask_image
|
| 696 |
+
).images[0]
|
| 697 |
+
make_image_grid([init_image, mask_image, image], rows=1, cols=3)
|
| 698 |
+
```
|
| 699 |
+
|
| 700 |
+
### ControlNet
|
| 701 |
+
|
| 702 |
+
ControlNet models are used with other diffusion models like Stable Diffusion, and they provide an even more flexible and accurate way to control how an image is generated. A ControlNet accepts an additional conditioning image input that guides the diffusion model to preserve the features in it.
|
| 703 |
+
|
| 704 |
+
For example, let's condition an image with a ControlNet pretrained on inpaint images:
|
| 705 |
+
|
| 706 |
+
```py
|
| 707 |
+
import torch
|
| 708 |
+
import numpy as np
|
| 709 |
+
from diffusers import ControlNetModel, StableDiffusionControlNetInpaintPipeline
|
| 710 |
+
from diffusers.utils import load_image, make_image_grid
|
| 711 |
+
|
| 712 |
+
# load ControlNet
|
| 713 |
+
controlnet = ControlNetModel.from_pretrained("lllyasviel/control_v11p_sd15_inpaint", torch_dtype=torch.float16, variant="fp16")
|
| 714 |
+
|
| 715 |
+
# pass ControlNet to the pipeline
|
| 716 |
+
pipeline = StableDiffusionControlNetInpaintPipeline.from_pretrained(
|
| 717 |
+
"stable-diffusion-v1-5/stable-diffusion-inpainting", controlnet=controlnet, torch_dtype=torch.float16, variant="fp16"
|
| 718 |
+
)
|
| 719 |
+
pipeline.enable_model_cpu_offload()
|
| 720 |
+
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
|
| 721 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 722 |
+
|
| 723 |
+
# load base and mask image
|
| 724 |
+
init_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint.png")
|
| 725 |
+
mask_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint_mask.png")
|
| 726 |
+
|
| 727 |
+
# prepare control image
|
| 728 |
+
def make_inpaint_condition(init_image, mask_image):
|
| 729 |
+
init_image = np.array(init_image.convert("RGB")).astype(np.float32) / 255.0
|
| 730 |
+
mask_image = np.array(mask_image.convert("L")).astype(np.float32) / 255.0
|
| 731 |
+
|
| 732 |
+
assert init_image.shape[0:1] == mask_image.shape[0:1], "image and image_mask must have the same image size"
|
| 733 |
+
init_image[mask_image > 0.5] = -1.0 # set as masked pixel
|
| 734 |
+
init_image = np.expand_dims(init_image, 0).transpose(0, 3, 1, 2)
|
| 735 |
+
init_image = torch.from_numpy(init_image)
|
| 736 |
+
return init_image
|
| 737 |
+
|
| 738 |
+
control_image = make_inpaint_condition(init_image, mask_image)
|
| 739 |
+
```
|
| 740 |
+
|
| 741 |
+
Now generate an image from the base, mask and control images. You'll notice features of the base image are strongly preserved in the generated image.
|
| 742 |
+
|
| 743 |
+
```py
|
| 744 |
+
prompt = "concept art digital painting of an elven castle, inspired by lord of the rings, highly detailed, 8k"
|
| 745 |
+
image = pipeline(prompt=prompt, image=init_image, mask_image=mask_image, control_image=control_image).images[0]
|
| 746 |
+
make_image_grid([init_image, mask_image, PIL.Image.fromarray(np.uint8(control_image[0][0])).convert('RGB'), image], rows=2, cols=2)
|
| 747 |
+
```
|
| 748 |
+
|
| 749 |
+
You can take this a step further and chain it with an image-to-image pipeline to apply a new [style](https://huggingface.co/nitrosocke/elden-ring-diffusion):
|
| 750 |
+
|
| 751 |
+
```py
|
| 752 |
+
from diffusers import AutoPipelineForImage2Image
|
| 753 |
+
|
| 754 |
+
pipeline = AutoPipelineForImage2Image.from_pretrained(
|
| 755 |
+
"nitrosocke/elden-ring-diffusion", torch_dtype=torch.float16,
|
| 756 |
+
)
|
| 757 |
+
pipeline.enable_model_cpu_offload()
|
| 758 |
+
# remove following line if xFormers is not installed or you have PyTorch 2.0 or higher installed
|
| 759 |
+
pipeline.enable_xformers_memory_efficient_attention()
|
| 760 |
+
|
| 761 |
+
prompt = "elden ring style castle" # include the token "elden ring style" in the prompt
|
| 762 |
+
negative_prompt = "bad architecture, deformed, disfigured, poor details"
|
| 763 |
+
|
| 764 |
+
image_elden_ring = pipeline(prompt, negative_prompt=negative_prompt, image=image).images[0]
|
| 765 |
+
make_image_grid([init_image, mask_image, image, image_elden_ring], rows=2, cols=2)
|
| 766 |
+
```
|
| 767 |
+
|
| 768 |
+
<div class="flex flex-row gap-4">
|
| 769 |
+
<div class="flex-1">
|
| 770 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint.png"/>
|
| 771 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">initial image</figcaption>
|
| 772 |
+
</div>
|
| 773 |
+
<div class="flex-1">
|
| 774 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint-controlnet.png"/>
|
| 775 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">ControlNet inpaint</figcaption>
|
| 776 |
+
</div>
|
| 777 |
+
<div class="flex-1">
|
| 778 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/inpaint-img2img.png"/>
|
| 779 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">image-to-image</figcaption>
|
| 780 |
+
</div>
|
| 781 |
+
</div>
|
| 782 |
+
|
| 783 |
+
## Optimize
|
| 784 |
+
|
| 785 |
+
It can be difficult and slow to run diffusion models if you're resource constrained, but it doesn't have to be with a few optimization tricks. One of the biggest (and easiest) optimizations you can enable is switching to memory-efficient attention. If you're using PyTorch 2.0, [scaled-dot product attention](../optimization/fp16#scaled-dot-product-attention) is automatically enabled and you don't need to do anything else. For non-PyTorch 2.0 users, you can install and use [xFormers](../optimization/xformers)'s implementation of memory-efficient attention. Both options reduce memory usage and accelerate inference.
|
| 786 |
+
|
| 787 |
+
You can also offload the model to the CPU to save even more memory:
|
| 788 |
+
|
| 789 |
+
```diff
|
| 790 |
+
+ pipeline.enable_xformers_memory_efficient_attention()
|
| 791 |
+
+ pipeline.enable_model_cpu_offload()
|
| 792 |
+
```
|
| 793 |
+
|
| 794 |
+
To speed-up your inference code even more, use [`torch_compile`](../optimization/fp16#torchcompile). You should wrap `torch.compile` around the most intensive component in the pipeline which is typically the UNet:
|
| 795 |
+
|
| 796 |
+
```py
|
| 797 |
+
pipeline.unet = torch.compile(pipeline.unet, mode="reduce-overhead", fullgraph=True)
|
| 798 |
+
```
|
| 799 |
+
|
| 800 |
+
Learn more in the [Reduce memory usage](../optimization/memory) and [Accelerate inference](../optimization/fp16) guides.
|