AdithyaSK HF Staff commited on
Commit
b08f646
·
verified ·
1 Parent(s): 9206181

Stage Harbor release files 54501-55000

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/training/t2i_adapters.md +218 -0
  2. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/training/text2image.md +182 -0
  3. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/training/text_inversion.md +206 -0
  4. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/training/unconditional_training.md +198 -0
  5. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/training/wuerstchen.md +175 -0
  6. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/tutorials/autopipeline.md +74 -0
  7. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/tutorials/basic_training.md +395 -0
  8. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/tutorials/using_peft_for_inference.md +691 -0
  9. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/automodel.md +128 -0
  10. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/batched_inference.md +173 -0
  11. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/callback.md +136 -0
  12. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/conditional_image_generation.md +307 -0
  13. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/controlling_generation.md +177 -0
  14. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/controlnet.md +346 -0
  15. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/create_a_server.md +61 -0
  16. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/custom_pipeline_overview.md +172 -0
  17. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/depth2img.md +46 -0
  18. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/dreambooth.md +35 -0
  19. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/guiders.md +161 -0
  20. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/image_quality.md +140 -0
  21. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/img2img.md +596 -0
  22. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/inpaint.md +800 -0
  23. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/ip_adapter.md +790 -0
  24. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/loading.md +252 -0
  25. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/other-formats.md +284 -0
  26. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/push_to_hub.md +184 -0
  27. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/reusing_seeds.md +95 -0
  28. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/schedulers.md +282 -0
  29. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/t2i_adapter.md +157 -0
  30. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/text-img2vid.md +447 -0
  31. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/textual_inversion_inference.md +65 -0
  32. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/unconditional_image_generation.md +52 -0
  33. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/weighted_prompts.md +105 -0
  34. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/write_own_pipeline.md +284 -0
  35. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/ja/_toctree.yml +16 -0
  36. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/ja/index.md +48 -0
  37. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/ja/installation.md +142 -0
  38. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/ja/quicktour.md +304 -0
  39. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/ja/stable_diffusion.md +254 -0
  40. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/ja/tutorials/autopipeline.md +165 -0
  41. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/ja/tutorials/tutorial_overview.md +23 -0
  42. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/ko/_toctree.yml +200 -0
  43. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/ko/api/pipelines/stable_diffusion/stable_diffusion_xl.md +394 -0
  44. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/ko/conceptual/contribution.md +511 -0
  45. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/ko/conceptual/ethical_guidelines.md +60 -0
  46. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/ko/conceptual/evaluation.md +542 -0
  47. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/ko/conceptual/philosophy.md +103 -0
  48. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/ko/in_translation.md +16 -0
  49. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/ko/index.md +49 -0
  50. tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/ko/installation.md +139 -0
tasks/tasksmith-7bc616ce49d7/environment/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-7bc616ce49d7/environment/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-7bc616ce49d7/environment/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-7bc616ce49d7/environment/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-7bc616ce49d7/environment/source/docs/source/en/training/wuerstchen.md ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2025 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ # 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
+
tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/tutorials/autopipeline.md ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 four types of [AutoPipeline](../api/models/auto_model) classes:
66
+
67
+ - [`AutoPipelineForText2Image`]
68
+ - [`AutoPipelineForImage2Image`]
69
+ - [`AutoPipelineForInpainting`]
70
+ - [`AutoPipelineForText2Audio`]
71
+
72
+ Each of these classes have a predefined mapping, linking a pipeline to their task-specific subclass.
73
+
74
+ 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-7bc616ce49d7/environment/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-7bc616ce49d7/environment/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-7bc616ce49d7/environment/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-7bc616ce49d7/environment/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-7bc616ce49d7/environment/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-7bc616ce49d7/environment/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](../api/pipelines/stable_diffusion/stable_diffusion_xl) 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-7bc616ce49d7/environment/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 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 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 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 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 you 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 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-7bc616ce49d7/environment/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-7bc616ce49d7/environment/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-7bc616ce49d7/environment/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-7bc616ce49d7/environment/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-7bc616ce49d7/environment/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-7bc616ce49d7/environment/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-7bc616ce49d7/environment/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-7bc616ce49d7/environment/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](../api/pipelines/stable_diffusion/stable_diffusion_xl) 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-7bc616ce49d7/environment/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](../api/pipelines/stable_diffusion/stable_diffusion_xl) 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.
tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/ip_adapter.md ADDED
@@ -0,0 +1,790 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # IP-Adapter
14
+
15
+ [IP-Adapter](https://huggingface.co/papers/2308.06721) is a lightweight adapter designed to integrate image-based guidance with text-to-image diffusion models. The adapter uses an image encoder to extract image features that are passed to the newly added cross-attention layers in the UNet and fine-tuned. The original UNet model and the existing cross-attention layers corresponding to text features is frozen. Decoupling the cross-attention for image and text features enables more fine-grained and controllable generation.
16
+
17
+ IP-Adapter files are typically ~100MBs because they only contain the image embeddings. This means you need to load a model first, and then load the IP-Adapter with [`~loaders.IPAdapterMixin.load_ip_adapter`].
18
+
19
+ > [!TIP]
20
+ > IP-Adapters are available to many models such as [Flux](../api/pipelines/flux#ip-adapter) and [Stable Diffusion 3](../api/pipelines/stable_diffusion/stable_diffusion_3), and more. The examples in this guide use Stable Diffusion and Stable Diffusion XL.
21
+
22
+ Use the [`~loaders.IPAdapterMixin.set_ip_adapter_scale`] parameter to scale the influence of the IP-Adapter during generation. A value of `1.0` means the model is only conditioned on the image prompt, and `0.5` typically produces balanced results between the text and image prompt.
23
+
24
+ ```py
25
+ import torch
26
+ from diffusers import AutoPipelineForText2Image
27
+ from diffusers.utils import load_image
28
+
29
+ pipeline = AutoPipelineForText2Image.from_pretrained(
30
+ "stabilityai/stable-diffusion-xl-base-1.0",
31
+ torch_dtype=torch.float16
32
+ ).to("cuda")
33
+ pipeline.load_ip_adapter(
34
+ "h94/IP-Adapter",
35
+ subfolder="sdxl_models",
36
+ weight_name="ip-adapter_sdxl.bin"
37
+ )
38
+ pipeline.set_ip_adapter_scale(0.8)
39
+ ```
40
+
41
+ Pass an image to `ip_adapter_image` along with a text prompt to generate an image.
42
+
43
+ ```py
44
+ image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_adapter_diner.png")
45
+ pipeline(
46
+ prompt="a polar bear sitting in a chair drinking a milkshake",
47
+ ip_adapter_image=image,
48
+ negative_prompt="deformed, ugly, wrong proportion, low res, bad anatomy, worst quality, low quality",
49
+ ).images[0]
50
+ ```
51
+
52
+ <div style="display: flex; gap: 10px; justify-content: space-around; align-items: flex-end;">
53
+ <figure>
54
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_adapter_diner.png" width="400" alt="IP-Adapter image"/>
55
+ <figcaption style="text-align: center;">IP-Adapter image</figcaption>
56
+ </figure>
57
+ <figure>
58
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_adapter_diner_2.png" width="400" alt="generated image"/>
59
+ <figcaption style="text-align: center;">generated image</figcaption>
60
+ </figure>
61
+ </div>
62
+
63
+ Take a look at the examples below to learn how to use IP-Adapter for other tasks.
64
+
65
+ <hfoptions id="usage">
66
+ <hfoption id="image-to-image">
67
+
68
+ ```py
69
+ import torch
70
+ from diffusers import AutoPipelineForImage2Image
71
+ from diffusers.utils import load_image
72
+
73
+ pipeline = AutoPipelineForImage2Image.from_pretrained(
74
+ "stabilityai/stable-diffusion-xl-base-1.0",
75
+ torch_dtype=torch.float16
76
+ ).to("cuda")
77
+ pipeline.load_ip_adapter(
78
+ "h94/IP-Adapter",
79
+ subfolder="sdxl_models",
80
+ weight_name="ip-adapter_sdxl.bin"
81
+ )
82
+ pipeline.set_ip_adapter_scale(0.8)
83
+
84
+ image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_adapter_bear_1.png")
85
+ ip_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_adapter_gummy.png")
86
+ pipeline(
87
+ prompt="best quality, high quality",
88
+ image=image,
89
+ ip_adapter_image=ip_image,
90
+ strength=0.5,
91
+ ).images[0]
92
+ ```
93
+
94
+ <div style="display: flex; gap: 10px; justify-content: space-around; align-items: flex-end;">
95
+ <figure>
96
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_adapter_bear_1.png" width="300" alt="input image"/>
97
+ <figcaption style="text-align: center;">input image</figcaption>
98
+ </figure>
99
+ <figure>
100
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_adapter_gummy.png" width="300" alt="IP-Adapter image"/>
101
+ <figcaption style="text-align: center;">IP-Adapter image</figcaption>
102
+ </figure>
103
+ <figure>
104
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_adapter_bear_3.png" width="300" alt="generated image"/>
105
+ <figcaption style="text-align: center;">generated image</figcaption>
106
+ </figure>
107
+ </div>
108
+
109
+ </hfoption>
110
+ <hfoption id="inpainting">
111
+
112
+ ```py
113
+ import torch
114
+ from diffusers import AutoPipelineForImage2Image
115
+ from diffusers.utils import load_image
116
+
117
+ pipeline = AutoPipelineForImage2Image.from_pretrained(
118
+ "stabilityai/stable-diffusion-xl-base-1.0",
119
+ torch_dtype=torch.float16
120
+ ).to("cuda")
121
+ pipeline.load_ip_adapter(
122
+ "h94/IP-Adapter",
123
+ subfolder="sdxl_models",
124
+ weight_name="ip-adapter_sdxl.bin"
125
+ )
126
+ pipeline.set_ip_adapter_scale(0.6)
127
+
128
+ mask_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_adapter_mask.png")
129
+ image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_adapter_bear_1.png")
130
+ ip_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_adapter_gummy.png")
131
+ pipeline(
132
+ prompt="a cute gummy bear waving",
133
+ image=image,
134
+ mask_image=mask_image,
135
+ ip_adapter_image=ip_image,
136
+ ).images[0]
137
+ ```
138
+
139
+ <div style="display: flex; gap: 10px; justify-content: space-around; align-items: flex-end;">
140
+ <figure>
141
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_adapter_bear_1.png" width="300" alt="input image"/>
142
+ <figcaption style="text-align: center;">input image</figcaption>
143
+ </figure>
144
+ <figure>
145
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_adapter_gummy.png" width="300" alt="IP-Adapter image"/>
146
+ <figcaption style="text-align: center;">IP-Adapter image</figcaption>
147
+ </figure>
148
+ <figure>
149
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_adapter_inpaint.png" width="300" alt="generated image"/>
150
+ <figcaption style="text-align: center;">generated image</figcaption>
151
+ </figure>
152
+ </div>
153
+
154
+ </hfoption>
155
+ <hfoption id="video">
156
+
157
+ The [`~DiffusionPipeline.enable_model_cpu_offload`] method is useful for reducing memory and it should be enabled **after** the IP-Adapter is loaded. Otherwise, the IP-Adapter's image encoder is also offloaded to the CPU and returns an error.
158
+
159
+ ```py
160
+ import torch
161
+ from diffusers import AnimateDiffPipeline, DDIMScheduler, MotionAdapter
162
+ from diffusers.utils import export_to_gif
163
+ from diffusers.utils import load_image
164
+
165
+ adapter = MotionAdapter.from_pretrained(
166
+ "guoyww/animatediff-motion-adapter-v1-5-2",
167
+ torch_dtype=torch.float16
168
+ )
169
+ pipeline = AnimateDiffPipeline.from_pretrained(
170
+ "emilianJR/epiCRealism",
171
+ motion_adapter=adapter,
172
+ torch_dtype=torch.float16
173
+ )
174
+ scheduler = DDIMScheduler.from_pretrained(
175
+ "emilianJR/epiCRealism",
176
+ subfolder="scheduler",
177
+ clip_sample=False,
178
+ timestep_spacing="linspace",
179
+ beta_schedule="linear",
180
+ steps_offset=1,
181
+ )
182
+ pipeline.scheduler = scheduler
183
+ pipeline.enable_vae_slicing()
184
+ pipeline.load_ip_adapter("h94/IP-Adapter", subfolder="models", weight_name="ip-adapter_sd15.bin")
185
+ pipeline.enable_model_cpu_offload()
186
+
187
+ ip_adapter_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_adapter_inpaint.png")
188
+ pipeline(
189
+ prompt="A cute gummy bear waving",
190
+ negative_prompt="bad quality, worse quality, low resolution",
191
+ ip_adapter_image=ip_adapter_image,
192
+ num_frames=16,
193
+ guidance_scale=7.5,
194
+ num_inference_steps=50,
195
+ ).frames[0]
196
+ ```
197
+
198
+ <div style="display: flex; gap: 10px; justify-content: space-around; align-items: flex-end;">
199
+ <figure>
200
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_adapter_inpaint.png" width="400" alt="IP-Adapter image"/>
201
+ <figcaption style="text-align: center;">IP-Adapter image</figcaption>
202
+ </figure>
203
+ <figure>
204
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/gummy_bear.gif" width="400" alt="generated video"/>
205
+ <figcaption style="text-align: center;">generated video</figcaption>
206
+ </figure>
207
+ </div>
208
+
209
+ </hfoption>
210
+ </hfoptions>
211
+
212
+ ## Model variants
213
+
214
+ There are two variants of IP-Adapter, Plus and FaceID. The Plus variant uses patch embeddings and the ViT-H image encoder. FaceID variant uses face embeddings generated from InsightFace.
215
+
216
+ <hfoptions id="ipadapter-variants">
217
+ <hfoption id="IP-Adapter Plus">
218
+
219
+ ```py
220
+ import torch
221
+ from transformers import CLIPVisionModelWithProjection, AutoPipelineForText2Image
222
+
223
+ image_encoder = CLIPVisionModelWithProjection.from_pretrained(
224
+ "h94/IP-Adapter",
225
+ subfolder="models/image_encoder",
226
+ torch_dtype=torch.float16
227
+ )
228
+
229
+ pipeline = AutoPipelineForText2Image.from_pretrained(
230
+ "stabilityai/stable-diffusion-xl-base-1.0",
231
+ image_encoder=image_encoder,
232
+ torch_dtype=torch.float16
233
+ ).to("cuda")
234
+
235
+ pipeline.load_ip_adapter(
236
+ "h94/IP-Adapter",
237
+ subfolder="sdxl_models",
238
+ weight_name="ip-adapter-plus_sdxl_vit-h.safetensors"
239
+ )
240
+ ```
241
+
242
+ </hfoption>
243
+ <hfoption id="IP-Adapter FaceID">
244
+
245
+ ```py
246
+ import torch
247
+ from transformers import AutoPipelineForText2Image
248
+
249
+ pipeline = AutoPipelineForText2Image.from_pretrained(
250
+ "stabilityai/stable-diffusion-xl-base-1.0",
251
+ torch_dtype=torch.float16
252
+ ).to("cuda")
253
+
254
+ pipeline.load_ip_adapter(
255
+ "h94/IP-Adapter-FaceID",
256
+ subfolder=None,
257
+ weight_name="ip-adapter-faceid_sdxl.bin",
258
+ image_encoder_folder=None
259
+ )
260
+ ```
261
+
262
+ To use a IP-Adapter FaceID Plus model, load the CLIP image encoder as well as [`~transformers.CLIPVisionModelWithProjection`].
263
+
264
+ ```py
265
+ from transformers import AutoPipelineForText2Image, CLIPVisionModelWithProjection
266
+
267
+ image_encoder = CLIPVisionModelWithProjection.from_pretrained(
268
+ "laion/CLIP-ViT-H-14-laion2B-s32B-b79K",
269
+ torch_dtype=torch.float16,
270
+ )
271
+
272
+ pipeline = AutoPipelineForText2Image.from_pretrained(
273
+ "stable-diffusion-v1-5/stable-diffusion-v1-5",
274
+ image_encoder=image_encoder,
275
+ torch_dtype=torch.float16
276
+ ).to("cuda")
277
+
278
+ pipeline.load_ip_adapter(
279
+ "h94/IP-Adapter-FaceID",
280
+ subfolder=None,
281
+ weight_name="ip-adapter-faceid-plus_sd15.bin"
282
+ )
283
+ ```
284
+
285
+ </hfoption>
286
+ </hfoptions>
287
+
288
+ ## Image embeddings
289
+
290
+ The `prepare_ip_adapter_image_embeds` generates image embeddings you can reuse if you're running the pipeline multiple times because you have more than one image. Loading and encoding multiple images each time you use the pipeline can be inefficient. Precomputing the image embeddings ahead of time, saving them to disk, and loading them when you need them is more efficient.
291
+
292
+ ```py
293
+ import torch
294
+ from diffusers import AutoPipelineForText2Image
295
+
296
+ pipeline = AutoPipelineForImage2Image.from_pretrained(
297
+ "stabilityai/stable-diffusion-xl-base-1.0",
298
+ torch_dtype=torch.float16
299
+ ).to("cuda")
300
+
301
+ image_embeds = pipeline.prepare_ip_adapter_image_embeds(
302
+ ip_adapter_image=image,
303
+ ip_adapter_image_embeds=None,
304
+ device="cuda",
305
+ num_images_per_prompt=1,
306
+ do_classifier_free_guidance=True,
307
+ )
308
+
309
+ torch.save(image_embeds, "image_embeds.ipadpt")
310
+ ```
311
+
312
+ Reload the image embeddings by passing them to the `ip_adapter_image_embeds` parameter. Set `image_encoder_folder` to `None` because you don't need the image encoder anymore to generate the image embeddings.
313
+
314
+ > [!TIP]
315
+ > You can also load image embeddings from other sources such as ComfyUI.
316
+
317
+ ```py
318
+ pipeline.load_ip_adapter(
319
+ "h94/IP-Adapter",
320
+ subfolder="sdxl_models",
321
+ image_encoder_folder=None,
322
+ weight_name="ip-adapter_sdxl.bin"
323
+ )
324
+ pipeline.set_ip_adapter_scale(0.8)
325
+ image_embeds = torch.load("image_embeds.ipadpt")
326
+ pipeline(
327
+ prompt="a polar bear sitting in a chair drinking a milkshake",
328
+ ip_adapter_image_embeds=image_embeds,
329
+ negative_prompt="deformed, ugly, wrong proportion, low res, bad anatomy, worst quality, low quality",
330
+ num_inference_steps=100,
331
+ generator=generator,
332
+ ).images[0]
333
+ ```
334
+
335
+ ## Masking
336
+
337
+ Binary masking enables assigning an IP-Adapter image to a specific area of the output image, making it useful for composing multiple IP-Adapter images. Each IP-Adapter image requires a binary mask.
338
+
339
+ Load the [`~image_processor.IPAdapterMaskProcessor`] to preprocess the image masks. For the best results, provide the output `height` and `width` to ensure masks with different aspect ratios are appropriately sized. If the input masks already match the aspect ratio of the generated image, you don't need to set the `height` and `width`.
340
+
341
+ ```py
342
+ import torch
343
+ from diffusers import AutoPipelineForText2Image
344
+ from diffusers.image_processor import IPAdapterMaskProcessor
345
+ from diffusers.utils import load_image
346
+
347
+ pipeline = AutoPipelineForImage2Image.from_pretrained(
348
+ "stabilityai/stable-diffusion-xl-base-1.0",
349
+ torch_dtype=torch.float16
350
+ ).to("cuda")
351
+
352
+ mask1 = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_mask_mask1.png")
353
+ mask2 = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_mask_mask2.png")
354
+
355
+ processor = IPAdapterMaskProcessor()
356
+ masks = processor.preprocess([mask1, mask2], height=1024, width=1024)
357
+ ```
358
+
359
+ <div style="display: flex; gap: 10px; justify-content: space-around; align-items: flex-end;">
360
+ <figure>
361
+ <img src="https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/ip_mask_mask1.png" width="200" alt="mask 1"/>
362
+ <figcaption style="text-align: center;">mask 1</figcaption>
363
+ </figure>
364
+ <figure>
365
+ <img src="https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/ip_mask_mask2.png" width="200" alt="mask 2"/>
366
+ <figcaption style="text-align: center;">mask 2</figcaption>
367
+ </figure>
368
+ </div>
369
+
370
+ Provide both the IP-Adapter images and their scales as a list. Pass the preprocessed masks to `cross_attention_kwargs` in the pipeline.
371
+
372
+ ```py
373
+ face_image1 = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_mask_girl1.png")
374
+ face_image2 = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_mask_girl2.png")
375
+
376
+ pipeline.load_ip_adapter(
377
+ "h94/IP-Adapter",
378
+ subfolder="sdxl_models",
379
+ weight_name=["ip-adapter-plus-face_sdxl_vit-h.safetensors"]
380
+ )
381
+ pipeline.set_ip_adapter_scale([[0.7, 0.7]])
382
+
383
+ ip_images = [[face_image1, face_image2]]
384
+ masks = [masks.reshape(1, masks.shape[0], masks.shape[2], masks.shape[3])]
385
+
386
+ pipeline(
387
+ prompt="2 girls",
388
+ ip_adapter_image=ip_images,
389
+ negative_prompt="monochrome, lowres, bad anatomy, worst quality, low quality",
390
+ cross_attention_kwargs={"ip_adapter_masks": masks}
391
+ ).images[0]
392
+ ```
393
+
394
+ <div style="display: flex; flex-direction: column; gap: 10px;">
395
+ <div style="display: flex; gap: 10px; justify-content: space-around; align-items: flex-end;">
396
+ <figure>
397
+ <img src="https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/ip_mask_girl1.png" width="400" alt="IP-Adapter image 1"/>
398
+ <figcaption style="text-align: center;">IP-Adapter image 1</figcaption>
399
+ </figure>
400
+ <figure>
401
+ <img src="https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/ip_mask_girl2.png" width="400" alt="IP-Adapter image 2"/>
402
+ <figcaption style="text-align: center;">IP-Adapter image 2</figcaption>
403
+ </figure>
404
+ </div>
405
+ <div style="display: flex; gap: 10px; justify-content: space-around; align-items: flex-end;">
406
+ <figure>
407
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_adapter_attention_mask_result_seed_0.png" width="400" alt="Generated image with mask"/>
408
+ <figcaption style="text-align: center;">generated with mask</figcaption>
409
+ </figure>
410
+ <figure>
411
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_adapter_no_attention_mask_result_seed_0.png" width="400" alt="Generated image without mask"/>
412
+ <figcaption style="text-align: center;">generated without mask</figcaption>
413
+ </figure>
414
+ </div>
415
+ </div>
416
+
417
+ ## Applications
418
+
419
+ The section below covers some popular applications of IP-Adapter.
420
+
421
+ ### Face models
422
+
423
+ Face generation and preserving its details can be challenging. To help generate more accurate faces, there are checkpoints specifically conditioned on images of cropped faces. You can find the face models in the [h94/IP-Adapter](https://huggingface.co/h94/IP-Adapter) repository or the [h94/IP-Adapter-FaceID](https://huggingface.co/h94/IP-Adapter-FaceID) repository. The FaceID checkpoints use the FaceID embeddings from [InsightFace](https://github.com/deepinsight/insightface) instead of CLIP image embeddings.
424
+
425
+ We recommend using the [`DDIMScheduler`] or [`EulerDiscreteScheduler`] for face models.
426
+
427
+ <hfoptions id="usage">
428
+ <hfoption id="h94/IP-Adapter">
429
+
430
+ ```py
431
+ import torch
432
+ from diffusers import StableDiffusionPipeline, DDIMScheduler
433
+ from diffusers.utils import load_image
434
+
435
+ pipeline = StableDiffusionPipeline.from_pretrained(
436
+ "stable-diffusion-v1-5/stable-diffusion-v1-5",
437
+ torch_dtype=torch.float16,
438
+ ).to("cuda")
439
+ pipeline.scheduler = DDIMScheduler.from_config(pipeline.scheduler.config)
440
+ pipeline.load_ip_adapter(
441
+ "h94/IP-Adapter",
442
+ subfolder="models",
443
+ weight_name="ip-adapter-full-face_sd15.bin"
444
+ )
445
+
446
+ pipeline.set_ip_adapter_scale(0.5)
447
+ image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_adapter_einstein_base.png")
448
+
449
+ pipeline(
450
+ prompt="A photo of Einstein as a chef, wearing an apron, cooking in a French restaurant",
451
+ ip_adapter_image=image,
452
+ negative_prompt="lowres, bad anatomy, worst quality, low quality",
453
+ num_inference_steps=100,
454
+ ).images[0]
455
+ ```
456
+
457
+ <div style="display: flex; gap: 10px; justify-content: space-around; align-items: flex-end;">
458
+ <figure>
459
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_adapter_einstein_base.png" width="400" alt="IP-Adapter image"/>
460
+ <figcaption style="text-align: center;">IP-Adapter image</figcaption>
461
+ </figure>
462
+ <figure>
463
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_adapter_einstein.png" width="400" alt="generated image"/>
464
+ <figcaption style="text-align: center;">generated image</figcaption>
465
+ </figure>
466
+ </div>
467
+
468
+ </hfoption>
469
+ <hfoption id="h94/IP-Adapter-FaceID">
470
+
471
+ For FaceID models, extract the face embeddings and pass them as a list of tensors to `ip_adapter_image_embeds`.
472
+
473
+ ```py
474
+ # pip install insightface
475
+ import torch
476
+ from diffusers import StableDiffusionPipeline, DDIMScheduler
477
+ from diffusers.utils import load_image
478
+ from insightface.app import FaceAnalysis
479
+
480
+ pipeline = StableDiffusionPipeline.from_pretrained(
481
+ "stable-diffusion-v1-5/stable-diffusion-v1-5",
482
+ torch_dtype=torch.float16,
483
+ ).to("cuda")
484
+ pipeline.scheduler = DDIMScheduler.from_config(pipeline.scheduler.config)
485
+ pipeline.load_ip_adapter(
486
+ "h94/IP-Adapter-FaceID",
487
+ subfolder=None,
488
+ weight_name="ip-adapter-faceid_sd15.bin",
489
+ image_encoder_folder=None
490
+ )
491
+ pipeline.set_ip_adapter_scale(0.6)
492
+
493
+ image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_mask_girl1.png")
494
+
495
+ ref_images_embeds = []
496
+ app = FaceAnalysis(name="buffalo_l", providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
497
+ app.prepare(ctx_id=0, det_size=(640, 640))
498
+ image = cv2.cvtColor(np.asarray(image), cv2.COLOR_BGR2RGB)
499
+ faces = app.get(image)
500
+ image = torch.from_numpy(faces[0].normed_embedding)
501
+ ref_images_embeds.append(image.unsqueeze(0))
502
+ ref_images_embeds = torch.stack(ref_images_embeds, dim=0).unsqueeze(0)
503
+ neg_ref_images_embeds = torch.zeros_like(ref_images_embeds)
504
+ id_embeds = torch.cat([neg_ref_images_embeds, ref_images_embeds]).to(dtype=torch.float16, device="cuda")
505
+
506
+ pipeline(
507
+ prompt="A photo of a girl",
508
+ ip_adapter_image_embeds=[id_embeds],
509
+ negative_prompt="monochrome, lowres, bad anatomy, worst quality, low quality",
510
+ ).images[0]
511
+ ```
512
+
513
+ The IP-Adapter FaceID Plus and Plus v2 models require CLIP image embeddings. Prepare the face embeddings and then extract and pass the CLIP embeddings to the hidden image projection layers.
514
+
515
+ ```py
516
+ clip_embeds = pipeline.prepare_ip_adapter_image_embeds(
517
+ [ip_adapter_images], None, torch.device("cuda"), num_images, True)[0]
518
+
519
+ pipeline.unet.encoder_hid_proj.image_projection_layers[0].clip_embeds = clip_embeds.to(dtype=torch.float16)
520
+ # set to True if using IP-Adapter FaceID Plus v2
521
+ pipeline.unet.encoder_hid_proj.image_projection_layers[0].shortcut = False
522
+ ```
523
+
524
+ </hfoption>
525
+ </hfoptions>
526
+
527
+ ### Multiple IP-Adapters
528
+
529
+ Combine multiple IP-Adapters to generate images in more diverse styles. For example, you can use IP-Adapter Face to generate consistent faces and characters and IP-Adapter Plus to generate those faces in specific styles.
530
+
531
+ Load an image encoder with [`~transformers.CLIPVisionModelWithProjection`].
532
+
533
+ ```py
534
+ import torch
535
+ from diffusers import AutoPipelineForText2Image, DDIMScheduler
536
+ from transformers import CLIPVisionModelWithProjection
537
+ from diffusers.utils import load_image
538
+
539
+ image_encoder = CLIPVisionModelWithProjection.from_pretrained(
540
+ "h94/IP-Adapter",
541
+ subfolder="models/image_encoder",
542
+ torch_dtype=torch.float16,
543
+ )
544
+ ```
545
+
546
+ Load a base model, scheduler and the following IP-Adapters.
547
+
548
+ - [ip-adapter-plus_sdxl_vit-h](https://huggingface.co/h94/IP-Adapter#ip-adapter-for-sdxl-10) uses patch embeddings and a ViT-H image encoder
549
+ - [ip-adapter-plus-face_sdxl_vit-h](https://huggingface.co/h94/IP-Adapter#ip-adapter-for-sdxl-10) uses patch embeddings and a ViT-H image encoder but it is conditioned on images of cropped faces
550
+
551
+ ```py
552
+ pipeline = AutoPipelineForText2Image.from_pretrained(
553
+ "stabilityai/stable-diffusion-xl-base-1.0",
554
+ torch_dtype=torch.float16,
555
+ image_encoder=image_encoder,
556
+ )
557
+ pipeline.scheduler = DDIMScheduler.from_config(pipeline.scheduler.config)
558
+ pipeline.load_ip_adapter(
559
+ "h94/IP-Adapter",
560
+ subfolder="sdxl_models",
561
+ weight_name=["ip-adapter-plus_sdxl_vit-h.safetensors", "ip-adapter-plus-face_sdxl_vit-h.safetensors"]
562
+ )
563
+ pipeline.set_ip_adapter_scale([0.7, 0.3])
564
+ # enable_model_cpu_offload to reduce memory usage
565
+ pipeline.enable_model_cpu_offload()
566
+ ```
567
+
568
+ Load an image and a folder containing images of a certain style to apply.
569
+
570
+ ```py
571
+ face_image = load_image("https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/women_input.png")
572
+ style_folder = "https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/style_ziggy"
573
+ style_images = [load_image(f"{style_folder}/img{i}.png") for i in range(10)]
574
+ ```
575
+
576
+ <div style="display: flex; gap: 10px; justify-content: space-around; align-items: flex-end;">
577
+ <figure>
578
+ <img src="https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/women_input.png" width="400" alt="Face image"/>
579
+ <figcaption style="text-align: center;">face image</figcaption>
580
+ </figure>
581
+ <figure>
582
+ <img src="https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/ip_style_grid.png" width="400" alt="Style images"/>
583
+ <figcaption style="text-align: center;">style images</figcaption>
584
+ </figure>
585
+ </div>
586
+
587
+ Pass style and face images as a list to `ip_adapter_image`.
588
+
589
+ ```py
590
+ generator = torch.Generator(device="cpu").manual_seed(0)
591
+
592
+ pipeline(
593
+ prompt="wonderwoman",
594
+ ip_adapter_image=[style_images, face_image],
595
+ negative_prompt="monochrome, lowres, bad anatomy, worst quality, low quality",
596
+ ).images[0]
597
+ ```
598
+
599
+ <div style="display: flex; justify-content: center;">
600
+ <figure>
601
+ <img src="https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/ip_multi_out.png" width="400" alt="Generated image"/>
602
+ <figcaption style="text-align: center;">generated image</figcaption>
603
+ </figure>
604
+ </div>
605
+
606
+ ### Instant generation
607
+
608
+ [Latent Consistency Models (LCM)](../api/pipelines/latent_consistency_models) can generate images 4 steps or less, unlike other diffusion models which require a lot more steps, making it feel "instantaneous". IP-Adapters are compatible with LCM models to instantly generate images.
609
+
610
+ Load the IP-Adapter weights and load the LoRA weights with [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`].
611
+
612
+ ```py
613
+ import torch
614
+ from diffusers import DiffusionPipeline, LCMScheduler
615
+ from diffusers.utils import load_image
616
+
617
+ pipeline = DiffusionPipeline.from_pretrained(
618
+ "sd-dreambooth-library/herge-style",
619
+ torch_dtype=torch.float16
620
+ )
621
+
622
+ pipeline.load_ip_adapter(
623
+ "h94/IP-Adapter",
624
+ subfolder="models",
625
+ weight_name="ip-adapter_sd15.bin"
626
+ )
627
+ pipeline.load_lora_weights("latent-consistency/lcm-lora-sdv1-5")
628
+ pipeline.scheduler = LCMScheduler.from_config(pipeline.scheduler.config)
629
+ # enable_model_cpu_offload to reduce memory usage
630
+ pipeline.enable_model_cpu_offload()
631
+ ```
632
+
633
+ Try using a lower IP-Adapter scale to condition generation more on the style you want to apply and remember to use the special token in your prompt to trigger its generation.
634
+
635
+ ```py
636
+ pipeline.set_ip_adapter_scale(0.4)
637
+
638
+ prompt = "herge_style woman in armor, best quality, high quality"
639
+
640
+ ip_adapter_image = load_image("https://user-images.githubusercontent.com/24734142/266492875-2d50d223-8475-44f0-a7c6-08b51cb53572.png")
641
+ pipeline(
642
+ prompt=prompt,
643
+ ip_adapter_image=ip_adapter_image,
644
+ num_inference_steps=4,
645
+ guidance_scale=1,
646
+ ).images[0]
647
+ ```
648
+
649
+ <div style="display: flex; justify-content: center;">
650
+ <figure>
651
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ip_adapter_herge.png" width="400" alt="Generated image"/>
652
+ <figcaption style="text-align: center;">generated image</figcaption>
653
+ </figure>
654
+ </div>
655
+
656
+ ### Structural control
657
+
658
+ For structural control, combine IP-Adapter with [ControlNet](../api/pipelines/controlnet) conditioned on depth maps, edge maps, pose estimations, and more.
659
+
660
+ The example below loads a [`ControlNetModel`] checkpoint conditioned on depth maps and combines it with a IP-Adapter.
661
+
662
+ ```py
663
+ import torch
664
+ from diffusers.utils import load_image
665
+ from diffusers import StableDiffusionControlNetPipeline, ControlNetModel
666
+
667
+ controlnet = ControlNetModel.from_pretrained(
668
+ "lllyasviel/control_v11f1p_sd15_depth",
669
+ torch_dtype=torch.float16
670
+ )
671
+
672
+ pipeline = StableDiffusionControlNetPipeline.from_pretrained(
673
+ "stable-diffusion-v1-5/stable-diffusion-v1-5",
674
+ controlnet=controlnet,
675
+ torch_dtype=torch.float16
676
+ ).to("cuda")
677
+ pipeline.load_ip_adapter(
678
+ "h94/IP-Adapter",
679
+ subfolder="models",
680
+ weight_name="ip-adapter_sd15.bin"
681
+ )
682
+ ```
683
+
684
+ Pass the depth map and IP-Adapter image to the pipeline.
685
+
686
+ ```py
687
+ pipeline(
688
+ prompt="best quality, high quality",
689
+ image=depth_map,
690
+ ip_adapter_image=ip_adapter_image,
691
+ negative_prompt="monochrome, lowres, bad anatomy, worst quality, low quality",
692
+ ).images[0]
693
+ ```
694
+
695
+ <div style="display: flex; gap: 10px; justify-content: space-around; align-items: flex-end;">
696
+ <figure>
697
+ <img src="https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/statue.png" width="300" alt="IP-Adapter image"/>
698
+ <figcaption style="text-align: center;">IP-Adapter image</figcaption>
699
+ </figure>
700
+ <figure>
701
+ <img src="https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/depth.png" width="300" alt="Depth map"/>
702
+ <figcaption style="text-align: center;">depth map</figcaption>
703
+ </figure>
704
+ <figure>
705
+ <img src="https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/ipa-controlnet-out.png" width="300" alt="Generated image"/>
706
+ <figcaption style="text-align: center;">generated image</figcaption>
707
+ </figure>
708
+ </div>
709
+
710
+ ### Style and layout control
711
+
712
+ For style and layout control, combine IP-Adapter with [InstantStyle](https://huggingface.co/papers/2404.02733). InstantStyle separates *style* (color, texture, overall feel) and *content* from each other. It only applies the style in style-specific blocks of the model to prevent it from distorting other areas of an image. This generates images with stronger and more consistent styles and better control over the layout.
713
+
714
+ The IP-Adapter is only activated for specific parts of the model. Use the [`~loaders.IPAdapterMixin.set_ip_adapter_scale`] method to scale the influence of the IP-Adapter in different layers. The example below activates the IP-Adapter in the second layer of the models down `block_2` and up `block_0`. Down `block_2` is where the IP-Adapter injects layout information and up `block_0` is where style is injected.
715
+
716
+ ```py
717
+ import torch
718
+ from diffusers import AutoPipelineForText2Image
719
+ from diffusers.utils import load_image
720
+
721
+ pipeline = AutoPipelineForText2Image.from_pretrained(
722
+ "stabilityai/stable-diffusion-xl-base-1.0",
723
+ torch_dtype=torch.float16
724
+ ).to("cuda")
725
+ pipeline.load_ip_adapter(
726
+ "h94/IP-Adapter",
727
+ subfolder="sdxl_models",
728
+ weight_name="ip-adapter_sdxl.bin"
729
+ )
730
+
731
+ scale = {
732
+ "down": {"block_2": [0.0, 1.0]},
733
+ "up": {"block_0": [0.0, 1.0, 0.0]},
734
+ }
735
+ pipeline.set_ip_adapter_scale(scale)
736
+ ```
737
+
738
+ Load the style image and generate an image.
739
+
740
+ ```py
741
+ style_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/0052a70beed5bf71b92610a43a52df6d286cd5f3/diffusers/rabbit.jpg")
742
+
743
+ pipeline(
744
+ prompt="a cat, masterpiece, best quality, high quality",
745
+ ip_adapter_image=style_image,
746
+ negative_prompt="text, watermark, lowres, low quality, worst quality, deformed, glitch, low contrast, noisy, saturation, blurry",
747
+ guidance_scale=5,
748
+ ).images[0]
749
+ ```
750
+
751
+ <div style="display: flex; gap: 10px; justify-content: space-around; align-items: flex-end;">
752
+ <figure>
753
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/0052a70beed5bf71b92610a43a52df6d286cd5f3/diffusers/rabbit.jpg" width="400" alt="Style image"/>
754
+ <figcaption style="text-align: center;">style image</figcaption>
755
+ </figure>
756
+ <figure>
757
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/cat_style_layout.png" width="400" alt="Generated image"/>
758
+ <figcaption style="text-align: center;">generated image</figcaption>
759
+ </figure>
760
+ </div>
761
+
762
+ You can also insert the IP-Adapter in all the model layers. This tends to generate images that focus more on the image prompt and may reduce the diversity of generated images. Only activate the IP-Adapter in up `block_0` or the style layer.
763
+
764
+ > [!TIP]
765
+ > You don't need to specify all the layers in the `scale` dictionary. Layers not included are set to 0, which means the IP-Adapter is disabled.
766
+
767
+ ```py
768
+ scale = {
769
+ "up": {"block_0": [0.0, 1.0, 0.0]},
770
+ }
771
+ pipeline.set_ip_adapter_scale(scale)
772
+
773
+ pipeline(
774
+ prompt="a cat, masterpiece, best quality, high quality",
775
+ ip_adapter_image=style_image,
776
+ negative_prompt="text, watermark, lowres, low quality, worst quality, deformed, glitch, low contrast, noisy, saturation, blurry",
777
+ guidance_scale=5,
778
+ ).images[0]
779
+ ```
780
+
781
+ <div style="display: flex; gap: 10px; justify-content: space-around; align-items: flex-end;">
782
+ <figure>
783
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/cat_style_only.png" width="400" alt="Generated image (style only)"/>
784
+ <figcaption style="text-align: center;">style-layer generated image</figcaption>
785
+ </figure>
786
+ <figure>
787
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/cat_ip_adapter.png" width="400" alt="Generated image (IP-Adapter only)"/>
788
+ <figcaption style="text-align: center;">all layers generated image</figcaption>
789
+ </figure>
790
+ </div>
tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/loading.md ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # DiffusionPipeline
16
+
17
+ Diffusion models consists of multiple components like UNets or diffusion transformers (DiTs), text encoders, variational autoencoders (VAEs), and schedulers. The [`DiffusionPipeline`] wraps all of these components into a single easy-to-use API without giving up the flexibility to modify it's components.
18
+
19
+ This guide will show you how to load a [`DiffusionPipeline`].
20
+
21
+ ## Loading a pipeline
22
+
23
+ [`DiffusionPipeline`] is a base pipeline class that automatically selects and returns an instance of a model's pipeline subclass, like [`QwenImagePipeline`], by scanning the `model_index.json` file for the class name.
24
+
25
+ Pass a model id to [`~DiffusionPipeline.from_pretrained`] to load a pipeline.
26
+
27
+ ```py
28
+ import torch
29
+ from diffusers import DiffusionPipeline
30
+
31
+ pipeline = DiffusionPipeline.from_pretrained(
32
+ "Qwen/Qwen-Image", torch_dtype=torch.bfloat16, device_map="cuda"
33
+ )
34
+ ```
35
+
36
+ Every model has a specific pipeline subclass that inherits from [`DiffusionPipeline`]. A subclass usually has a narrow focus and are task-specific. See the table below for an example.
37
+
38
+ | pipeline subclass | task |
39
+ |---|---|
40
+ | [`QwenImagePipeline`] | text-to-image |
41
+ | [`QwenImageImg2ImgPipeline`] | image-to-image |
42
+ | [`QwenImageInpaintPipeline`] | inpaint |
43
+
44
+ You could use the subclass directly by passing a model id to [`~QwenImagePipeline.from_pretrained`].
45
+
46
+ ```py
47
+ import torch
48
+ from diffusers import QwenImagePipeline
49
+
50
+ pipeline = QwenImagePipeline.from_pretrained(
51
+ "Qwen/Qwen-Image", torch_dtype=torch.bfloat16, device_map="cuda"
52
+ )
53
+ ```
54
+
55
+ > [!TIP]
56
+ > Refer to the [Single file format](./other-formats#single-file-format) docs to learn how to load single file models.
57
+
58
+ ### Local pipelines
59
+
60
+ Pipelines can also be run locally. Use [`~huggingface_hub.snapshot_download`] to download a model repository.
61
+
62
+ ```py
63
+ from huggingface_hub import snapshot_download
64
+
65
+ snapshot_download(repo_id="Qwen/Qwen-Image")
66
+ ```
67
+
68
+ The model is downloaded to your [cache](../installation#cache). Pass the folder path to [`~QwenImagePipeline.from_pretrained`] to load it.
69
+
70
+ ```py
71
+ import torch
72
+ from diffusers import QwenImagePipeline
73
+
74
+ pipeline = QwenImagePipeline.from_pretrained(
75
+ "path/to/your/cache", torch_dtype=torch.bfloat16, device_map="cuda"
76
+ )
77
+ ```
78
+
79
+ The [`~QwenImagePipeline.from_pretrained`] method won't download files from the Hub when it detects a local path. But this also means it won't download and cache any updates that have been made to the model either.
80
+
81
+ ## Pipeline data types
82
+
83
+ Use the `torch_dtype` argument in [`~DiffusionPipeline.from_pretrained`] to load a model with a specific data type. This allows you to load different models in different precisions. For example, loading a large transformer model in half-precision reduces the memory required.
84
+
85
+ Pass the data type for each model as a dictionary to `torch_dtype`. Use the `default` key to set the default data type. If a model isn't in the dictionary and `default` isn't provided, it is loaded in full precision (`torch.float32`).
86
+
87
+ ```py
88
+ import torch
89
+ from diffusers import QwenImagePipeline
90
+
91
+ pipeline = QwenImagePipeline.from_pretrained(
92
+ "Qwen/Qwen-Image",
93
+ torch_dtype={"transformer": torch.bfloat16, "default": torch.float16},
94
+ )
95
+ print(pipeline.transformer.dtype, pipeline.vae.dtype)
96
+ ```
97
+
98
+ You don't need to use a dictionary if you're loading all the models in the same data type.
99
+
100
+ ```py
101
+ import torch
102
+ from diffusers import QwenImagePipeline
103
+
104
+ pipeline = QwenImagePipeline.from_pretrained(
105
+ "Qwen/Qwen-Image", torch_dtype=torch.bfloat16
106
+ )
107
+ print(pipeline.transformer.dtype, pipeline.vae.dtype)
108
+ ```
109
+
110
+ ## Device placement
111
+
112
+ The `device_map` argument determines individual model or pipeline placement on an accelerator like a GPU. It is especially helpful when there are multiple GPUs.
113
+
114
+ A pipeline supports two options for `device_map`, `"cuda"` and `"balanced"`. Refer to the table below to compare the placement strategies.
115
+
116
+ | parameter | description |
117
+ |---|---|
118
+ | `"cuda"` | places pipeline on a supported accelerator device like CUDA |
119
+ | `"balanced"` | evenly distributes pipeline on all GPUs |
120
+
121
+ Use the `max_memory` argument in [`~DiffusionPipeline.from_pretrained`] to allocate a maximum amount of memory to use on each device. By default, Diffusers uses the maximum amount available.
122
+
123
+ ```py
124
+ import torch
125
+ from diffusers import DiffusionPipeline
126
+
127
+ max_memory = {0: "16GB", 1: "16GB"}
128
+ pipeline = DiffusionPipeline.from_pretrained(
129
+ "Qwen/Qwen-Image",
130
+ torch_dtype=torch.bfloat16,
131
+ device_map="cuda",
132
+ )
133
+ ```
134
+
135
+ The `hf_device_map` attribute allows you to access and view the `device_map`.
136
+
137
+ ```py
138
+ print(pipeline.hf_device_map)
139
+ # {'unet': 1, 'vae': 1, 'safety_checker': 0, 'text_encoder': 0}
140
+ ```
141
+
142
+ Reset a pipeline's `device_map` with the [`~DiffusionPipeline.reset_device_map`] method. This is necessary if you want to use methods such as `.to()`, [`~DiffusionPipeline.enable_sequential_cpu_offload`], and [`~DiffusionPipeline.enable_model_cpu_offload`].
143
+
144
+ ```py
145
+ pipeline.reset_device_map()
146
+ ```
147
+
148
+ ## Parallel loading
149
+
150
+ Large models are often [sharded](../training/distributed_inference#model-sharding) into smaller files so that they are easier to load. Diffusers supports loading shards in parallel to speed up the loading process.
151
+
152
+ Set `HF_ENABLE_PARALLEL_LOADING` to `"YES"` to enable parallel loading of shards.
153
+
154
+ The `device_map` argument should be set to `"cuda"` to pre-allocate a large chunk of memory based on the model size. This substantially reduces model load time because warming up the memory allocator now avoids many smaller calls to the allocator later.
155
+
156
+ ```py
157
+ import os
158
+ import torch
159
+ from diffusers import DiffusionPipeline
160
+
161
+ os.environ["HF_ENABLE_PARALLEL_LOADING"] = "YES"
162
+
163
+ pipeline = DiffusionPipeline.from_pretrained(
164
+ "Wan-AI/Wan2.2-I2V-A14B-Diffusers", torch_dtype=torch.bfloat16, device_map="cuda"
165
+ )
166
+ ```
167
+
168
+ ## Replacing models in a pipeline
169
+
170
+ [`DiffusionPipeline`] is flexible and accommodates loading different models or schedulers. You can experiment with different schedulers to optimize for generation speed or quality, and you can replace models with more performant ones.
171
+
172
+ The example below uses a more stable VAE version.
173
+
174
+ ```py
175
+ import torch
176
+ from diffusers import DiffusionPipeline, AutoModel
177
+
178
+ vae = AutoModel.from_pretrained(
179
+ "madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16
180
+ )
181
+
182
+ pipeline = DiffusionPipeline.from_pretrained(
183
+ "stabilityai/stable-diffusion-xl-base-1.0",
184
+ vae=vae,
185
+ torch_dtype=torch.float16,
186
+ device_map="cuda"
187
+ )
188
+ ```
189
+
190
+ ## Reusing models in multiple pipelines
191
+
192
+ When working with multiple pipelines that use the same model, the [`~DiffusionPipeline.from_pipe`] method enables reusing a model instead of reloading it each time. This allows you to use multiple pipelines without increasing memory usage.
193
+
194
+ Memory usage is determined by the pipeline with the highest memory requirement regardless of the number of pipelines.
195
+
196
+ The example below loads a pipeline and then loads a second pipeline with [`~DiffusionPipeline.from_pipe`] to use [perturbed-attention guidance (PAG)](../api/pipelines/pag) to improve generation quality.
197
+
198
+ > [!WARNING]
199
+ > Use [`AutoPipelineForText2Image`] because [`DiffusionPipeline`] doesn't support PAG. Refer to the [AutoPipeline](../tutorials/autopipeline) docs to learn more.
200
+
201
+ ```py
202
+ import torch
203
+ from diffusers import AutoPipelineForText2Image
204
+
205
+ pipeline_sdxl = AutoPipelineForText2Image.from_pretrained(
206
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16, device_map="cuda"
207
+ )
208
+ prompt = """
209
+ cinematic film still of a cat sipping a margarita in a pool in Palm Springs, California
210
+ highly detailed, high budget hollywood movie, cinemascope, moody, epic, gorgeous, film grain
211
+ """
212
+ image = pipeline_sdxl(prompt).images[0]
213
+ print(f"Max memory reserved: {torch.cuda.max_memory_allocated() / 1024**3:.2f} GB")
214
+ # Max memory reserved: 10.47 GB
215
+ ```
216
+
217
+ Set `enable_pag=True` in the second pipeline to enable PAG. The second pipeline uses the same amount of memory because it shares model weights with the first one.
218
+
219
+ ```py
220
+ pipeline = AutoPipelineForText2Image.from_pipe(
221
+ pipeline_sdxl, enable_pag=True
222
+ )
223
+ prompt = """
224
+ cinematic film still of a cat sipping a margarita in a pool in Palm Springs, California
225
+ highly detailed, high budget hollywood movie, cinemascope, moody, epic, gorgeous, film grain
226
+ """
227
+ image = pipeline(prompt).images[0]
228
+ print(f"Max memory reserved: {torch.cuda.max_memory_allocated() / 1024**3:.2f} GB")
229
+ # Max memory reserved: 10.47 GB
230
+ ```
231
+
232
+ > [!WARNING]
233
+ > Pipelines created by [`~DiffusionPipeline.from_pipe`] share the same models and *state*. Modifying the state of a model in one pipeline affects all the other pipelines that share the same model.
234
+
235
+ Some methods may not work correctly on pipelines created with [`~DiffusionPipeline.from_pipe`]. For example, [`~DiffusionPipeline.enable_model_cpu_offload`] relies on a unique model execution order, which may differ in the new pipeline. To ensure proper functionality, reapply these methods on the new pipeline.
236
+
237
+ ## Safety checker
238
+
239
+ Diffusers provides a [safety checker](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/safety_checker.py) for older Stable Diffusion models to prevent generating harmful content. It screens the generated output against a set of hardcoded harmful concepts.
240
+
241
+ If you want to disable the safety checker, pass `safety_checker=None` in [`~DiffusionPipeline.from_pretrained`] as shown below.
242
+
243
+ ```py
244
+ from diffusers import DiffusionPipeline
245
+
246
+ pipeline = DiffusionPipeline.from_pretrained(
247
+ "stable-diffusion-v1-5/stable-diffusion-v1-5", safety_checker=None
248
+ )
249
+ """
250
+ You have disabled the safety checker for <class 'diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline'> by passing `safety_checker=None`. Ensure that you abide by the conditions of the Stable Diffusion license and do not expose unfiltered results in services or applications open to the public. Both the diffusers team and Hugging Face strongly recommend keeping the safety filter enabled in all public-facing circumstances, disabling it only for use cases that involve analyzing network behavior or auditing its results. For more information, please have a look at https://github.com/huggingface/diffusers/pull/254 .
251
+ """
252
+ ```
tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/other-formats.md ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Model formats
16
+
17
+ Diffusion models are typically stored in the Diffusers format or single-file format. Model files can be stored in various file types such as safetensors, dduf, or ckpt.
18
+
19
+ > [!TIP]
20
+ > Format refers to whether the weights are stored in a directory structure and file refers to the file type.
21
+
22
+ This guide will show you how to load pipelines and models from these formats and files.
23
+
24
+ ## Diffusers format
25
+
26
+ The Diffusers format stores each model (UNet, transformer, text encoder) in a separate subfolder. There are several benefits to storing models separately.
27
+
28
+ - Faster overall pipeline initialization because you can load the individual model you need or load them all in parallel.
29
+ - Reduced memory usage because you don't need to load all the pipeline components if you only need one model. [Reuse](./loading#reusing-models-in-multiple-pipelines) a model that is shared between multiple pipelines.
30
+ - Lower storage requirements because common models shared between multiple pipelines are only downloaded once.
31
+ - Flexibility to use new or improved models in a pipeline.
32
+
33
+ ## Single file format
34
+
35
+ A single-file format stores *all* the model (UNet, transformer, text encoder) weights in a single file. Benefits of single-file formats include the following.
36
+
37
+ - Greater compatibility with [ComfyUI](https://github.com/comfyanonymous/ComfyUI) or [Automatic1111](https://github.com/AUTOMATIC1111/stable-diffusion-webui).
38
+ - Easier to download and share a single file.
39
+
40
+ Use [`~loaders.FromSingleFileMixin.from_single_file`] to load a single file.
41
+
42
+ ```py
43
+ import torch
44
+ from diffusers import StableDiffusionXLPipeline
45
+
46
+ pipeline = StableDiffusionXLPipeline.from_single_file(
47
+ "https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/blob/main/sd_xl_base_1.0.safetensors",
48
+ torch_dtype=torch.float16,
49
+ device_map="cuda"
50
+ )
51
+ ```
52
+
53
+ The [`~loaders.FromSingleFileMixin.from_single_file`] method also supports passing new models or schedulers.
54
+
55
+ ```py
56
+ import torch
57
+ from diffusers import FluxPipeline, FluxTransformer2DModel
58
+
59
+ transformer = FluxTransformer2DModel.from_single_file(
60
+ "https://huggingface.co/Kijai/flux-fp8/blob/main/flux1-dev-fp8.safetensors", torch_dtype=torch.bfloat16
61
+ )
62
+ pipeline = FluxPipeline.from_pretrained(
63
+ "black-forest-labs/FLUX.1-dev",
64
+ transformer=transformer,
65
+ torch_dtype=torch.bfloat16,
66
+ device_map="cuda"
67
+ )
68
+ ```
69
+
70
+ ### Configuration options
71
+
72
+ Diffusers format models have a `config.json` file in their repositories with important attributes such as the number of layers and attention heads. The [`~loaders.FromSingleFileMixin.from_single_file`] method automatically determines the appropriate config to use from `config.json`. This may fail in a few rare instances though, in which case, you should use the `config` argument.
73
+
74
+ You should also use the `config` argument if the models in a pipeline are different from the original implementation or if it doesn't have the necessary metadata to determine the correct config.
75
+
76
+ ```py
77
+ from diffusers import StableDiffusionXLPipeline
78
+
79
+ ckpt_path = "https://huggingface.co/segmind/SSD-1B/blob/main/SSD-1B.safetensors"
80
+
81
+ pipeline = StableDiffusionXLPipeline.from_single_file(ckpt_path, config="segmind/SSD-1B")
82
+ ```
83
+
84
+ Diffusers attempts to infer the pipeline components based on the signature types of the pipeline class when using `original_config` with `local_files_only=True`. It won't download the config files from a Hub repository to avoid backward breaking changes when you can't connect to the internet. This method isn't as reliable as providing a path to a local model with the `config` argument and may lead to errors. You should run the pipeline with `local_files_only=False` to download the config files to the local cache to avoid errors.
85
+
86
+ Override default configs by passing the arguments directly to [`~loaders.FromSingleFileMixin.from_single_file`]. The examples below demonstrate how to override the configs in a pipeline or model.
87
+
88
+ ```py
89
+ from diffusers import StableDiffusionXLInstructPix2PixPipeline
90
+
91
+ ckpt_path = "https://huggingface.co/stabilityai/cosxl/blob/main/cosxl_edit.safetensors"
92
+ pipeline = StableDiffusionXLInstructPix2PixPipeline.from_single_file(
93
+ ckpt_path, config="diffusers/sdxl-instructpix2pix-768", is_cosxl_edit=True
94
+ )
95
+ ```
96
+
97
+ ```py
98
+ from diffusers import UNet2DConditionModel
99
+
100
+ ckpt_path = "https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/blob/main/sd_xl_base_1.0_0.9vae.safetensors"
101
+ model = UNet2DConditionModel.from_single_file(ckpt_path, upcast_attention=True)
102
+ ```
103
+
104
+ ### Local files
105
+
106
+ The [`~loaders.FromSingleFileMixin.from_single_file`] method attempts to configure a pipeline or model by inferring the model type from the keys in the checkpoint file. For example, any single file checkpoint based on the Stable Diffusion XL base model is configured from [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0).
107
+
108
+ If you're working with local files, download the config files with the [`~huggingface_hub.snapshot_download`] method and the model checkpoint with [`~huggingface_hub.hf_hub_download`]. These files are downloaded to your [cache directory](https://huggingface.co/docs/huggingface_hub/en/guides/manage-cache), but you can download them to a specific directory with the `local_dir` argument.
109
+
110
+ ```py
111
+ from huggingface_hub import hf_hub_download, snapshot_download
112
+ from diffusers import StableDiffusionXLPipeline
113
+
114
+ my_local_checkpoint_path = hf_hub_download(
115
+ repo_id="segmind/SSD-1B",
116
+ filename="SSD-1B.safetensors"
117
+ )
118
+
119
+ my_local_config_path = snapshot_download(
120
+ repo_id="segmind/SSD-1B",
121
+ allow_patterns=["*.json", "**/*.json", "*.txt", "**/*.txt"]
122
+ )
123
+
124
+ pipeline = StableDiffusionXLPipeline.from_single_file(
125
+ my_local_checkpoint_path, config=my_local_config_path, local_files_only=True
126
+ )
127
+ ```
128
+
129
+ ### Symlink
130
+
131
+ If you're working with a file system that does not support symlinking, download the checkpoint file to a local directory first with the `local_dir` parameter. Using the `local_dir` parameter automatically disables symlinks.
132
+
133
+ ```py
134
+ from huggingface_hub import hf_hub_download, snapshot_download
135
+ from diffusers import StableDiffusionXLPipeline
136
+
137
+ my_local_checkpoint_path = hf_hub_download(
138
+ repo_id="segmind/SSD-1B",
139
+ filename="SSD-1B.safetensors"
140
+ local_dir="my_local_checkpoints",
141
+ )
142
+ print("My local checkpoint: ", my_local_checkpoint_path)
143
+
144
+ my_local_config_path = snapshot_download(
145
+ repo_id="segmind/SSD-1B",
146
+ allow_patterns=["*.json", "**/*.json", "*.txt", "**/*.txt"]
147
+ )
148
+ print("My local config: ", my_local_config_path)
149
+ ```
150
+
151
+ Pass these paths to [`~loaders.FromSingleFileMixin.from_single_file`].
152
+
153
+ ```py
154
+ pipeline = StableDiffusionXLPipeline.from_single_file(
155
+ my_local_checkpoint_path, config=my_local_config_path, local_files_only=True
156
+ )
157
+ ```
158
+
159
+ ## File types
160
+
161
+ Models can be stored in several file types. Safetensors is the most common file type but you may encounter other file types on the Hub or diffusion community.
162
+
163
+ ### safetensors
164
+
165
+ [Safetensors](https://hf.co/docs/safetensors) is a safe and fast file type for securely storing and loading tensors. It restricts the header size to limit certain types of attacks, supports lazy loading (useful for distributed setups), and generally loads faster.
166
+
167
+ Diffusers loads safetensors file by default (a required dependency) if they are available and the Safetensors library is installed.
168
+
169
+ Use [`~DiffusionPipeline.from_pretrained`] or [`~loaders.FromSingleFileMixin.from_single_file`] to load safetensor files.
170
+
171
+ ```py
172
+ import torch
173
+ from diffusers import DiffusionPipeline
174
+
175
+ pipeline = DiffusionPipeline.from_pretrained(
176
+ "stabilityai/stable-diffusion-xl-base-1.0",
177
+ torch.dtype=torch.float16,
178
+ device_map="cuda"
179
+ )
180
+
181
+ pipeline = DiffusionPipeline.from_single_file(
182
+ "https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/blob/main/sd_xl_base_1.0.safetensors",
183
+ torch_dtype=torch.float16,
184
+ )
185
+ ```
186
+
187
+ If you're using a checkpoint trained with a Diffusers training script, metadata such as the LoRA configuration, is automatically saved. When the file is loaded, the metadata is parsed to correctly configure the LoRA and avoid missing or incorrect LoRA configs. Inspect the metadata of a safetensors file by clicking on the <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/safetensors/logo.png" alt="safetensors logo" style="vertical-align: middle; display: inline-block; max-height: 0.8em; max-width: 0.8em; margin: 0; padding: 0; line-height: 1;"> logo next to the file on the Hub.
188
+
189
+ Save the metadata for LoRAs that aren't trained with Diffusers with either `transformer_lora_adapter_metadata` or `unet_lora_adapter_metadata` depending on your model. For the text encoder, use the `text_encoder_lora_adapter_metadata` and `text_encoder_2_lora_adapter_metadata` arguments in [`~loaders.FluxLoraLoaderMixin.save_lora_weights`]. This is only supported for safetensors files.
190
+
191
+ ```py
192
+ import torch
193
+ from diffusers import FluxPipeline
194
+
195
+ pipeline = FluxPipeline.from_pretrained(
196
+ "black-forest-labs/FLUX.1-dev", torch_dtype=torch.bfloat16
197
+ ).to("cuda")
198
+ pipeline.load_lora_weights("linoyts/yarn_art_Flux_LoRA")
199
+ pipeline.save_lora_weights(
200
+ text_encoder_lora_adapter_metadata={"r": 8, "lora_alpha": 8},
201
+ text_encoder_2_lora_adapter_metadata={"r": 8, "lora_alpha": 8}
202
+ )
203
+ ```
204
+
205
+ ### ckpt
206
+
207
+ Older model weights are commonly saved with Python's [pickle](https://docs.python.org/3/library/pickle.html) utility in a ckpt file.
208
+
209
+ Pickled files may be unsafe because they can be exploited to execute malicious code. It is recommended to use safetensors files or convert the weights to safetensors files.
210
+
211
+ Use [`~loaders.FromSingleFileMixin.from_single_file`] to load a ckpt file.
212
+
213
+ ```py
214
+ from diffusers import DiffusionPipeline
215
+
216
+ pipeline = DiffusionPipeline.from_single_file(
217
+ "https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5/blob/main/v1-5-pruned.ckpt"
218
+ )
219
+ ```
220
+
221
+ ### dduf
222
+
223
+ > [!TIP]
224
+ > DDUF is an experimental file type and the API may change. Refer to the DDUF [docs](https://huggingface.co/docs/hub/dduf) to learn more.
225
+
226
+ DDUF is a file type designed to unify different diffusion model distribution methods and weight-saving formats. It is a standardized and flexible method to package all components of a diffusion model into a single file, providing a balance between the Diffusers and single-file formats.
227
+
228
+ Use the `dduf_file` argument in [`~DiffusionPipeline.from_pretrained`] to load a DDUF file. You can also load quantized dduf files as long as they are stored in the Diffusers format.
229
+
230
+ ```py
231
+ import torch
232
+ from diffusers import DiffusionPipeline
233
+
234
+ pipeline = DiffusionPipeline.from_pretrained(
235
+ "DDUF/FLUX.1-dev-DDUF",
236
+ dduf_file="FLUX.1-dev.dduf",
237
+ torch_dtype=torch.bfloat16,
238
+ device_map="cuda"
239
+ )
240
+ ```
241
+
242
+ To save a pipeline as a dduf file, use the [`~huggingface_hub.export_folder_as_dduf`] utility.
243
+
244
+ ```py
245
+ import torch
246
+ from diffusers import DiffusionPipeline
247
+ from huggingface_hub import export_folder_as_dduf
248
+
249
+ pipeline = DiffusionPipeline.from_pretrained("black-forest-labs/FLUX.1-dev", torch_dtype=torch.bfloat16)
250
+
251
+ save_folder = "flux-dev"
252
+ pipeline.save_pretrained("flux-dev")
253
+ export_folder_as_dduf("flux-dev.dduf", folder_path=save_folder)
254
+ ```
255
+
256
+ ## Converting formats and files
257
+
258
+ Diffusers provides scripts and methods to convert format and files to enable broader support across the diffusion ecosystem.
259
+
260
+ Take a look at the [diffusers/scripts](https://github.com/huggingface/diffusers/tree/main/scripts) folder to find a conversion script. Scripts with `"to_diffusers` appended at the end converts a model to the Diffusers format. Each script has a specific set of arguments for configuring the conversion. Make sure you check what arguments are available.
261
+
262
+ The example below converts a model stored in Diffusers format to a single-file format. Provide the path to the model to convert and where to save the converted model. You can optionally specify what file type and data type to save the model as.
263
+
264
+ ```bash
265
+ python convert_diffusers_to_original_sdxl.py --model_path path/to/model/to/convert --checkpoint_path path/to/save/model/to --use_safetensors
266
+ ```
267
+
268
+ The [`~DiffusionPipeline.save_pretrained`] method also saves a model in Diffusers format and takes care of creating subfolders for each model. It saves the files as safetensor files by default.
269
+
270
+ ```py
271
+ from diffusers import DiffusionPipeline
272
+
273
+ pipeline = DiffusionPipeline.from_single_file(
274
+ "https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/blob/main/sd_xl_base_1.0.safetensors",
275
+ )
276
+ pipeline.save_pretrained()
277
+ ```
278
+
279
+ Finally, you can use a Space like [SD To Diffusers](https://hf.co/spaces/diffusers/sd-to-diffusers) or [SD-XL To Diffusers](https://hf.co/spaces/diffusers/sdxl-to-diffusers) to convert models to the Diffusers format. It'll open a PR on your model repository with the converted files. This is the easiest way to convert a model, but it may fail for more complicated models. Using a conversion script is more reliable.
280
+
281
+ ## Resources
282
+
283
+ - Learn more about the design decisions and why safetensor files are preferred for saving and loading model weights in the [Safetensors audited as really safe and becoming the default](https://blog.eleuther.ai/safetensors-security-audit/) blog post.
284
+
tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/push_to_hub.md ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Sharing pipelines and models
16
+
17
+ Share your pipeline or models and schedulers on the Hub with the [`~diffusers.utils.PushToHubMixin`] class. This class:
18
+
19
+ 1. creates a repository on the Hub
20
+ 2. saves your model, scheduler, or pipeline files so they can be reloaded later
21
+ 3. uploads folder containing these files to the Hub
22
+
23
+ This guide will show you how to upload your files to the Hub with the [`~diffusers.utils.PushToHubMixin`] class.
24
+
25
+ Log in to your Hugging Face account with your access [token](https://huggingface.co/settings/tokens).
26
+
27
+ <hfoptions id="login">
28
+ <hfoption id="notebook">
29
+
30
+ ```py
31
+ from huggingface_hub import notebook_login
32
+
33
+ notebook_login()
34
+ ```
35
+
36
+ </hfoption>
37
+ <hfoption id="hf CLI">
38
+
39
+ ```bash
40
+ hf auth login
41
+ ```
42
+
43
+ </hfoption>
44
+ </hfoptions>
45
+
46
+ ## Models
47
+
48
+ To push a model to the Hub, call [`~diffusers.utils.PushToHubMixin.push_to_hub`] and specify the repository id of the model.
49
+
50
+ ```py
51
+ from diffusers import ControlNetModel
52
+
53
+ controlnet = ControlNetModel(
54
+ block_out_channels=(32, 64),
55
+ layers_per_block=2,
56
+ in_channels=4,
57
+ down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
58
+ cross_attention_dim=32,
59
+ conditioning_embedding_out_channels=(16, 32),
60
+ )
61
+ controlnet.push_to_hub("my-controlnet-model")
62
+ ```
63
+
64
+ The [`~diffusers.utils.PushToHubMixin.push_to_hub`] method saves the model's `config.json` file and the weights are automatically saved as safetensors files.
65
+
66
+ Load the model again with [`~DiffusionPipeline.from_pretrained`].
67
+
68
+ ```py
69
+ model = ControlNetModel.from_pretrained("your-namespace/my-controlnet-model")
70
+ ```
71
+
72
+ ## Scheduler
73
+
74
+ To push a scheduler to the Hub, call [`~diffusers.utils.PushToHubMixin.push_to_hub`] and specify the repository id of the scheduler.
75
+
76
+ ```py
77
+ from diffusers import DDIMScheduler
78
+
79
+ scheduler = DDIMScheduler(
80
+ beta_start=0.00085,
81
+ beta_end=0.012,
82
+ beta_schedule="scaled_linear",
83
+ clip_sample=False,
84
+ set_alpha_to_one=False,
85
+ )
86
+ scheduler.push_to_hub("my-controlnet-scheduler")
87
+ ```
88
+
89
+ The [`~diffusers.utils.PushToHubMixin.push_to_hub`] function saves the scheduler's `scheduler_config.json` file to the specified repository.
90
+
91
+ Load the scheduler again with [`~SchedulerMixin.from_pretrained`].
92
+
93
+ ```py
94
+ scheduler = DDIMScheduler.from_pretrained("your-namepsace/my-controlnet-scheduler")
95
+ ```
96
+
97
+ ## Pipeline
98
+
99
+ To push a pipeline to the Hub, initialize the pipeline components with your desired parameters.
100
+
101
+ ```py
102
+ from diffusers import (
103
+ UNet2DConditionModel,
104
+ AutoencoderKL,
105
+ DDIMScheduler,
106
+ StableDiffusionPipeline,
107
+ )
108
+ from transformers import CLIPTextModel, CLIPTextConfig, CLIPTokenizer
109
+
110
+ unet = UNet2DConditionModel(
111
+ block_out_channels=(32, 64),
112
+ layers_per_block=2,
113
+ sample_size=32,
114
+ in_channels=4,
115
+ out_channels=4,
116
+ down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
117
+ up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
118
+ cross_attention_dim=32,
119
+ )
120
+
121
+ scheduler = DDIMScheduler(
122
+ beta_start=0.00085,
123
+ beta_end=0.012,
124
+ beta_schedule="scaled_linear",
125
+ clip_sample=False,
126
+ set_alpha_to_one=False,
127
+ )
128
+
129
+ vae = AutoencoderKL(
130
+ block_out_channels=[32, 64],
131
+ in_channels=3,
132
+ out_channels=3,
133
+ down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
134
+ up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
135
+ latent_channels=4,
136
+ )
137
+
138
+ text_encoder_config = CLIPTextConfig(
139
+ bos_token_id=0,
140
+ eos_token_id=2,
141
+ hidden_size=32,
142
+ intermediate_size=37,
143
+ layer_norm_eps=1e-05,
144
+ num_attention_heads=4,
145
+ num_hidden_layers=5,
146
+ pad_token_id=1,
147
+ vocab_size=1000,
148
+ )
149
+ text_encoder = CLIPTextModel(text_encoder_config)
150
+ tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
151
+ ```
152
+
153
+ Pass all components to the pipeline and call [`~diffusers.utils.PushToHubMixin.push_to_hub`].
154
+
155
+ ```py
156
+ components = {
157
+ "unet": unet,
158
+ "scheduler": scheduler,
159
+ "vae": vae,
160
+ "text_encoder": text_encoder,
161
+ "tokenizer": tokenizer,
162
+ "safety_checker": None,
163
+ "feature_extractor": None,
164
+ }
165
+
166
+ pipeline = StableDiffusionPipeline(**components)
167
+ pipeline.push_to_hub("my-pipeline")
168
+ ```
169
+
170
+ The [`~diffusers.utils.PushToHubMixin.push_to_hub`] method saves each component to a subfolder in the repository. Load the pipeline again with [`~DiffusionPipeline.from_pretrained`].
171
+
172
+ ```py
173
+ pipeline = StableDiffusionPipeline.from_pretrained("your-namespace/my-pipeline")
174
+ ```
175
+
176
+ ## Privacy
177
+
178
+ Set `private=True` in [`~diffusers.utils.PushToHubMixin.push_to_hub`] to keep a model, scheduler, or pipeline files private.
179
+
180
+ ```py
181
+ controlnet.push_to_hub("my-controlnet-model-private", private=True)
182
+ ```
183
+
184
+ Private repositories are only visible to you. Other users won't be able to clone the repository and it won't appear in search results. Even if a user has the URL to your private repository, they'll receive a `404 - Sorry, we can't find the page you are looking for`. You must be [logged in](https://huggingface.co/docs/huggingface_hub/quick-start#login) to load a model from a private repository.
tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/reusing_seeds.md ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Reproducibility
14
+
15
+ Diffusion is a random process that generates a different output every time. For certain situations like testing and replicating results, you want to generate the same result each time, across releases and platforms within a certain tolerance range.
16
+
17
+ This guide will show you how to control sources of randomness and enable deterministic algorithms.
18
+
19
+ ## Generator
20
+
21
+ Pipelines rely on [torch.randn](https://pytorch.org/docs/stable/generated/torch.randn.html), which uses a different random seed each time, to create the initial noisy tensors. To generate the same output on a CPU or GPU, use a [Generator](https://docs.pytorch.org/docs/stable/generated/torch.Generator.html) to manage how random values are generated.
22
+
23
+ > [!TIP]
24
+ > If reproducibility is important to your use case, we recommend always using a CPU `Generator`. The performance loss is often negligible and you'll generate more similar values.
25
+
26
+ <hfoptions id="generator">
27
+ <hfoption id="GPU">
28
+
29
+ The GPU uses a different random number generator than the CPU. Diffusers solves this issue with the [`~utils.torch_utils.randn_tensor`] function to create the random tensor on a CPU and then moving it to the GPU. This function is used everywhere inside the pipeline and you don't need to explicitly call it.
30
+
31
+ Use [manual_seed](https://docs.pytorch.org/docs/stable/generated/torch.manual_seed.html) as shown below to set a seed.
32
+
33
+ ```py
34
+ import torch
35
+ import numpy as np
36
+ from diffusers import DDIMPipeline
37
+
38
+ ddim = DDIMPipeline.from_pretrained("google/ddpm-cifar10-32", device_map="cuda")
39
+ generator = torch.manual_seed(0)
40
+ image = ddim(num_inference_steps=2, output_type="np", generator=generator).images
41
+ print(np.abs(image).sum())
42
+ ```
43
+
44
+ </hfoption>
45
+ <hfoption id="CPU">
46
+
47
+ Set `device="cpu"` in the `Generator` and use [manual_seed](https://docs.pytorch.org/docs/stable/generated/torch.manual_seed.html) to set a seed for generating random numbers.
48
+
49
+ ```py
50
+ import torch
51
+ import numpy as np
52
+ from diffusers import DDIMPipeline
53
+
54
+ ddim = DDIMPipeline.from_pretrained("google/ddpm-cifar10-32")
55
+ generator = torch.Generator(device="cpu").manual_seed(0)
56
+ image = ddim(num_inference_steps=2, output_type="np", generator=generator).images
57
+ print(np.abs(image).sum())
58
+ ```
59
+
60
+ </hfoption>
61
+ </hfoptions>
62
+
63
+ The `Generator` object should be passed to the pipeline instead of an integer seed. `Generator` maintains a *random state* that is consumed and modified when used. Once consumed, the same `Generator` object produces different results in subsequent calls, even across different pipelines, because its *state* has changed.
64
+
65
+ ```py
66
+ generator = torch.manual_seed(0)
67
+
68
+ for _ in range(5):
69
+ - image = pipeline(prompt, generator=generator)
70
+ + image = pipeline(prompt, generator=torch.manual_seed(0))
71
+ ```
72
+
73
+ ## Deterministic algorithms
74
+
75
+ PyTorch supports [deterministic algorithms](https://docs.pytorch.org/docs/stable/notes/randomness.html#avoiding-nondeterministic-algorithms) - where available - for certain operations so they produce the same results. Deterministic algorithms may be slower and decrease performance.
76
+
77
+ Use Diffusers' [enable_full_determinism](https://github.com/huggingface/diffusers/blob/142f353e1c638ff1d20bd798402b68f72c1ebbdd/src/diffusers/utils/testing_utils.py#L861) function to enable deterministic algorithms.
78
+
79
+ ```py
80
+ import torch
81
+ from diffusers_utils import enable_full_determinism
82
+
83
+ enable_full_determinism()
84
+ ```
85
+
86
+ Under the hood, `enable_full_determinism` works by:
87
+
88
+ - Setting the environment variable [CUBLAS_WORKSPACE_CONFIG](https://docs.nvidia.com/cuda/cublas/index.html#results-reproducibility) to `:16:8` to only use one buffer size during rntime. Non-deterministic behavior occurs when operations are used in more than one CUDA stream.
89
+ - Disabling benchmarking to find the fastest convolution operation by setting `torch.backends.cudnn.benchmark=False`. Non-deterministic behavior occurs because the benchmark may select different algorithms each time depending on hardware or benchmarking noise.
90
+ - Disabling TensorFloat32 (TF32) operations in favor of more precise and consistent full-precision operations.
91
+
92
+
93
+ ## Resources
94
+
95
+ We strongly recommend reading PyTorch's developer notes about [Reproducibility](https://docs.pytorch.org/docs/stable/notes/randomness.html). You can try to limit randomness, but it is not *guaranteed* even with an identical seed.
tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/schedulers.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
+ [[open-in-colab]]
14
+
15
+ # Schedulers
16
+
17
+ A scheduler is an algorithm that provides instructions to the denoising process such as how much noise to remove at a certain step. It takes the model prediction from step *t* and applies an update for how to compute the next sample at step *t-1*. Different schedulers produce different results; some are faster while others are more accurate.
18
+
19
+ Diffusers supports many schedulers and allows you to modify their timestep schedules, timestep spacing, and more, to generate high-quality images in fewer steps.
20
+
21
+ This guide will show you how to load and customize schedulers.
22
+
23
+ ## Loading schedulers
24
+
25
+ Schedulers don't have any parameters and are defined in a configuration file. Access the `.scheduler` attribute of a pipeline to view the configuration.
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", torch_dtype=torch.float16, device_map="cuda"
33
+ )
34
+ pipeline.scheduler
35
+ ```
36
+
37
+ Load a different scheduler with [`~SchedulerMixin.from_pretrained`] and specify the `subfolder` argument to load the configuration file into the correct subfolder of the pipeline repository. Pass the new scheduler to the existing pipeline.
38
+
39
+ ```py
40
+ from diffusers import DPMSolverMultistepScheduler
41
+
42
+ dpm = DPMSolverMultistepScheduler.from_pretrained(
43
+ "stabilityai/stable-diffusion-xl-base-1.0", subfolder="scheduler"
44
+ )
45
+ pipeline = DiffusionPipeline.from_pretrained(
46
+ "stabilityai/stable-diffusion-xl-base-1.0",
47
+ scheduler=dpm,
48
+ torch_dtype=torch.float16,
49
+ device_map="cuda"
50
+ )
51
+ pipeline.scheduler
52
+ ```
53
+
54
+ ## Timestep schedules
55
+
56
+ Timestep or noise schedule decides how noise is distributed over the denoising process. The schedule can be linear or more concentrated toward the beginning or end. It is a precomputed sequence of noise levels generated from the scheduler's default configuration, but it can be customized to use other schedules.
57
+
58
+ > [!TIP]
59
+ > The `timesteps` argument is only supported for a select list of schedulers and pipelines. Feel free to open a feature request if you want to extend these parameters to a scheduler and pipeline that does not currently support it!
60
+
61
+ The example below uses the [Align Your Steps (AYS)](https://research.nvidia.com/labs/toronto-ai/AlignYourSteps/) schedule which can generate a high-quality image in 10 steps, significantly speeding up generation and reducing computation time.
62
+
63
+ Import the schedule and pass it to the `timesteps` argument in the pipeline.
64
+
65
+ ```py
66
+ import torch
67
+ from diffusers import DiffusionPipeline, DPMSolverMultistepScheduler
68
+ from diffusers.schedulers import AysSchedules
69
+
70
+ sampling_schedule = AysSchedules["StableDiffusionXLTimesteps"]
71
+ print(sampling_schedule)
72
+ "[999, 845, 730, 587, 443, 310, 193, 116, 53, 13]"
73
+
74
+ pipeline = DiffusionPipeline.from_pretrained(
75
+ "SG161222/RealVisXL_V4.0",
76
+ torch_dtype=torch.float16,
77
+ device_map="cuda"
78
+ )
79
+ pipeline.scheduler = DPMSolverMultistepScheduler.from_config(
80
+ pipeline.scheduler.config, algorithm_type="sde-dpmsolver++"
81
+ )
82
+
83
+ prompt = "A cinematic shot of a cute little rabbit wearing a jacket and doing a thumbs up"
84
+ image = pipeline(
85
+ prompt=prompt,
86
+ negative_prompt="",
87
+ timesteps=sampling_schedule,
88
+ ).images[0]
89
+ ```
90
+
91
+ <div class="flex gap-4">
92
+ <div>
93
+ <img class="rounded-xl" src="https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/ays.png"/>
94
+ <figcaption class="mt-2 text-center text-sm text-gray-500">AYS timestep schedule 10 steps</figcaption>
95
+ </div>
96
+ <div>
97
+ <img class="rounded-xl" src="https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/10.png"/>
98
+ <figcaption class="mt-2 text-center text-sm text-gray-500">Linearly-spaced timestep schedule 10 steps</figcaption>
99
+ </div>
100
+ <div>
101
+ <img class="rounded-xl" src="https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/25.png"/>
102
+ <figcaption class="mt-2 text-center text-sm text-gray-500">Linearly-spaced timestep schedule 25 steps</figcaption>
103
+ </div>
104
+ </div>
105
+
106
+ ### Rescaling schedules
107
+
108
+ Denoising should begin with pure noise and the signal-to-noise (SNR) ration should be zero. However, some models don't actually start from pure noise which makes it difficult to generate images at brightness extremes.
109
+
110
+ > [!TIP]
111
+ > Train your own model with `v_prediction` by adding the `--prediction_type="v_prediction"` flag to your training script. You can also [search](https://huggingface.co/search/full-text?q=v_prediction&type=model) for existing models trained with `v_prediction`.
112
+
113
+ To fix this, a model must be trained with `v_prediction`. If a model is trained with `v_prediction`, then enable the following arguments in the scheduler.
114
+
115
+ - Set `rescale_betas_zero_snr=True` to rescale the noise schedule to the very last timestep with exactly zero SNR
116
+ - Set `timestep_spacing="trailing"` to force sampling from the last timestep with pure noise
117
+
118
+ ```py
119
+ from diffusers import DiffusionPipeline, DDIMScheduler
120
+
121
+ pipeline = DiffusionPipeline.from_pretrained("ptx0/pseudo-journey-v2", device_map="cuda")
122
+
123
+ pipeline.scheduler = DDIMScheduler.from_config(
124
+ pipeline.scheduler.config, rescale_betas_zero_snr=True, timestep_spacing="trailing"
125
+ )
126
+ ```
127
+
128
+ Set `guidance_rescale` in the pipeline to avoid overexposed images. A lower value increases brightness, but some details may appear washed out.
129
+
130
+ ```py
131
+ prompt = """
132
+ cinematic photo of a snowy mountain at night with the northern lights aurora borealis
133
+ overhead, 35mm photograph, film, professional, 4k, highly detailed
134
+ """
135
+ image = pipeline(prompt, guidance_rescale=0.7).images[0]
136
+ ```
137
+
138
+ <div class="flex gap-4">
139
+ <div>
140
+ <img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/no-zero-snr.png"/>
141
+ <figcaption class="mt-2 text-center text-sm text-gray-500">default Stable Diffusion v2-1 image</figcaption>
142
+ </div>
143
+ <div>
144
+ <img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/zero-snr.png"/>
145
+ <figcaption class="mt-2 text-center text-sm text-gray-500">image with zero SNR and trailing timestep spacing enabled</figcaption>
146
+ </div>
147
+ </div>
148
+
149
+ ## Timestep spacing
150
+
151
+ Timestep spacing refers to the specific steps *t* to sample from from the schedule. Diffusers provides three spacing types as shown below.
152
+
153
+ | spacing strategy | spacing calculation | example timesteps |
154
+ |---|---|---|
155
+ | `leading` | evenly spaced steps | `[900, 800, 700, ..., 100, 0]` |
156
+ | `linspace` | include first and last steps and evenly divide remaining intermediate steps | `[1000, 888.89, 777.78, ..., 111.11, 0]` |
157
+ | `trailing` | include last step and evenly divide remaining intermediate steps beginning from the end | `[999, 899, 799, 699, 599, 499, 399, 299, 199, 99]` |
158
+
159
+ Pass the spacing strategy to the `timestep_spacing` argument in the scheduler.
160
+
161
+ > [!TIP]
162
+ > The `trailing` strategy typically produces higher quality images with more details with fewer steps, but the difference in quality is not as obvious for more standard step values.
163
+
164
+ ```py
165
+ import torch
166
+ from diffusers import DiffusionPipeline, DPMSolverMultistepScheduler
167
+
168
+ pipeline = DiffusionPipeline.from_pretrained(
169
+ "SG161222/RealVisXL_V4.0",
170
+ torch_dtype=torch.float16,
171
+ device_map="cuda"
172
+ )
173
+ pipeline.scheduler = DPMSolverMultistepScheduler.from_config(
174
+ pipeline.scheduler.config, timestep_spacing="trailing"
175
+ )
176
+
177
+ prompt = "A cinematic shot of a cute little black cat sitting on a pumpkin at night"
178
+ image = pipeline(
179
+ prompt=prompt,
180
+ negative_prompt="",
181
+ num_inference_steps=5,
182
+ ).images[0]
183
+ image
184
+ ```
185
+
186
+ <div class="flex gap-4">
187
+ <div>
188
+ <img class="rounded-xl" src="https://huggingface.co/datasets/stevhliu/testing-images/resolve/main/trailing_spacing.png"/>
189
+ <figcaption class="mt-2 text-center text-sm text-gray-500">trailing spacing after 5 steps</figcaption>
190
+ </div>
191
+ <div>
192
+ <img class="rounded-xl" src="https://huggingface.co/datasets/stevhliu/testing-images/resolve/main/leading_spacing.png"/>
193
+ <figcaption class="mt-2 text-center text-sm text-gray-500">leading spacing after 5 steps</figcaption>
194
+ </div>
195
+ </div>
196
+
197
+ ## Sigmas
198
+
199
+ Sigmas is a measure of how noisy a sample is at a certain step as defined by the schedule. When using custom `sigmas`, the `timesteps` are calculated from these values instead of the default scheduler configuration.
200
+
201
+ > [!TIP]
202
+ > The `sigmas` argument is only supported for a select list of schedulers and pipelines. Feel free to open a feature request if you want to extend these parameters to a scheduler and pipeline that does not currently support it!
203
+
204
+ Pass the custom sigmas to the `sigmas` argument in the pipeline. The example below uses the [sigmas](https://github.com/huggingface/diffusers/blob/6529ee67ec02fcf58d2fd9242164ea002b351d75/src/diffusers/schedulers/scheduling_utils.py#L55) from the 10-step AYS schedule.
205
+
206
+ ```py
207
+ import torch
208
+ from diffusers import DiffusionPipeline, DPMSolverMultistepScheduler
209
+
210
+ pipeline = DiffusionPipeline.from_pretrained(
211
+ "SG161222/RealVisXL_V4.0",
212
+ torch_dtype=torch.float16,
213
+ device_map="cuda"
214
+ )
215
+ pipeline.scheduler = DPMSolverMultistepScheduler.from_config(
216
+ pipeline.scheduler.config, algorithm_type="sde-dpmsolver++"
217
+ )
218
+
219
+ sigmas = [14.615, 6.315, 3.771, 2.181, 1.342, 0.862, 0.555, 0.380, 0.234, 0.113, 0.0]
220
+ prompt = "A cinematic shot of a cute little rabbit wearing a jacket and doing a thumbs up"
221
+ image = pipeline(
222
+ prompt=prompt,
223
+ negative_prompt="",
224
+ sigmas=sigmas,
225
+ ).images[0]
226
+ ```
227
+
228
+ ### Karras sigmas
229
+
230
+ [Karras sigmas](https://huggingface.co/papers/2206.00364) resamples the noise schedule for more efficient sampling by clustering sigmas more densely in the middle of the sequence where structure reconstruction is critical, while using fewer sigmas at the beginning and end where noise changes have less impact. This can increase the level of details in a generated image.
231
+
232
+ Set `use_karras_sigmas=True` in the scheduler to enable it.
233
+
234
+ ```py
235
+ import torch
236
+ from diffusers import DiffusionPipeline, DPMSolverMultistepScheduler
237
+
238
+ pipeline = DiffusionPipeline.from_pretrained(
239
+ "SG161222/RealVisXL_V4.0",
240
+ torch_dtype=torch.float16,
241
+ device_map="cuda"
242
+ )
243
+ pipeline.scheduler = DPMSolverMultistepScheduler.from_config(
244
+ pipeline.scheduler.config,
245
+ algorithm_type="sde-dpmsolver++",
246
+ use_karras_sigmas=True,
247
+ )
248
+
249
+ prompt = "A cinematic shot of a cute little rabbit wearing a jacket and doing a thumbs up"
250
+ image = pipeline(
251
+ prompt=prompt,
252
+ negative_prompt="",
253
+ sigmas=sigmas,
254
+ ).images[0]
255
+ ```
256
+
257
+ <div class="flex gap-4">
258
+ <div>
259
+ <img class="rounded-xl" src="https://huggingface.co/datasets/stevhliu/testing-images/resolve/main/karras_sigmas_true.png"/>
260
+ <figcaption class="mt-2 text-center text-sm text-gray-500">Karras sigmas enabled</figcaption>
261
+ </div>
262
+ <div>
263
+ <img class="rounded-xl" src="https://huggingface.co/datasets/stevhliu/testing-images/resolve/main/karras_sigmas_false.png"/>
264
+ <figcaption class="mt-2 text-center text-sm text-gray-500">Karras sigmas disabled</figcaption>
265
+ </div>
266
+ </div>
267
+
268
+ Refer to the scheduler API [overview](../api/schedulers/overview) for a list of schedulers that support Karras sigmas. It should only be used for models trained with Karras sigmas.
269
+
270
+ ## Choosing a scheduler
271
+
272
+ It's important to try different schedulers to find the best one for your use case. Here are a few recommendations to help you get started.
273
+
274
+ - DPM++ 2M SDE Karras is generally a good all-purpose option.
275
+ - [`TCDScheduler`] works well for distilled models.
276
+ - [`FlowMatchEulerDiscreteScheduler`] and [`FlowMatchHeunDiscreteScheduler`] for FlowMatch models.
277
+ - [`EulerDiscreteScheduler`] or [`EulerAncestralDiscreteScheduler`] for generating anime style images.
278
+ - DPM++ 2M paired with [`LCMScheduler`] on SDXL for generating realistic images.
279
+
280
+ ## Resources
281
+
282
+ - Read the [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) paper for more details about rescaling the noise schedule to enforce zero SNR.
tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/t2i_adapter.md ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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://huggingface.co/papers/2302.08453) is an adapter that enables controllable generation like [ControlNet](./controlnet). A T2I-Adapter works by learning a *mapping* between a control signal (for example, a depth map) and a pretrained model's internal knowledge. The adapter is plugged in to the base model to provide extra guidance based on the control signal during generation.
16
+
17
+ Load a T2I-Adapter conditioned on a specific control, such as canny edge, and pass it to the pipeline in [`~DiffusionPipeline.from_pretrained`].
18
+
19
+ ```py
20
+ import torch
21
+ from diffusers import T2IAdapter, StableDiffusionXLAdapterPipeline, AutoencoderKL
22
+
23
+ t2i_adapter = T2IAdapter.from_pretrained(
24
+ "TencentARC/t2i-adapter-canny-sdxl-1.0",
25
+ torch_dtype=torch.float16,
26
+ )
27
+ ```
28
+
29
+ Generate a canny image with [opencv-python](https://github.com/opencv/opencv-python).
30
+
31
+ ```py
32
+ import cv2
33
+ import numpy as np
34
+ from PIL import Image
35
+ from diffusers.utils import load_image
36
+
37
+ original_image = load_image(
38
+ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/non-enhanced-prompt.png"
39
+ )
40
+
41
+ image = np.array(original_image)
42
+
43
+ low_threshold = 100
44
+ high_threshold = 200
45
+
46
+ image = cv2.Canny(image, low_threshold, high_threshold)
47
+ image = image[:, :, None]
48
+ image = np.concatenate([image, image, image], axis=2)
49
+ canny_image = Image.fromarray(image)
50
+ ```
51
+
52
+ Pass the canny image to the pipeline to generate an image.
53
+
54
+ ```py
55
+ vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
56
+ pipeline = StableDiffusionXLAdapterPipeline.from_pretrained(
57
+ "stabilityai/stable-diffusion-xl-base-1.0",
58
+ adapter=t2i_adapter,
59
+ vae=vae,
60
+ torch_dtype=torch.float16,
61
+ ).to("cuda")
62
+
63
+ prompt = """
64
+ A photorealistic overhead image of a cat reclining sideways in a flamingo pool floatie holding a margarita.
65
+ The cat is floating leisurely in the pool and completely relaxed and happy.
66
+ """
67
+
68
+ pipeline(
69
+ prompt,
70
+ image=canny_image,
71
+ num_inference_steps=100,
72
+ guidance_scale=10,
73
+ ).images[0]
74
+ ```
75
+
76
+ <div style="display: flex; gap: 10px; justify-content: space-around; align-items: flex-end;">
77
+ <figure>
78
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/non-enhanced-prompt.png" width="300" alt="Generated image (prompt only)"/>
79
+ <figcaption style="text-align: center;">original image</figcaption>
80
+ </figure>
81
+ <figure>
82
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/canny-cat.png" width="300" alt="Control image (Canny edges)"/>
83
+ <figcaption style="text-align: center;">canny image</figcaption>
84
+ </figure>
85
+ <figure>
86
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/t2i-canny-cat-generated.png" width="300" alt="Generated image (ControlNet + prompt)"/>
87
+ <figcaption style="text-align: center;">generated image</figcaption>
88
+ </figure>
89
+ </div>
90
+
91
+ ## MultiAdapter
92
+
93
+ You can compose multiple controls, such as canny image and a depth map, with the [`MultiAdapter`] class.
94
+
95
+ The example below composes a canny image and depth map.
96
+
97
+ Load the control images and T2I-Adapters as a list.
98
+
99
+ ```py
100
+ import torch
101
+ from diffusers.utils import load_image
102
+ from diffusers import StableDiffusionXLAdapterPipeline, AutoencoderKL, MultiAdapter, T2IAdapter
103
+
104
+ canny_image = load_image(
105
+ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/canny-cat.png"
106
+ )
107
+ depth_image = load_image(
108
+ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/sdxl_depth_image.png"
109
+ )
110
+ controls = [canny_image, depth_image]
111
+ prompt = ["""
112
+ a relaxed rabbit sitting on a striped towel next to a pool with a tropical drink nearby,
113
+ bright sunny day, vacation scene, 35mm photograph, film, professional, 4k, highly detailed
114
+ """]
115
+
116
+ adapters = MultiAdapter(
117
+ [
118
+ T2IAdapter.from_pretrained("TencentARC/t2i-adapter-canny-sdxl-1.0", torch_dtype=torch.float16),
119
+ T2IAdapter.from_pretrained("TencentARC/t2i-adapter-depth-midas-sdxl-1.0", torch_dtype=torch.float16),
120
+ ]
121
+ )
122
+ ```
123
+
124
+ Pass the adapters, prompt, and control images to [`StableDiffusionXLAdapterPipeline`]. Use the `adapter_conditioning_scale` parameter to determine how much weight to assign to each control.
125
+
126
+ ```py
127
+ vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
128
+ pipeline = StableDiffusionXLAdapterPipeline.from_pretrained(
129
+ "stabilityai/stable-diffusion-xl-base-1.0",
130
+ torch_dtype=torch.float16,
131
+ vae=vae,
132
+ adapter=adapters,
133
+ ).to("cuda")
134
+
135
+ pipeline(
136
+ prompt,
137
+ image=controls,
138
+ height=1024,
139
+ width=1024,
140
+ adapter_conditioning_scale=[0.7, 0.7]
141
+ ).images[0]
142
+ ```
143
+
144
+ <div style="display: flex; gap: 10px; justify-content: space-around; align-items: flex-end;">
145
+ <figure>
146
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/canny-cat.png" width="300" alt="Generated image (prompt only)"/>
147
+ <figcaption style="text-align: center;">canny image</figcaption>
148
+ </figure>
149
+ <figure>
150
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/sdxl_depth_image.png" width="300" alt="Control image (Canny edges)"/>
151
+ <figcaption style="text-align: center;">depth map</figcaption>
152
+ </figure>
153
+ <figure>
154
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/t2i-multi-rabbit.png" width="300" alt="Generated image (ControlNet + prompt)"/>
155
+ <figcaption style="text-align: center;">generated image</figcaption>
156
+ </figure>
157
+ </div>
tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/text-img2vid.md ADDED
@@ -0,0 +1,447 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Video generation
14
+
15
+ Video generation models extend image generation (can be considered a 1-frame video) to also process data related to space and time. Making sure all this data - text, space, time - remain consistent and aligned from frame-to-frame is a big challenge in generating long and high-resolution videos.
16
+
17
+ Modern video models tackle this challenge with the diffusion transformer (DiT) architecture. This reduces computational costs and allows more efficient scaling to larger and higher-quality image and video data.
18
+
19
+ Check out what some of these video models are capable of below.
20
+
21
+ <hfoptions id="popular models">
22
+ <hfoption id="Wan2.1">
23
+
24
+ ```py
25
+ # pip install ftfy
26
+ import torch
27
+ import numpy as np
28
+ from diffusers import AutoModel, WanPipeline
29
+ from diffusers.hooks.group_offloading import apply_group_offloading
30
+ from diffusers.utils import export_to_video, load_image
31
+ from transformers import UMT5EncoderModel
32
+
33
+ text_encoder = UMT5EncoderModel.from_pretrained("Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="text_encoder", torch_dtype=torch.bfloat16)
34
+ vae = AutoModel.from_pretrained("Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="vae", torch_dtype=torch.float32)
35
+ transformer = AutoModel.from_pretrained("Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="transformer", torch_dtype=torch.bfloat16)
36
+
37
+ # group-offloading
38
+ onload_device = torch.device("cuda")
39
+ offload_device = torch.device("cpu")
40
+ apply_group_offloading(text_encoder,
41
+ onload_device=onload_device,
42
+ offload_device=offload_device,
43
+ offload_type="block_level",
44
+ num_blocks_per_group=4
45
+ )
46
+ transformer.enable_group_offload(
47
+ onload_device=onload_device,
48
+ offload_device=offload_device,
49
+ offload_type="leaf_level",
50
+ use_stream=True
51
+ )
52
+
53
+ pipeline = WanPipeline.from_pretrained(
54
+ "Wan-AI/Wan2.1-T2V-14B-Diffusers",
55
+ vae=vae,
56
+ transformer=transformer,
57
+ text_encoder=text_encoder,
58
+ torch_dtype=torch.bfloat16
59
+ )
60
+ pipeline.to("cuda")
61
+
62
+ prompt = """
63
+ The camera rushes from far to near in a low-angle shot,
64
+ revealing a white ferret on a log. It plays, leaps into the water, and emerges, as the camera zooms in
65
+ for a close-up. Water splashes berry bushes nearby, while moss, snow, and leaves blanket the ground.
66
+ Birch trees and a light blue sky frame the scene, with ferns in the foreground. Side lighting casts dynamic
67
+ shadows and warm highlights. Medium composition, front view, low angle, with depth of field.
68
+ """
69
+ negative_prompt = """
70
+ Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality,
71
+ low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured,
72
+ misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards
73
+ """
74
+
75
+ output = pipeline(
76
+ prompt=prompt,
77
+ negative_prompt=negative_prompt,
78
+ num_frames=81,
79
+ guidance_scale=5.0,
80
+ ).frames[0]
81
+ export_to_video(output, "output.mp4", fps=16)
82
+ ```
83
+
84
+ </hfoption>
85
+ <hfoption id="HunyuanVideo">
86
+
87
+ ```py
88
+ import torch
89
+ from diffusers importAutoModel, HunyuanVideoPipeline
90
+ from diffusers.quantizers import PipelineQuantizationConfig
91
+ from diffusers.utils import export_to_video
92
+
93
+ # quantize weights to int4 with bitsandbytes
94
+ pipeline_quant_config = PipelineQuantizationConfig(
95
+ quant_backend="bitsandbytes_4bit",
96
+ quant_kwargs={
97
+ "load_in_4bit": True,
98
+ "bnb_4bit_quant_type": "nf4",
99
+ "bnb_4bit_compute_dtype": torch.bfloat16
100
+ },
101
+ components_to_quantize="transformer"
102
+ )
103
+
104
+ pipeline = HunyuanVideoPipeline.from_pretrained(
105
+ "hunyuanvideo-community/HunyuanVideo",
106
+ quantization_config=pipeline_quant_config,
107
+ torch_dtype=torch.bfloat16,
108
+ )
109
+
110
+ # model-offloading and tiling
111
+ pipeline.enable_model_cpu_offload()
112
+ pipeline.vae.enable_tiling()
113
+
114
+ prompt = "A fluffy teddy bear sits on a bed of soft pillows surrounded by children's toys."
115
+ video = pipeline(prompt=prompt, num_frames=61, num_inference_steps=30).frames[0]
116
+ export_to_video(video, "output.mp4", fps=15)
117
+ ```
118
+
119
+ </hfoption>
120
+ <hfoption id="LTX-Video">
121
+
122
+ ```py
123
+ import torch
124
+ from diffusers import LTXPipeline, AutoModel
125
+ from diffusers.hooks import apply_group_offloading
126
+ from diffusers.utils import export_to_video
127
+
128
+ # fp8 layerwise weight-casting
129
+ transformer = AutoModel.from_pretrained(
130
+ "Lightricks/LTX-Video",
131
+ subfolder="transformer",
132
+ torch_dtype=torch.bfloat16
133
+ )
134
+ transformer.enable_layerwise_casting(
135
+ storage_dtype=torch.float8_e4m3fn, compute_dtype=torch.bfloat16
136
+ )
137
+
138
+ pipeline = LTXPipeline.from_pretrained("Lightricks/LTX-Video", transformer=transformer, torch_dtype=torch.bfloat16)
139
+
140
+ # group-offloading
141
+ onload_device = torch.device("cuda")
142
+ offload_device = torch.device("cpu")
143
+ pipeline.transformer.enable_group_offload(onload_device=onload_device, offload_device=offload_device, offload_type="leaf_level", use_stream=True)
144
+ apply_group_offloading(pipeline.text_encoder, onload_device=onload_device, offload_type="block_level", num_blocks_per_group=2)
145
+ apply_group_offloading(pipeline.vae, onload_device=onload_device, offload_type="leaf_level")
146
+
147
+ prompt = """
148
+ A woman with long brown hair and light skin smiles at another woman with long blonde hair. The woman with brown hair wears a black jacket and has a small, barely noticeable mole on her right cheek. The camera angle is a close-up, focused on the woman with brown hair's face. The lighting is warm and natural, likely from the setting sun, casting a soft glow on the scene. The scene appears to be real-life footage
149
+ """
150
+ negative_prompt = "worst quality, inconsistent motion, blurry, jittery, distorted"
151
+
152
+ video = pipeline(
153
+ prompt=prompt,
154
+ negative_prompt=negative_prompt,
155
+ width=768,
156
+ height=512,
157
+ num_frames=161,
158
+ decode_timestep=0.03,
159
+ decode_noise_scale=0.025,
160
+ num_inference_steps=50,
161
+ ).frames[0]
162
+ export_to_video(video, "output.mp4", fps=24)
163
+ ```
164
+
165
+ </hfoption>
166
+ </hfoptions>
167
+
168
+ This guide will cover video generation basics such as which parameters to configure and how to reduce their memory usage.
169
+
170
+ > [!TIP]
171
+ > If you're interested in learning more about how to use a specific model, please refer to their pipeline API model card.
172
+
173
+ ## Pipeline parameters
174
+
175
+ There are several parameters to configure in the pipeline that'll affect video generation quality or speed. Experimenting with different parameter values is important for discovering the appropriate quality and speed tradeoff.
176
+
177
+ ### num_frames
178
+
179
+ A frame is a still image that is played in a sequence of other frames to create motion or a video. Control the number of frames generated per second with `num_frames`. Increasing `num_frames` increases perceived motion smoothness and visual coherence, making it especially important for videos with dynamic content. A higher `num_frames` value also increases video duration.
180
+
181
+ Some video models require more specific `num_frames` values for inference. For example, [`HunyuanVideoPipeline`] recommends calculating the `num_frames` with `(4 * num_frames) +1`. Always check a pipelines API model card to see if there is a recommended value.
182
+
183
+ ```py
184
+ import torch
185
+ from diffusers import LTXPipeline
186
+ from diffusers.utils import export_to_video
187
+
188
+ pipeline = LTXPipeline.from_pretrained(
189
+ "Lightricks/LTX-Video", torch_dtype=torch.bfloat16
190
+ ).to("cuda")
191
+
192
+ prompt = """
193
+ A woman with long brown hair and light skin smiles at another woman with long blonde hair. The woman
194
+ with brown hair wears a black jacket and has a small, barely noticeable mole on her right cheek. The
195
+ camera angle is a close-up, focused on the woman with brown hair's face. The lighting is warm and
196
+ natural, likely from the setting sun, casting a soft glow on the scene. The scene appears to be
197
+ real-life footage
198
+ """
199
+
200
+ video = pipeline(
201
+ prompt=prompt,
202
+ negative_prompt=negative_prompt,
203
+ width=768,
204
+ height=512,
205
+ num_frames=161,
206
+ decode_timestep=0.03,
207
+ decode_noise_scale=0.025,
208
+ num_inference_steps=50,
209
+ ).frames[0]
210
+ export_to_video(video, "output.mp4", fps=24)
211
+ ```
212
+
213
+ ### guidance_scale
214
+
215
+ Guidance scale or "cfg" controls how closely the generated frames adhere to the input conditioning (text, image or both). Increasing `guidance_scale` generates frames that resemble the input conditions more closely and includes finer details, but risk introducing artifacts and reducing output diversity. Lower `guidance_scale` values encourages looser prompt adherence and increased output variety, but details may not be as great. If it's too low, it may ignore your prompt entirely and generate random noise.
216
+
217
+ ```py
218
+ import torch
219
+ from diffusers import CogVideoXPipeline, CogVideoXTransformer3DModel
220
+ from diffusers.utils import export_to_video
221
+
222
+ pipeline = CogVideoXPipeline.from_pretrained(
223
+ "THUDM/CogVideoX-2b",
224
+ torch_dtype=torch.float16
225
+ ).to("cuda")
226
+
227
+ prompt = """
228
+ A detailed wooden toy ship with intricately carved masts and sails is seen gliding smoothly over
229
+ a plush, blue carpet that mimics the waves of the sea. The ship's hull is painted a rich brown,
230
+ with tiny windows. The carpet, soft and textured, provides a perfect backdrop, resembling an
231
+ oceanic expanse. Surrounding the ship are various other toys and children's items, hinting at
232
+ a playful environment. The scene captures the innocence and imagination of childhood,
233
+ with the toy ship's journey symbolizing endless adventures in a whimsical, indoor setting.
234
+ """
235
+
236
+ video = pipeline(
237
+ prompt=prompt,
238
+ guidance_scale=6,
239
+ num_inference_steps=50
240
+ ).frames[0]
241
+ export_to_video(video, "output.mp4", fps=8)
242
+ ```
243
+
244
+ ### negative_prompt
245
+
246
+ A negative prompt is useful for excluding things you don't want to see in the generated video. It is commonly used to refine the quality and alignment of the generated video by pushing the model away from undesirable elements like "blurry, distorted, ugly". This can create cleaner and more focused videos.
247
+
248
+ ```py
249
+ # pip install ftfy
250
+ import torch
251
+ from diffusers import WanPipeline
252
+ from diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepScheduler
253
+ from diffusers.utils import export_to_video
254
+
255
+ vae = AutoencoderKLWan.from_pretrained(
256
+ "Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="vae", torch_dtype=torch.float32
257
+ )
258
+ pipeline = WanPipeline.from_pretrained(
259
+ "Wan-AI/Wan2.1-T2V-14B-Diffusers", vae=vae, torch_dtype=torch.bfloat16
260
+ )
261
+ pipeline.scheduler = UniPCMultistepScheduler.from_config(
262
+ pipeline.scheduler.config, flow_shift=5.0
263
+ )
264
+ pipeline.to("cuda")
265
+
266
+ pipeline.load_lora_weights("benjamin-paine/steamboat-willie-14b", adapter_name="steamboat-willie")
267
+ pipeline.set_adapters("steamboat-willie")
268
+
269
+ pipeline.enable_model_cpu_offload()
270
+
271
+ # use "steamboat willie style" to trigger the LoRA
272
+ prompt = """
273
+ steamboat willie style, golden era animation, The camera rushes from far to near in a low-angle shot,
274
+ revealing a white ferret on a log. It plays, leaps into the water, and emerges, as the camera zooms in
275
+ for a close-up. Water splashes berry bushes nearby, while moss, snow, and leaves blanket the ground.
276
+ Birch trees and a light blue sky frame the scene, with ferns in the foreground. Side lighting casts
277
+ dynamic shadows and warm highlights. Medium composition, front view, low angle, with depth of field.
278
+ """
279
+
280
+ output = pipeline(
281
+ prompt=prompt,
282
+ num_frames=81,
283
+ guidance_scale=5.0,
284
+ ).frames[0]
285
+ export_to_video(output, "output.mp4", fps=16)
286
+ ```
287
+
288
+ ## Reduce memory usage
289
+
290
+ Recent video models like [`HunyuanVideoPipeline`] and [`WanPipeline`], which have 10B+ parameters, require a lot of memory and it often exceeds the memory available on consumer hardware. Diffusers offers several techniques for reducing the memory requirements of these large models.
291
+
292
+ > [!TIP]
293
+ > Refer to the [Reduce memory usage](../optimization/memory) guide for more details about other memory saving techniques.
294
+
295
+ One of these techniques is [group-offloading](../optimization/memory#group-offloading), which offloads groups of internal model layers (such as `torch.nn.Sequential`) to the CPU when it isn't being used. These layers are only loaded when they're needed for computation to avoid storing **all** the model components on the GPU. For a 14B parameter model like [`WanPipeline`], group-offloading can lower the required memory to ~13GB of VRAM.
296
+
297
+ ```py
298
+ # pip install ftfy
299
+ import torch
300
+ import numpy as np
301
+ from diffusers import AutoModel, WanPipeline
302
+ from diffusers.hooks.group_offloading import apply_group_offloading
303
+ from diffusers.utils import export_to_video, load_image
304
+ from transformers import UMT5EncoderModel
305
+
306
+ text_encoder = UMT5EncoderModel.from_pretrained("Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="text_encoder", torch_dtype=torch.bfloat16)
307
+ vae = AutoModel.from_pretrained("Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="vae", torch_dtype=torch.float32)
308
+ transformer = AutoModel.from_pretrained("Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="transformer", torch_dtype=torch.bfloat16)
309
+
310
+ # group-offloading
311
+ onload_device = torch.device("cuda")
312
+ offload_device = torch.device("cpu")
313
+ apply_group_offloading(text_encoder,
314
+ onload_device=onload_device,
315
+ offload_device=offload_device,
316
+ offload_type="block_level",
317
+ num_blocks_per_group=4
318
+ )
319
+ transformer.enable_group_offload(
320
+ onload_device=onload_device,
321
+ offload_device=offload_device,
322
+ offload_type="leaf_level",
323
+ use_stream=True
324
+ )
325
+
326
+ pipeline = WanPipeline.from_pretrained(
327
+ "Wan-AI/Wan2.1-T2V-14B-Diffusers",
328
+ vae=vae,
329
+ transformer=transformer,
330
+ text_encoder=text_encoder,
331
+ torch_dtype=torch.bfloat16
332
+ )
333
+ pipeline.to("cuda")
334
+
335
+ prompt = """
336
+ The camera rushes from far to near in a low-angle shot,
337
+ revealing a white ferret on a log. It plays, leaps into the water, and emerges, as the camera zooms in
338
+ for a close-up. Water splashes berry bushes nearby, while moss, snow, and leaves blanket the ground.
339
+ Birch trees and a light blue sky frame the scene, with ferns in the foreground. Side lighting casts dynamic
340
+ shadows and warm highlights. Medium composition, front view, low angle, with depth of field.
341
+ """
342
+ negative_prompt = """
343
+ Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality,
344
+ low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured,
345
+ misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards
346
+ """
347
+
348
+ output = pipeline(
349
+ prompt=prompt,
350
+ negative_prompt=negative_prompt,
351
+ num_frames=81,
352
+ guidance_scale=5.0,
353
+ ).frames[0]
354
+ export_to_video(output, "output.mp4", fps=16)
355
+ ```
356
+
357
+ Another option for reducing memory is to consider quantizing a model, which stores the model weights in a lower precision data type. However, quantization may impact video quality depending on the specific video model. Refer to the quantization [Overivew](../quantization/overview) to learn more about the different supported quantization backends.
358
+
359
+ The example below uses [bitsandbytes](../quantization/bitsandbytes) to quantize a model.
360
+
361
+ ```py
362
+ # pip install ftfy
363
+
364
+ import torch
365
+ from diffusers import WanPipeline
366
+ from diffusers import AutoModel, WanPipeline
367
+ from diffusers.quantizers import PipelineQuantizationConfig
368
+ from diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepScheduler
369
+ from transformers import UMT5EncoderModel
370
+ from diffusers.utils import export_to_video
371
+
372
+ # quantize transformer and text encoder weights with bitsandbytes
373
+ pipeline_quant_config = PipelineQuantizationConfig(
374
+ quant_backend="bitsandbytes_4bit",
375
+ quant_kwargs={"load_in_4bit": True},
376
+ components_to_quantize=["transformer", "text_encoder"]
377
+ )
378
+
379
+ vae = AutoModel.from_pretrained(
380
+ "Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="vae", torch_dtype=torch.float32
381
+ )
382
+ pipeline = WanPipeline.from_pretrained(
383
+ "Wan-AI/Wan2.1-T2V-14B-Diffusers", vae=vae, quantization_config=pipeline_quant_config, torch_dtype=torch.bfloat16
384
+ )
385
+ pipeline.scheduler = UniPCMultistepScheduler.from_config(
386
+ pipeline.scheduler.config, flow_shift=5.0
387
+ )
388
+ pipeline.to("cuda")
389
+
390
+ pipeline.load_lora_weights("benjamin-paine/steamboat-willie-14b", adapter_name="steamboat-willie")
391
+ pipeline.set_adapters("steamboat-willie")
392
+
393
+ pipeline.enable_model_cpu_offload()
394
+
395
+ # use "steamboat willie style" to trigger the LoRA
396
+ prompt = """
397
+ steamboat willie style, golden era animation, The camera rushes from far to near in a low-angle shot,
398
+ revealing a white ferret on a log. It plays, leaps into the water, and emerges, as the camera zooms in
399
+ for a close-up. Water splashes berry bushes nearby, while moss, snow, and leaves blanket the ground.
400
+ Birch trees and a light blue sky frame the scene, with ferns in the foreground. Side lighting casts
401
+ dynamic shadows and warm highlights. Medium composition, front view, low angle, with depth of field.
402
+ """
403
+
404
+ output = pipeline(
405
+ prompt=prompt,
406
+ num_frames=81,
407
+ guidance_scale=5.0,
408
+ ).frames[0]
409
+ export_to_video(output, "output.mp4", fps=16)
410
+ ```
411
+
412
+ ## Inference speed
413
+
414
+ [torch.compile](https://pytorch.org/tutorials/intermediate/torch_compile_tutorial_.html) can speedup inference by using optimized kernels. Compilation takes longer the first time, but once compiled, it is much faster. It is best to compile the pipeline once, and then use the pipeline multiple times without changing anything. A change, such as in the image size, triggers recompilation.
415
+
416
+ The example below compiles the transformer in the pipeline and uses the `"max-autotune"` mode to maximize performance.
417
+
418
+ ```py
419
+ import torch
420
+ from diffusers import CogVideoXPipeline, CogVideoXTransformer3DModel
421
+ from diffusers.utils import export_to_video
422
+
423
+ pipeline = CogVideoXPipeline.from_pretrained(
424
+ "THUDM/CogVideoX-2b",
425
+ torch_dtype=torch.float16
426
+ ).to("cuda")
427
+
428
+ # torch.compile
429
+ pipeline.transformer.to(memory_format=torch.channels_last)
430
+ pipeline.transformer = torch.compile(
431
+ pipeline.transformer, mode="max-autotune", fullgraph=True
432
+ )
433
+
434
+ prompt = """
435
+ A detailed wooden toy ship with intricately carved masts and sails is seen gliding smoothly over a plush, blue carpet that mimics the waves of the sea.
436
+ The ship's hull is painted a rich brown, with tiny windows. The carpet, soft and textured, provides a perfect backdrop, resembling an oceanic expanse.
437
+ Surrounding the ship are various other toys and children's items, hinting at a playful environment. The scene captures the innocence and imagination of childhood,
438
+ with the toy ship's journey symbolizing endless adventures in a whimsical, indoor setting.
439
+ """
440
+
441
+ video = pipeline(
442
+ prompt=prompt,
443
+ guidance_scale=6,
444
+ num_inference_steps=50
445
+ ).frames[0]
446
+ export_to_video(video, "output.mp4", fps=8)
447
+ ```
tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/textual_inversion_inference.md ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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://huggingface.co/papers/2208.01618) is a method for generating personalized images of a concept. It works by fine-tuning a models word embeddings on 3-5 images of the concept (for example, pixel art) that is associated with a unique token (`<sks>`). This allows you to use the `<sks>` token in your prompt to trigger the model to generate pixel art images.
16
+
17
+ Textual Inversion weights are very lightweight and typically only a few KBs because they're only word embeddings. However, this also means the word embeddings need to be loaded after loading a model with [`~DiffusionPipeline.from_pretrained`].
18
+
19
+ ```py
20
+ import torch
21
+ from diffusers import AutoPipelineForText2Image
22
+
23
+ pipeline = AutoPipelineForText2Image.from_pretrained(
24
+ "stable-diffusion-v1-5/stable-diffusion-v1-5",
25
+ torch_dtype=torch.float16
26
+ ).to("cuda")
27
+ ```
28
+
29
+ Load the word embeddings with [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] and include the unique token in the prompt to activate its generation.
30
+
31
+ ```py
32
+ pipeline.load_textual_inversion("sd-concepts-library/gta5-artwork")
33
+ prompt = "A cute brown bear eating a slice of pizza, stunning color scheme, masterpiece, illustration, <gta5-artwork> style"
34
+ pipeline(prompt).images[0]
35
+ ```
36
+
37
+ <div class="flex justify-center">
38
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/load_txt_embed.png" />
39
+ </div>
40
+
41
+ Textual Inversion can also be trained to learn *negative embeddings* to steer generation away from unwanted characteristics such as "blurry" or "ugly". It is useful for improving image quality.
42
+
43
+ EasyNegative is a widely used negative embedding that contains multiple learned negative concepts. Load the negative embeddings and specify the file name and token associated with the negative embeddings. Pass the token to `negative_prompt` in your pipeline to activate it.
44
+
45
+ ```py
46
+ import torch
47
+ from diffusers import AutoPipelineForText2Image
48
+
49
+ pipeline = AutoPipelineForText2Image.from_pretrained(
50
+ "stable-diffusion-v1-5/stable-diffusion-v1-5",
51
+ torch_dtype=torch.float16
52
+ ).to("cuda")
53
+ pipeline.load_textual_inversion(
54
+ "EvilEngine/easynegative",
55
+ weight_name="easynegative.safetensors",
56
+ token="easynegative"
57
+ )
58
+ prompt = "A cute brown bear eating a slice of pizza, stunning color scheme, masterpiece, illustration"
59
+ negative_prompt = "easynegative"
60
+ pipeline(prompt, negative_prompt).images[0]
61
+ ```
62
+
63
+ <div class="flex justify-center">
64
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/load_neg_embed.png" />
65
+ </div>
tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/unconditional_image_generation.md ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ [[open-in-colab]]
16
+
17
+ Unconditional image generation generates images that look like a random sample from the training data the model was trained on because the denoising process is not guided by any additional context like text or image.
18
+
19
+ To get started, use the [`DiffusionPipeline`] to load the [anton-l/ddpm-butterflies-128](https://huggingface.co/anton-l/ddpm-butterflies-128) checkpoint to generate images of butterflies. The [`DiffusionPipeline`] downloads and caches all the model components required to generate an image.
20
+
21
+ ```py
22
+ from diffusers import DiffusionPipeline
23
+
24
+ generator = DiffusionPipeline.from_pretrained("anton-l/ddpm-butterflies-128").to("cuda")
25
+ image = generator().images[0]
26
+ image
27
+ ```
28
+
29
+ > [!TIP]
30
+ > Want to generate images of something else? Take a look at the training [guide](../training/unconditional_training) to learn how to train a model to generate your own images.
31
+
32
+ The output image is a [`PIL.Image`](https://pillow.readthedocs.io/en/stable/reference/Image.html?highlight=image#the-image-class) object that can be saved:
33
+
34
+ ```py
35
+ image.save("generated_image.png")
36
+ ```
37
+
38
+ You can also try experimenting with the `num_inference_steps` parameter, which controls the number of denoising steps. More denoising steps typically produce higher quality images, but it'll take longer to generate. Feel free to play around with this parameter to see how it affects the image quality.
39
+
40
+ ```py
41
+ image = generator(num_inference_steps=100).images[0]
42
+ image
43
+ ```
44
+
45
+ Try out the Space below to generate an image of a butterfly!
46
+
47
+ <iframe
48
+ src="https://stevhliu-unconditional-image-generation.hf.space"
49
+ frameborder="0"
50
+ width="850"
51
+ height="500"
52
+ ></iframe>
tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/weighted_prompts.md ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2025 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ [[open-in-colab]]
14
+
15
+ # Prompting
16
+
17
+ Prompts describes what a model should generate. Good prompts are detailed, specific, and structured and they generate better images and videos.
18
+
19
+ This guide shows you how to write effective prompts and introduces techniques that make them stronger.
20
+
21
+ ## Writing good prompts
22
+
23
+ Every effective prompt needs three core elements.
24
+
25
+ 1. <span class="underline decoration-sky-500 decoration-2 underline-offset-4">Subject</span> - what you want to generate. Start your prompt here.
26
+ 2. <span class="underline decoration-pink-500 decoration-2 underline-offset-4">Style</span> - the medium or aesthetic. How should it look?
27
+ 3. <span class="underline decoration-green-500 decoration-2 underline-offset-4">Context</span> - details about actions, setting, and mood.
28
+
29
+ Use these elements as a structured narrative, not a keyword list. Modern models understand language better than keyword matching. Start simple, then add details.
30
+
31
+ Context is especially important for creating better prompts. Try adding lighting, artistic details, and mood.
32
+
33
+ <div class="flex gap-4">
34
+ <div class="flex-1 text-center">
35
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ok-prompt.png" class="w-full h-auto object-cover rounded-lg">
36
+ <figcaption class="mt-2 text-sm text-gray-500">A <span class="underline decoration-sky-500 decoration-2 underline-offset-1">cute cat</span> <span class="underline decoration-pink-500 decoration-2 underline-offset-1">lounges on a leaf in a pool during a peaceful summer afternoon</span>, in <span class="underline decoration-green-500 decoration-2 underline-offset-1">lofi art style, illustration</span>.</figcaption>
37
+ </div>
38
+ <div class="flex-1 text-center">
39
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/better-prompt.png" class="w-full h-auto object-cover rounded-lg"/>
40
+ <figcaption class="mt-2 text-sm text-gray-500">A cute cat lounges on a floating leaf in a sparkling pool during a peaceful summer afternoon. Clear reflections ripple across the water, with sunlight casting soft, smooth highlights. The illustration is detailed and polished, with elegant lines and harmonious colors, evoking a relaxing, serene, and whimsical lofi mood, anime-inspired and visually comforting.</figcaption>
41
+ </div>
42
+ </div>
43
+
44
+ Be specific and add context. Use photography terms like lens type, focal length, camera angles, and depth of field.
45
+
46
+ > [!TIP]
47
+ > Try a [prompt enhancer](https://huggingface.co/models?sort=downloads&search=prompt+enhancer) to help improve your prompt structure.
48
+
49
+ ## Prompt weighting
50
+
51
+ Prompt weighting makes some words stronger and others weaker. It scales attention scores so you control how much influence each concept has.
52
+
53
+ Diffusers handles this through `prompt_embeds` and `pooled_prompt_embeds` arguments which take scaled text embedding vectors. Use the [sd_embed](https://github.com/xhinker/sd_embed) library to generate these embeddings. It also supports longer prompts.
54
+
55
+ > [!NOTE]
56
+ > The sd_embed library only supports Stable Diffusion, Stable Diffusion XL, Stable Diffusion 3, Stable Cascade, and Flux. Prompt weighting doesn't necessarily help for newer models like Flux which already has very good prompt adherence.
57
+
58
+ ```py
59
+ !uv pip install git+https://github.com/xhinker/sd_embed.git@main
60
+ ```
61
+
62
+ Format weighted text with numerical multipliers or parentheses. More parentheses mean stronger weighting.
63
+
64
+ | format | multiplier |
65
+ |---|---|
66
+ | `(cat)` | increase by 1.1x |
67
+ | `((cat))` | increase by 1.21x |
68
+ | `(cat:1.5)` | increase by 1.5x |
69
+ | `(cat:0.5)` | decrease by 4x |
70
+
71
+ Create a weighted prompt and pass it to [get_weighted_text_embeddings_sdxl](https://github.com/xhinker/sd_embed/blob/4a47f71150a22942fa606fb741a1c971d95ba56f/src/sd_embed/embedding_funcs.py#L405) to generate embeddings.
72
+
73
+ > [!TIP]
74
+ > You could also pass negative prompts to `negative_prompt_embeds` and `negative_pooled_prompt_embeds`.
75
+
76
+ ```py
77
+ import torch
78
+ from diffusers import DiffusionPipeline
79
+ from sd_embed.embedding_funcs import get_weighted_text_embeddings_sdxl
80
+
81
+ pipeline = DiffusionPipeline.from_pretrained(
82
+ "Lykon/dreamshaper-xl-1-0", torch_dtype=torch.bfloat16, device_map="cuda"
83
+ )
84
+
85
+ prompt = """
86
+ A (cute cat:1.4) lounges on a (floating leaf:1.2) in a (sparkling pool:1.1) during a peaceful summer afternoon.
87
+ Gentle ripples reflect pastel skies, while (sunlight:1.1) casts soft highlights. The illustration is smooth and polished
88
+ with elegant, sketchy lines and subtle gradients, evoking a ((whimsical, nostalgic, dreamy lofi atmosphere:2.0)),
89
+ (anime-inspired:1.6), calming, comforting, and visually serene.
90
+ """
91
+
92
+ prompt_embeds, _, pooled_prompt_embeds, *_ = get_weighted_text_embeddings_sdxl(pipeline, prompt=prompt)
93
+ ```
94
+
95
+ Pass the embeddings to `prompt_embeds` and `pooled_prompt_embeds` to generate your image.
96
+
97
+ ```py
98
+ image = pipeline(prompt_embeds=prompt_embeds, pooled_prompt_embeds=pooled_prompt_embeds).images[0]
99
+ ```
100
+
101
+ <div class="flex justify-center">
102
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/prompt-embed-sdxl.png"/>
103
+ </div>
104
+
105
+ Prompt weighting works with [Textual inversion](./textual_inversion_inference) and [DreamBooth](./dreambooth) adapters too.
tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/en/using-diffusers/write_own_pipeline.md ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Understanding pipelines, models and schedulers
14
+
15
+ [[open-in-colab]]
16
+
17
+ 🧨 Diffusers is designed to be a user-friendly and flexible toolbox for building diffusion systems tailored to your use-case. At the core of the toolbox are models and schedulers. While the [`DiffusionPipeline`] bundles these components together for convenience, you can also unbundle the pipeline and use the models and schedulers separately to create new diffusion systems.
18
+
19
+ In this tutorial, you'll learn how to use models and schedulers to assemble a diffusion system for inference, starting with a basic pipeline and then progressing to the Stable Diffusion pipeline.
20
+
21
+ ## Deconstruct a basic pipeline
22
+
23
+ A pipeline is a quick and easy way to run a model for inference, requiring no more than four lines of code to generate an image:
24
+
25
+ ```py
26
+ >>> from diffusers import DDPMPipeline
27
+
28
+ >>> ddpm = DDPMPipeline.from_pretrained("google/ddpm-cat-256", use_safetensors=True).to("cuda")
29
+ >>> image = ddpm(num_inference_steps=25).images[0]
30
+ >>> image
31
+ ```
32
+
33
+ <div class="flex justify-center">
34
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/ddpm-cat.png" alt="Image of cat created from DDPMPipeline"/>
35
+ </div>
36
+
37
+ That was super easy, but how did the pipeline do that? Let's breakdown the pipeline and take a look at what's happening under the hood.
38
+
39
+ In the example above, the pipeline contains a [`UNet2DModel`] model and a [`DDPMScheduler`]. The pipeline denoises an image by taking random noise the size of the desired output and passing it through the model several times. At each timestep, the model predicts the *noise residual* and the scheduler uses it to predict a less noisy image. The pipeline repeats this process until it reaches the end of the specified number of inference steps.
40
+
41
+ To recreate the pipeline with the model and scheduler separately, let's write our own denoising process.
42
+
43
+ 1. Load the model and scheduler:
44
+
45
+ ```py
46
+ >>> from diffusers import DDPMScheduler, UNet2DModel
47
+
48
+ >>> scheduler = DDPMScheduler.from_pretrained("google/ddpm-cat-256")
49
+ >>> model = UNet2DModel.from_pretrained("google/ddpm-cat-256", use_safetensors=True).to("cuda")
50
+ ```
51
+
52
+ 2. Set the number of timesteps to run the denoising process for:
53
+
54
+ ```py
55
+ >>> scheduler.set_timesteps(50)
56
+ ```
57
+
58
+ 3. Setting the scheduler timesteps creates a tensor with evenly spaced elements in it, 50 in this example. Each element corresponds to a timestep at which the model denoises an image. When you create the denoising loop later, you'll iterate over this tensor to denoise an image:
59
+
60
+ ```py
61
+ >>> scheduler.timesteps
62
+ tensor([980, 960, 940, 920, 900, 880, 860, 840, 820, 800, 780, 760, 740, 720,
63
+ 700, 680, 660, 640, 620, 600, 580, 560, 540, 520, 500, 480, 460, 440,
64
+ 420, 400, 380, 360, 340, 320, 300, 280, 260, 240, 220, 200, 180, 160,
65
+ 140, 120, 100, 80, 60, 40, 20, 0])
66
+ ```
67
+
68
+ 4. Create some random noise with the same shape as the desired output:
69
+
70
+ ```py
71
+ >>> import torch
72
+
73
+ >>> sample_size = model.config.sample_size
74
+ >>> noise = torch.randn((1, 3, sample_size, sample_size), device="cuda")
75
+ ```
76
+
77
+ 5. Now write a loop to iterate over the timesteps. At each timestep, the model does a [`UNet2DModel.forward`] pass and returns the noisy residual. The scheduler's [`~DDPMScheduler.step`] method takes the noisy residual, timestep, and input and it predicts the image at the previous timestep. This output becomes the next input to the model in the denoising loop, and it'll repeat until it reaches the end of the `timesteps` array.
78
+
79
+ ```py
80
+ >>> input = noise
81
+
82
+ >>> for t in scheduler.timesteps:
83
+ ... with torch.no_grad():
84
+ ... noisy_residual = model(input, t).sample
85
+ ... previous_noisy_sample = scheduler.step(noisy_residual, t, input).prev_sample
86
+ ... input = previous_noisy_sample
87
+ ```
88
+
89
+ This is the entire denoising process, and you can use this same pattern to write any diffusion system.
90
+
91
+ 6. The last step is to convert the denoised output into an image:
92
+
93
+ ```py
94
+ >>> from PIL import Image
95
+ >>> import numpy as np
96
+
97
+ >>> image = (input / 2 + 0.5).clamp(0, 1).squeeze()
98
+ >>> image = (image.permute(1, 2, 0) * 255).round().to(torch.uint8).cpu().numpy()
99
+ >>> image = Image.fromarray(image)
100
+ >>> image
101
+ ```
102
+
103
+ In the next section, you'll put your skills to the test and breakdown the more complex Stable Diffusion pipeline. The steps are more or less the same. You'll initialize the necessary components, and set the number of timesteps to create a `timestep` array. The `timestep` array is used in the denoising loop, and for each element in this array, the model predicts a less noisy image. The denoising loop iterates over the `timestep`'s, and at each timestep, it outputs a noisy residual and the scheduler uses it to predict a less noisy image at the previous timestep. This process is repeated until you reach the end of the `timestep` array.
104
+
105
+ Let's try it out!
106
+
107
+ ## Deconstruct the Stable Diffusion pipeline
108
+
109
+ Stable Diffusion is a text-to-image *latent diffusion* model. It is called a latent diffusion model because it works with a lower-dimensional representation of the image instead of the actual pixel space, which makes it more memory efficient. The encoder compresses the image into a smaller representation, and a decoder converts the compressed representation back into an image. For text-to-image models, you'll need a tokenizer and an encoder to generate text embeddings. From the previous example, you already know you need a UNet model and a scheduler.
110
+
111
+ As you can see, this is already more complex than the DDPM pipeline which only contains a UNet model. The Stable Diffusion model has three separate pretrained models.
112
+
113
+ > [!TIP]
114
+ > 💡 Read the [How does Stable Diffusion work?](https://huggingface.co/blog/stable_diffusion#how-does-stable-diffusion-work) blog for more details about how the VAE, UNet, and text encoder models work.
115
+
116
+ Now that you know what you need for the Stable Diffusion pipeline, load all these components with the [`~ModelMixin.from_pretrained`] method. You can find them in the pretrained [`stable-diffusion-v1-5/stable-diffusion-v1-5`](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5) checkpoint, and each component is stored in a separate subfolder:
117
+
118
+ ```py
119
+ >>> from PIL import Image
120
+ >>> import torch
121
+ >>> from transformers import CLIPTextModel, CLIPTokenizer
122
+ >>> from diffusers import AutoencoderKL, UNet2DConditionModel, PNDMScheduler
123
+
124
+ >>> vae = AutoencoderKL.from_pretrained("CompVis/stable-diffusion-v1-4", subfolder="vae", use_safetensors=True)
125
+ >>> tokenizer = CLIPTokenizer.from_pretrained("CompVis/stable-diffusion-v1-4", subfolder="tokenizer")
126
+ >>> text_encoder = CLIPTextModel.from_pretrained(
127
+ ... "CompVis/stable-diffusion-v1-4", subfolder="text_encoder", use_safetensors=True
128
+ ... )
129
+ >>> unet = UNet2DConditionModel.from_pretrained(
130
+ ... "CompVis/stable-diffusion-v1-4", subfolder="unet", use_safetensors=True
131
+ ... )
132
+ ```
133
+
134
+ Instead of the default [`PNDMScheduler`], exchange it for the [`UniPCMultistepScheduler`] to see how easy it is to plug a different scheduler in:
135
+
136
+ ```py
137
+ >>> from diffusers import UniPCMultistepScheduler
138
+
139
+ >>> scheduler = UniPCMultistepScheduler.from_pretrained("CompVis/stable-diffusion-v1-4", subfolder="scheduler")
140
+ ```
141
+
142
+ To speed up inference, move the models to a GPU since, unlike the scheduler, they have trainable weights:
143
+
144
+ ```py
145
+ >>> torch_device = "cuda"
146
+ >>> vae.to(torch_device)
147
+ >>> text_encoder.to(torch_device)
148
+ >>> unet.to(torch_device)
149
+ ```
150
+
151
+ ### Create text embeddings
152
+
153
+ The next step is to tokenize the text to generate embeddings. The text is used to condition the UNet model and steer the diffusion process towards something that resembles the input prompt.
154
+
155
+ > [!TIP]
156
+ > 💡 The `guidance_scale` parameter determines how much weight should be given to the prompt when generating an image.
157
+
158
+ Feel free to choose any prompt you like if you want to generate something else!
159
+
160
+ ```py
161
+ >>> prompt = ["a photograph of an astronaut riding a horse"]
162
+ >>> height = 512 # default height of Stable Diffusion
163
+ >>> width = 512 # default width of Stable Diffusion
164
+ >>> num_inference_steps = 25 # Number of denoising steps
165
+ >>> guidance_scale = 7.5 # Scale for classifier-free guidance
166
+ >>> generator = torch.manual_seed(0) # Seed generator to create the initial latent noise
167
+ >>> batch_size = len(prompt)
168
+ ```
169
+
170
+ Tokenize the text and generate the embeddings from the prompt:
171
+
172
+ ```py
173
+ >>> text_input = tokenizer(
174
+ ... prompt, padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt"
175
+ ... )
176
+
177
+ >>> with torch.no_grad():
178
+ ... text_embeddings = text_encoder(text_input.input_ids.to(torch_device))[0]
179
+ ```
180
+
181
+ You'll also need to generate the *unconditional text embeddings* which are the embeddings for the padding token. These need to have the same shape (`batch_size` and `seq_length`) as the conditional `text_embeddings`:
182
+
183
+ ```py
184
+ >>> max_length = text_input.input_ids.shape[-1]
185
+ >>> uncond_input = tokenizer([""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt")
186
+ >>> uncond_embeddings = text_encoder(uncond_input.input_ids.to(torch_device))[0]
187
+ ```
188
+
189
+ Let's concatenate the conditional and unconditional embeddings into a batch to avoid doing two forward passes:
190
+
191
+ ```py
192
+ >>> text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
193
+ ```
194
+
195
+ ### Create random noise
196
+
197
+ Next, generate some initial random noise as a starting point for the diffusion process. This is the latent representation of the image, and it'll be gradually denoised. At this point, the `latent` image is smaller than the final image size but that's okay though because the model will transform it into the final 512x512 image dimensions later.
198
+
199
+ > [!TIP]
200
+ > 💡 The height and width are divided by 8 because the `vae` model has 3 down-sampling layers. You can check by running the following:
201
+ >
202
+ > ```py
203
+ > 2 ** (len(vae.config.block_out_channels) - 1) == 8
204
+ > ```
205
+
206
+ ```py
207
+ >>> latents = torch.randn(
208
+ ... (batch_size, unet.config.in_channels, height // 8, width // 8),
209
+ ... generator=generator,
210
+ ... device=torch_device,
211
+ ... )
212
+ ```
213
+
214
+ ### Denoise the image
215
+
216
+ Start by scaling the input with the initial noise distribution, *sigma*, the noise scale value, which is required for improved schedulers like [`UniPCMultistepScheduler`]:
217
+
218
+ ```py
219
+ >>> latents = latents * scheduler.init_noise_sigma
220
+ ```
221
+
222
+ The last step is to create the denoising loop that'll progressively transform the pure noise in `latents` to an image described by your prompt. Remember, the denoising loop needs to do three things:
223
+
224
+ 1. Set the scheduler's timesteps to use during denoising.
225
+ 2. Iterate over the timesteps.
226
+ 3. At each timestep, call the UNet model to predict the noise residual and pass it to the scheduler to compute the previous noisy sample.
227
+
228
+ ```py
229
+ >>> from tqdm.auto import tqdm
230
+
231
+ >>> scheduler.set_timesteps(num_inference_steps)
232
+
233
+ >>> for t in tqdm(scheduler.timesteps):
234
+ ... # expand the latents if we are doing classifier-free guidance to avoid doing two forward passes.
235
+ ... latent_model_input = torch.cat([latents] * 2)
236
+
237
+ ... latent_model_input = scheduler.scale_model_input(latent_model_input, timestep=t)
238
+
239
+ ... # predict the noise residual
240
+ ... with torch.no_grad():
241
+ ... noise_pred = unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
242
+
243
+ ... # perform guidance
244
+ ... noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
245
+ ... noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
246
+
247
+ ... # compute the previous noisy sample x_t -> x_t-1
248
+ ... latents = scheduler.step(noise_pred, t, latents).prev_sample
249
+ ```
250
+
251
+ ### Decode the image
252
+
253
+ The final step is to use the `vae` to decode the latent representation into an image and get the decoded output with `sample`:
254
+
255
+ ```py
256
+ # scale and decode the image latents with vae
257
+ latents = 1 / 0.18215 * latents
258
+ with torch.no_grad():
259
+ image = vae.decode(latents).sample
260
+ ```
261
+
262
+ Lastly, convert the image to a `PIL.Image` to see your generated image!
263
+
264
+ ```py
265
+ >>> image = (image / 2 + 0.5).clamp(0, 1).squeeze()
266
+ >>> image = (image.permute(1, 2, 0) * 255).to(torch.uint8).cpu().numpy()
267
+ >>> image = Image.fromarray(image)
268
+ >>> image
269
+ ```
270
+
271
+ <div class="flex justify-center">
272
+ <img src="https://huggingface.co/blog/assets/98_stable_diffusion/stable_diffusion_k_lms.png"/>
273
+ </div>
274
+
275
+ ## Next steps
276
+
277
+ From basic to complex pipelines, you've seen that all you really need to write your own diffusion system is a denoising loop. The loop should set the scheduler's timesteps, iterate over them, and alternate between calling the UNet model to predict the noise residual and passing it to the scheduler to compute the previous noisy sample.
278
+
279
+ This is really what 🧨 Diffusers is designed for: to make it intuitive and easy to write your own diffusion system using models and schedulers.
280
+
281
+ For your next steps, feel free to:
282
+
283
+ * Learn how to [build and contribute a pipeline](../conceptual/contribution) to 🧨 Diffusers. We can't wait and see what you'll come up with!
284
+ * Explore [existing pipelines](../api/pipelines/overview) in the library, and see if you can deconstruct and build a pipeline from scratch using the models and schedulers separately.
tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/ja/_toctree.yml ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - sections:
2
+ - local: index
3
+ title: 🧨 Diffusers
4
+ - local: quicktour
5
+ title: クイックツアー
6
+ - local: stable_diffusion
7
+ title: 有効で効率の良い拡散モデル
8
+ - local: installation
9
+ title: インストール
10
+ title: はじめに
11
+ - sections:
12
+ - local: tutorials/tutorial_overview
13
+ title: 概要
14
+ - local: tutorials/autopipeline
15
+ title: AutoPipeline
16
+ title: チュートリアル
tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/ja/index.md ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2025 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ <p align="center">
14
+ <br>
15
+ <img src="https://raw.githubusercontent.com/huggingface/diffusers/77aadfee6a891ab9fcfb780f87c693f7a5beeb8e/docs/source/imgs/diffusers_library.jpg" width="400"/>
16
+ <br>
17
+ </p>
18
+
19
+ # Diffusers
20
+
21
+ 🤗 Diffusers は、画像や音声、さらには分子の3D構造を生成するための、最先端の事前学習済みDiffusion Model(拡散モデル)を提供するライブラリです。シンプルな生成ソリューションをお探しの場合でも、独自の拡散モデルをトレーニングしたい場合でも、🤗 Diffusers はその両方をサポートするモジュール式のツールボックスです。私たちのライブラリは、[性能より使いやすさ](conceptual/philosophy#usability-over-performance)、[簡単よりシンプル](conceptual/philosophy#simple-over-easy)、[抽象化よりカスタマイズ性](conceptual/philosophy#tweakable-contributorfriendly-over-abstraction)に重点を置いて設計されています。
22
+
23
+ このライブラリには3つの主要コンポーネントがあります:
24
+
25
+ - 数行のコードで推論可能な最先端の[拡散パイプライン](api/pipelines/overview)。Diffusersには多くのパイプラインがあります。利用可能なパイプラインを網羅したリストと、それらが解決するタスクについては、パイプラインの[概要](https://huggingface.co/docs/diffusers/api/pipelines/overview)の表をご覧ください。
26
+ - 生成速度と品質のトレードオフのバランスを取る交換可能な[ノイズスケジューラ](api/schedulers/overview)
27
+ - ビルディングブロックとして使用することができ、スケジューラと組み合わせることで、エンドツーエンドの拡散モデルを構築可能な事前学習済み[モデル](api/models)
28
+
29
+ <div class="mt-10">
30
+ <div class="w-full flex flex-col space-y-4 md:space-y-0 md:grid md:grid-cols-2 md:gap-y-4 md:gap-x-5">
31
+ <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./tutorials/tutorial_overview"
32
+ ><div class="w-full text-center bg-gradient-to-br from-blue-400 to-blue-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">チュートリアル</div>
33
+ <p class="text-gray-700">出力の生成、独自の拡散システムの構築、拡散モデルのトレーニングを開始するために必要な基本的なスキルを学ぶことができます。初めて 🤗Diffusersを使用する場合は、ここから始めることをおすすめします!</p>
34
+ </a>
35
+ <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./using-diffusers/loading_overview"
36
+ ><div class="w-full text-center bg-gradient-to-br from-indigo-400 to-indigo-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">ガイド</div>
37
+ <p class="text-gray-700">パイプライン、モデル、スケジューラの読み込みに役立つ実践的なガイドです。また、特定のタスクにパイプラインを使用する方法、出力の生成方法を制御する方法、生成速度を最適化する方法、さまざまなトレーニング手法についても学ぶことができます。</p>
38
+ </a>
39
+ <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./conceptual/philosophy"
40
+ ><div class="w-full text-center bg-gradient-to-br from-pink-400 to-pink-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Conceptual guides</div>
41
+ <p class="text-gray-700">ライブラリがなぜこのように設計されたのかを理解し、ライブラリを利用する際の倫理的ガイドラインや安全対策について詳しく学べます。</p>
42
+ </a>
43
+ <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./api/models/overview"
44
+ ><div class="w-full text-center bg-gradient-to-br from-purple-400 to-purple-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">リファレンス</div>
45
+ <p class="text-gray-700">🤗 Diffusersのクラスとメソッドがどのように機能するかについての技術的な説明です。</p>
46
+ </a>
47
+ </div>
48
+ </div>
tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/ja/installation.md ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
15
+ お使いのディープラーニングライブラリに合わせてDiffusersをインストールできます。
16
+
17
+ 🤗 DiffusersはPython 3.8+、PyTorch 1.7.0+、Flaxでテストされています。使用するディープラーニングライブラリの以下のインストール手順に従ってください:
18
+
19
+ - [PyTorch](https://pytorch.org/get-started/locally/)のインストール手順。
20
+ - [Flax](https://flax.readthedocs.io/en/latest/)のインストール手順。
21
+
22
+ ## pip でインストール
23
+
24
+ Diffusersは[仮想環境](https://docs.python.org/3/library/venv.html)の中でインストールすることが推奨されています。
25
+ Python の仮想環境についてよく知らない場合は、こちらの [ガイド](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/) を参照してください。
26
+ 仮想環境は異なるプロジェクトの管理を容易にし、依存関係間の互換性の問題を回避します。
27
+
28
+ ではさっそく、プロジェクトディレクトリに仮想環境を作ってみます:
29
+
30
+ ```bash
31
+ python -m venv .env
32
+ ```
33
+
34
+ 仮想環境をアクティブにします:
35
+
36
+ ```bash
37
+ source .env/bin/activate
38
+ ```
39
+
40
+ 🤗 Diffusers もまた 🤗 Transformers ライブラリに依存しており、以下のコマンドで両方をインストールできます:
41
+
42
+ <frameworkcontent>
43
+ <pt>
44
+ ```bash
45
+ pip install diffusers["torch"] transformers
46
+ ```
47
+ </pt>
48
+ <jax>
49
+ ```bash
50
+ pip install diffusers["flax"] transformers
51
+ ```
52
+ </jax>
53
+ </frameworkcontent>
54
+
55
+ ## ソースからのインストール
56
+
57
+ ソースから🤗 Diffusersをインストールする前に、`torch`と🤗 Accelerateがインストールされていることを確認してください。
58
+
59
+ `torch`のインストールについては、`torch` [インストール](https://pytorch.org/get-started/locally/#start-locally)ガイドを参照してください。
60
+
61
+ 🤗 Accelerateをインストールするには:
62
+
63
+ ```bash
64
+ pip install accelerate
65
+ ```
66
+
67
+ 以下のコマンドでソースから🤗 Diffusersをインストールできます:
68
+
69
+ ```bash
70
+ pip install git+https://github.com/huggingface/diffusers
71
+ ```
72
+
73
+ このコマンドは最新の `stable` バージョンではなく、最先端の `main` バージョンをインストールします。
74
+ `main`バージョンは最新の開発に対応するのに便利です。
75
+ 例えば、前回の公式リリース以降にバグが修正されたが、新しいリリースがまだリリースされていない場合などには都合がいいです。
76
+ しかし、これは `main` バージョンが常に安定しているとは限らないです。
77
+ 私たちは `main` バージョンを運用し続けるよう努力しており、ほとんどの問題は通常数時間から1日以内に解決されます。
78
+ もし問題が発生した場合は、[Issue](https://github.com/huggingface/diffusers/issues/new/choose) を開いてください!
79
+
80
+ ## 編集可能なインストール
81
+
82
+ 以下の場合、編集可能なインストールが必要です:
83
+
84
+ * ソースコードの `main` バージョンを使用する。
85
+ * 🤗 Diffusers に貢献し、コードの変更をテストする必要がある場合。
86
+
87
+ リポジトリをクローンし、次のコマンドで 🤗 Diffusers をインストールしてください:
88
+
89
+ ```bash
90
+ git clone https://github.com/huggingface/diffusers.git
91
+ cd diffusers
92
+ ```
93
+
94
+ <frameworkcontent>
95
+ <pt>
96
+ ```bash
97
+ pip install -e ".[torch]"
98
+ ```
99
+ </pt>
100
+ <jax>
101
+ ```bash
102
+ pip install -e ".[flax]"
103
+ ```
104
+ </jax>
105
+ </frameworkcontent>
106
+
107
+ これらのコマンドは、リポジトリをクローンしたフォルダと Python のライブラリパスをリンクします。
108
+ Python は通常のライブラリパスに加えて、クローンしたフォルダの中を探すようになります。
109
+ 例えば、Python パッケージが通常 `~/anaconda3/envs/main/lib/python3.10/site-packages/` にインストールされている場合、Python はクローンした `~/diffusers/` フォルダも同様に参照します。
110
+
111
+ > [!WARNING]
112
+ > ライブラリを使い続けたい場合は、`diffusers`フォルダを残しておく必要があります。
113
+
114
+ これで、以下のコマンドで簡単にクローンを最新版の🤗 Diffusersにアップデートできます:
115
+
116
+ ```bash
117
+ cd ~/diffusers/
118
+ git pull
119
+ ```
120
+
121
+ Python環境は次の実行時�� `main` バージョンの🤗 Diffusersを見つけます。
122
+
123
+ ## テレメトリー・ロギングに関するお知らせ
124
+
125
+ このライブラリは `from_pretrained()` リクエスト中にデータを収集します。
126
+ このデータには Diffusers と PyTorch/Flax のバージョン、要求されたモデルやパイプラインクラスが含まれます。
127
+ また、Hubでホストされている場合は、事前に学習されたチェックポイントへのパスが含まれます。
128
+ この使用データは問題のデバッグや新機能の優先順位付けに役立ちます。
129
+ テレメトリーはHuggingFace Hubからモデルやパイプラインをロードするときのみ送信されます。ローカルでの使用中は収集されません。
130
+
131
+ 我々は、すべての人が追加情報を共有したくないことを理解し、あなたのプライバシーを尊重します。
132
+ そのため、ターミナルから `DISABLE_TELEMETRY` 環境変数を設定することで、データ収集を無効にすることができます:
133
+
134
+ Linux/MacOSの場合
135
+ ```bash
136
+ export DISABLE_TELEMETRY=YES
137
+ ```
138
+
139
+ Windows の場合
140
+ ```bash
141
+ set DISABLE_TELEMETRY=YES
142
+ ```
tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/ja/quicktour.md ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # 簡単な案内
16
+
17
+ 拡散モデル(Diffusion Model)は、ランダムな正規分布から段階的にノイズ除去するように学習され、画像や音声などの目的のものを生成できます。これは生成AIに多大な関心を呼び起こしました。インターネット上で拡散によって生成された画像の例を見たことがあるでしょう。🧨 Diffusersは、誰もが拡散モデルに広くアクセスできるようにすることを目的としたライブラリです。
18
+
19
+ この案内では、開発者または日常的なユーザーに関わらず、🧨 Diffusers を紹介し、素早く目的のものを生成できるようにします!このライブラリには3つの主要コンポーネントがあります:
20
+
21
+ * [`DiffusionPipeline`]は事前に学習された拡散モデルからサンプルを迅速に生成するために設計された高レベルのエンドツーエンドクラス。
22
+ * 拡散システムを作成するためのビルディングブロックとして使用できる、人気のある事前学習された[モデル](./api/models)アーキテクチャとモジュール。
23
+ * 多くの異なる[スケジューラ](./api/schedulers/overview) - ノイズがどのようにトレーニングのために加えられるか、そして生成中にどのようにノイズ除去された画像を生成するかを制御するアルゴリズム。
24
+
25
+ この案内では、[`DiffusionPipeline`]を生成に使用する方法を紹介し、モデルとスケジューラを組み合わせて[`DiffusionPipeline`]の内部で起こっていることを再現する方法を説明します。
26
+
27
+ > [!TIP]
28
+ > この案内は🧨 Diffusers [ノートブック](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/diffusers_intro.ipynb)を簡略化したもので、すぐに使い始めることができます。Diffusers 🧨のゴール、設計哲学、コアAPIの詳細についてもっと知りたい方は、ノートブックをご覧ください!
29
+
30
+ 始める前に必要なライブラリーがすべてインストールされていることを確認してください:
31
+
32
+ ```py
33
+ # uncomment to install the necessary libraries in Colab
34
+ #!pip install --upgrade diffusers accelerate transformers
35
+ ```
36
+
37
+ - [🤗 Accelerate](https://huggingface.co/docs/accelerate/index)生成とトレーニングのためのモデルのロードを高速化します
38
+ - [Stable Diffusion](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/overview)ような最も一般的な拡散モデルを実行するには、[🤗 Transformers](https://huggingface.co/docs/transformers/index)が必要です。
39
+
40
+ ## 拡散パイプライン
41
+
42
+ [`DiffusionPipeline`]は事前学習された拡散システムを生成に使用する最も簡単な方法です。これはモデルとスケジューラを含むエンドツーエンドのシステムです。[`DiffusionPipeline`]は多くの作業/タスクにすぐに使用することができます。また、サポートされているタスクの完全なリストについては[🧨Diffusersの概要](./api/pipelines/overview#diffusers-summary)の表を参照してください。
43
+
44
+ | **タスク** | **説明** | **パイプライン**
45
+ |------------------------------|--------------------------------------------------------------------------------------------------------------|-----------------|
46
+ | Unconditional Image Generation | 正規分布から画像生成 | [unconditional_image_generation](./using-diffusers/unconditional_image_generation) |
47
+ | Text-Guided Image Generation | 文章から画像生成 | [conditional_image_generation](./using-diffusers/conditional_image_generation) |
48
+ | Text-Guided Image-to-Image Translation | 画像と文章から新たな画像生成 | [img2img](./using-diffusers/img2img) |
49
+ | Text-Guided Image-Inpainting | 画像、マスク、および文章が指定された場合に、画像のマスクされた部分を文章をもとに修復 | [inpaint](./using-diffusers/inpaint) |
50
+ | Text-Guided Depth-to-Image Translation | 文章と深度推定によって構造を保持しながら画像生成 | [depth2img](./using-diffusers/depth2img) |
51
+
52
+ まず、[`DiffusionPipeline`]のインスタンスを作成���、ダウンロードしたいパイプラインのチェックポイントを指定します。
53
+ この[`DiffusionPipeline`]はHugging Face Hubに保存されている任意の[チェックポイント](https://huggingface.co/models?library=diffusers&sort=downloads)を使用することができます。
54
+ この案内では、[`stable-diffusion-v1-5`](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5)チェックポイントでテキストから画像へ生成します。
55
+
56
+ > [!WARNING]
57
+ > [Stable Diffusion]モデルについては、モデルを実行する前にまず[ライセンス](https://huggingface.co/spaces/CompVis/stable-diffusion-license)を注意深くお読みください。🧨 Diffusers は、攻撃的または有害なコンテンツを防ぐために [`safety_checker`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/safety_checker.py) を実装していますが、モデルの改良された画像生成機能により、潜在的に有害なコンテンツが生成される可能性があります。
58
+
59
+ モデルを[`~DiffusionPipeline.from_pretrained`]メソッドでロードします:
60
+
61
+ ```python
62
+ >>> from diffusers import DiffusionPipeline
63
+
64
+ >>> pipeline = DiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", use_safetensors=True)
65
+ ```
66
+ [`DiffusionPipeline`]は全てのモデリング、トークン化、スケジューリングコンポーネントをダウンロードしてキャッシュします。Stable Diffusionパイプラインは[`UNet2DConditionModel`]と[`PNDMScheduler`]などで構成されています:
67
+
68
+ ```py
69
+ >>> pipeline
70
+ StableDiffusionPipeline {
71
+ "_class_name": "StableDiffusionPipeline",
72
+ "_diffusers_version": "0.13.1",
73
+ ...,
74
+ "scheduler": [
75
+ "diffusers",
76
+ "PNDMScheduler"
77
+ ],
78
+ ...,
79
+ "unet": [
80
+ "diffusers",
81
+ "UNet2DConditionModel"
82
+ ],
83
+ "vae": [
84
+ "diffusers",
85
+ "AutoencoderKL"
86
+ ]
87
+ }
88
+ ```
89
+
90
+ このモデルはおよそ14億個のパラメータで構成されているため、GPU上でパイプラインを実行することを強く推奨します。
91
+ PyTorchと同じように、ジェネレータオブジェクトをGPUに移すことができます:
92
+
93
+ ```python
94
+ >>> pipeline.to("cuda")
95
+ ```
96
+
97
+ これで、文章を `pipeline` に渡して画像を生成し、ノイズ除去された画像にアクセスできるようになりました。デフォルトでは、画像出力は[`PIL.Image`](https://pillow.readthedocs.io/en/stable/reference/Image.html?highlight=image#the-image-class)オブジェクトでラップされます。
98
+
99
+ ```python
100
+ >>> image = pipeline("An image of a squirrel in Picasso style").images[0]
101
+ >>> image
102
+ ```
103
+
104
+ <div class="flex justify-center">
105
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/image_of_squirrel_painting.png"/>
106
+ </div>
107
+
108
+ `save`関数で画像を保存できます:
109
+
110
+ ```python
111
+ >>> image.save("image_of_squirrel_painting.png")
112
+ ```
113
+
114
+ ### ローカルパイプライン
115
+
116
+ ローカルでパイプラインを使用することもできます。唯一の違いは、最初にウェイトをダウンロードする必要があることです:
117
+
118
+ ```bash
119
+ !git lfs install
120
+ !git clone https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5
121
+ ```
122
+
123
+ 保存したウェイトをパイプラインにロードします:
124
+
125
+ ```python
126
+ >>> pipeline = DiffusionPipeline.from_pretrained("./stable-diffusion-v1-5", use_safetensors=True)
127
+ ```
128
+
129
+ これで、上のセクションと同じようにパイプラインを動かすことができます。
130
+
131
+ ### スケジューラの交換
132
+
133
+ スケジューラーによって、ノイズ除去のスピードや品質のトレードオフが異なります。どれが自分に最適かを知る最善の方法は、実際に試してみることです!Diffusers 🧨の主な機能の1つは、スケジューラを簡単に切り替えることができることです。例えば、デフォルトの[`PNDMScheduler`]を[`EulerDiscreteScheduler`]に置き換えるには、[`~diffusers.ConfigMixin.from_config`]メソッドでロードできます:
134
+
135
+ ```py
136
+ >>> from diffusers import EulerDiscreteScheduler
137
+
138
+ >>> pipeline = DiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", use_safetensors=True)
139
+ >>> pipeline.scheduler = EulerDiscreteScheduler.from_config(pipeline.scheduler.config)
140
+ ```
141
+
142
+ 新しいスケジューラを使って画像を生成し、その違いに気づくかどうか試してみてください!
143
+
144
+ 次のセクションでは、[`DiffusionPipeline`]を構成するコンポーネント(モデルとスケジューラ)を詳しく見て、これらのコンポーネントを使って猫の画像を生成する方法を学びます。
145
+
146
+ ## モデル
147
+
148
+ ほとんどのモデルはノイズの多いサンプルを取り、各タイムステップで*残りのノイズ*を予測します(他のモデルは前のサンプルを直接予測するか、速度または[`v-prediction`](https://github.com/huggingface/diffusers/blob/5e5ce13e2f89ac45a0066cb3f369462a3cf1d9ef/src/diffusers/schedulers/scheduling_ddim.py#L110)を予測するように学習します)。モデルを混ぜて他の拡散システムを作ることもできます。
149
+
150
+ モデルは[`~ModelMixin.from_pretrained`]メソッドで開始されます。このメソッドはモデルをローカルにキャッシュするので、次にモデルをロードするときに高速になります。この案内では、[`UNet2DModel`]をロードします。これは基本的な画像生成モデルであり、猫画像で学習されたチェックポイントを使います:
151
+
152
+ ```py
153
+ >>> from diffusers import UNet2DModel
154
+
155
+ >>> repo_id = "google/ddpm-cat-256"
156
+ >>> model = UNet2DModel.from_pretrained(repo_id, use_safetensors=True)
157
+ ```
158
+
159
+ モデルのパラメータにアクセスするには、`model.config` を呼び出せます:
160
+
161
+ ```py
162
+ >>> model.config
163
+ ```
164
+
165
+ モデル構成は🧊凍結🧊されたディクショナリであり、モデル作成後にこれらのパラメー タを変更することはできません。これは意図的なもので、最初にモデル・アーキテクチャを定義するために使用されるパラメータが同じままであることを保証します。他のパラメータは生成中に調整することができます。
166
+
167
+ 最も重要なパラメータは以下の通りです:
168
+
169
+ * sample_size`: 入力サンプルの高さと幅。
170
+ * `in_channels`: 入力サンプルの入力チャンネル数。
171
+ * down_block_types` と `up_block_types`: UNet アーキテクチャを作成するために使用されるダウンサンプリングブロックとアップサンプリングブロックのタイプ。
172
+ * block_out_channels`: ダウンサンプリングブロックの出力チャンネル数。逆順でアップサンプリングブロックの入力チャンネル数にも使用されます。
173
+ * layer_per_block`: 各 UNet ブロックに含まれる ResNet ブロックの数。
174
+
175
+ このモデルを生成に使用するには、ランダムな画像の形の正規分布を作成します。このモデルは複数のランダムな正規分布を受け取ることができるため`batch`軸を入れます。入力チャンネル数に対応する`channel`軸も必要です。画像の高さと幅に対応する`sample_size`軸を持つ必要があります:
176
+
177
+ ```py
178
+ >>> import torch
179
+
180
+ >>> torch.manual_seed(0)
181
+
182
+ >>> noisy_sample = torch.randn(1, model.config.in_channels, model.config.sample_size, model.config.sample_size)
183
+ >>> noisy_sample.shape
184
+ torch.Size([1, 3, 256, 256])
185
+ ```
186
+
187
+ 画像生成には、ノイズの多い画像と `timestep` をモデルに渡します。`timestep`は入力画像がどの程度ノイズが多いかを示します。これは、モデルが拡散プロセスにおける自分の位置を決定するのに役立ちます。モデルの出力を得るには `sample` メソッドを使用します:
188
+
189
+ ```py
190
+ >>> with torch.no_grad():
191
+ ... noisy_residual = model(sample=noisy_sample, timestep=2).sample
192
+ ```
193
+
194
+ しかし、実際の例を生成するには、ノイズ除去プロセスをガイドするスケジューラが必要です。次のセクションでは、モデルをスケジューラと組み合わせる方法を学びます。
195
+
196
+ ## スケジューラ
197
+
198
+ スケジューラは、モデルの出力(この場合は `noisy_residual` )が与えられたときに、ノイズの多いサンプルからノイズの少ないサンプルへの移行を管理します。
199
+
200
+
201
+ > [!TIP]
202
+ > 🧨 Diffusersは拡散システムを構築するためのツールボックスです。[`DiffusionPipeline`]は事前に構築された拡散システムを使い始めるのに便利な方法ですが、独自のモデルとスケジューラコンポーネントを個別に選択してカスタム拡散システムを構築することもできます。
203
+
204
+ この案内では、[`DDPMScheduler`]を[`~diffusers.ConfigMixin.from_config`]メソッドでインスタンス化します:
205
+
206
+ ```py
207
+ >>> from diffusers import DDPMScheduler
208
+
209
+ >>> scheduler = DDPMScheduler.from_config(repo_id)
210
+ >>> scheduler
211
+ DDPMScheduler {
212
+ "_class_name": "DDPMScheduler",
213
+ "_diffusers_version": "0.13.1",
214
+ "beta_end": 0.02,
215
+ "beta_schedule": "linear",
216
+ "beta_start": 0.0001,
217
+ "clip_sample": true,
218
+ "clip_sample_range": 1.0,
219
+ "num_train_timesteps": 1000,
220
+ "prediction_type": "epsilon",
221
+ "trained_betas": null,
222
+ "variance_type": "fixed_small"
223
+ }
224
+ ```
225
+
226
+ > [!TIP]
227
+ > 💡 スケジューラがどのようにコンフィギュレーションからインスタンス化されるかに注目してください。モデルとは異なり、スケジューラは学習可能な重みを持たず、パラメーターを持ちません!
228
+
229
+ 最も重要なパラメータは以下の通りです:
230
+
231
+ * num_train_timesteps`: ノイズ除去処理の長さ、言い換えれば、ランダムな正規分布をデータサンプルに処理するのに必要なタイムステップ数です。
232
+ * `beta_schedule`: 生成とトレーニングに使用するノイズスケジュールのタイプ。
233
+ * `beta_start` と `beta_end`: ノイズスケジュールの開始値と終了値。
234
+
235
+ 少しノイズの少ない画像を予測するには、スケジューラの [`~diffusers.DDPMScheduler.step`] メソッドに以下を渡します: モデルの出力、`timestep`、現在の `sample`。
236
+
237
+ ```py
238
+ >>> less_noisy_sample = scheduler.step(model_output=noisy_residual, timestep=2, sample=noisy_sample).prev_sample
239
+ >>> less_noisy_sample.shape
240
+ ```
241
+
242
+ `less_noisy_sample`は次の`timestep`に渡すことができ、そこでさらにノイズが少なくなります!
243
+
244
+ では、すべてをまとめて、ノイズ除去プロセス全体を視覚化してみましょう。
245
+
246
+ まず、ノイズ除去された画像を後処理して `PIL.Image` として表示する関数を作成します:
247
+
248
+ ```py
249
+ >>> import PIL.Image
250
+ >>> import numpy as np
251
+
252
+
253
+ >>> def display_sample(sample, i):
254
+ ... image_processed = sample.cpu().permute(0, 2, 3, 1)
255
+ ... image_processed = (image_processed + 1.0) * 127.5
256
+ ... image_processed = image_processed.numpy().astype(np.uint8)
257
+
258
+ ... image_pil = PIL.Image.fromarray(image_processed[0])
259
+ ... display(f"Image at step {i}")
260
+ ... display(image_pil)
261
+ ```
262
+
263
+ ノイズ除去処理を高速化するために入力とモデルをGPUに移します:
264
+
265
+ ```py
266
+ >>> model.to("cuda")
267
+ >>> noisy_sample = noisy_sample.to("cuda")
268
+ ```
269
+
270
+ ここで、ノイズが少なくなったサンプルの残りのノイズを予測するノイズ除去ループを作成し、スケジューラを使ってさらにノイズの少ないサンプルを計算します:
271
+
272
+ ```py
273
+ >>> import tqdm
274
+
275
+ >>> sample = noisy_sample
276
+
277
+ >>> for i, t in enumerate(tqdm.tqdm(scheduler.timesteps)):
278
+ ... # 1. predict noise residual
279
+ ... with torch.no_grad():
280
+ ... residual = model(sample, t).sample
281
+
282
+ ... # 2. compute less noisy image and set x_t -> x_t-1
283
+ ... sample = scheduler.step(residual, t, sample).prev_sample
284
+
285
+ ... # 3. optionally look at image
286
+ ... if (i + 1) % 50 == 0:
287
+ ... display_sample(sample, i + 1)
288
+ ```
289
+
290
+ 何もないところから猫が生成されるのを、座って見てください!😻
291
+
292
+ <div class="flex justify-center">
293
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/diffusion-quicktour.png"/>
294
+ </div>
295
+
296
+ ## 次のステップ
297
+
298
+ このクイックツアーで、🧨ディフューザーを使ったクールな画像をいくつか作成できたと思います!次のステップとして
299
+
300
+ * モデルをトレーニングまたは微調整については、[training](./tutorials/basic_training)チュートリアルを参照してください。
301
+ * 様々な使用例については、公式およびコミュニティの[training or finetuning scripts](https://github.com/huggingface/diffusers/tree/main/examples#-diffusers-examples)の例を参照してください。
302
+ * スケジューラのロード、アクセス、変更、比較については[Using different Schedulers](./using-diffusers/schedulers)ガイドを参照してください。
303
+ * プロンプトエンジニアリング、スピードとメモリの最適化、より高品質な画像を生成するためのヒントやトリックについては、[Stable Diffusion](./stable_diffusion)ガイドを参照してください。
304
+ * 🧨 Diffusers の高速化については、最適化された [PyTorch on a GPU](./optimization/fp16)のガイド、[Stable Diffusion on Apple Silicon (M1/M2)](./optimization/mps)と[ONNX Runtime](./optimization/onnx)を参照してください。
tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/ja/stable_diffusion.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
+ # 効果的で効率的な拡散モデル
14
+
15
+ [[open-in-colab]]
16
+
17
+ [`DiffusionPipeline`]を使って特定のスタイルで画像を生成したり、希望する画像を生成したりするのは難しいことです。多くの場合、[`DiffusionPipeline`]を何度か実行してからでないと満足のいく画像は得られません。しかし、何もないところから何かを生成するにはたくさんの計算が必要です。生成を何度も何度も実行する場合、特にたくさんの計算量が必要になります。
18
+
19
+ そのため、パイプラインから*計算*(速度)と*メモリ*(GPU RAM)の効率を最大限に引き出し、生成サイクル間の時間を短縮することで、より高速な反復処理を行えるようにすることが重要です。
20
+
21
+ このチュートリアルでは、[`DiffusionPipeline`]を用いて、より速く、より良い計算を行う方法を説明します。
22
+
23
+ まず、[`stable-diffusion-v1-5/stable-diffusion-v1-5`](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5)モデルをロードします:
24
+
25
+ ```python
26
+ from diffusers import DiffusionPipeline
27
+
28
+ model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
29
+ pipeline = DiffusionPipeline.from_pretrained(model_id, use_safetensors=True)
30
+ ```
31
+
32
+ ここで使用するプロンプトの例は年老いた戦士の長の肖像画ですが、ご自由に変更してください:
33
+
34
+ ```python
35
+ prompt = "portrait photo of a old warrior chief"
36
+ ```
37
+
38
+ ## Speed
39
+
40
+ > [!TIP]
41
+ > 💡 GPUを利用できない場合は、[Colab](https://colab.research.google.com/)のようなGPUプロバイダーから無料で利用できます!
42
+
43
+ 画像生成を高速化する最も簡単な方法の1つは、PyTorchモジュールと同じようにGPU上にパイプラインを配置することです:
44
+
45
+ ```python
46
+ pipeline = pipeline.to("cuda")
47
+ ```
48
+
49
+ 同じイメージを使って改良できるようにするには、[`Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html)を使い、[reproducibility](./using-diffusers/reusing_seeds)の種を設定します:
50
+
51
+ ```python
52
+ import torch
53
+
54
+ generator = torch.Generator("cuda").manual_seed(0)
55
+ ```
56
+
57
+ これで画像を生成できます:
58
+
59
+ ```python
60
+ image = pipeline(prompt, generator=generator).images[0]
61
+ image
62
+ ```
63
+
64
+ <div class="flex justify-center">
65
+ <img src="https://huggingface.co/datasets/diffusers/docs-images/resolve/main/stable_diffusion_101/sd_101_1.png">
66
+ </div>
67
+
68
+ この処理にはT4 GPUで~30秒かかりました(割り当てられているGPUがT4より優れている場合はもっと速いかもしれません)。デフォルトでは、[`DiffusionPipeline`]は完全な`float32`精度で生成を50ステップ実行します。float16`のような低い精度に変更するか、推論ステップ数を減らすことで高速化することができます。
69
+
70
+ まずは `float16` でモデルをロードして画像を生成してみましょう:
71
+
72
+ ```python
73
+ import torch
74
+
75
+ pipeline = DiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16, use_safetensors=True)
76
+ pipeline = pipeline.to("cuda")
77
+ generator = torch.Generator("cuda").manual_seed(0)
78
+ image = pipeline(prompt, generator=generator).images[0]
79
+ image
80
+ ```
81
+
82
+ <div class="flex justify-center">
83
+ <img src="https://huggingface.co/datasets/diffusers/docs-images/resolve/main/stable_diffusion_101/sd_101_2.png">
84
+ </div>
85
+
86
+ 今回、画像生成にかかった時間はわずか11秒で、以前より3倍近く速くなりました!
87
+
88
+ > [!TIP]
89
+ > 💡 パイプラインは常に `float16` で実行することを強くお勧めします。
90
+
91
+ 生成ステップ数を減らすという方法もあります。より効率的なスケジューラを選択することで、出力品質を犠牲にすることなくステップ数を減らすことができます。`compatibles`メソッドを呼び出すことで、[`DiffusionPipeline`]の現在のモデルと互換性のあるスケジューラを見つけることができます:
92
+
93
+ ```python
94
+ pipeline.scheduler.compatibles
95
+ [
96
+ diffusers.schedulers.scheduling_lms_discrete.LMSDiscreteScheduler,
97
+ diffusers.schedulers.scheduling_unipc_multistep.UniPCMultistepScheduler,
98
+ diffusers.schedulers.scheduling_k_dpm_2_discrete.KDPM2DiscreteScheduler,
99
+ diffusers.schedulers.scheduling_deis_multistep.DEISMultistepScheduler,
100
+ diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler,
101
+ diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler,
102
+ diffusers.schedulers.scheduling_ddpm.DDPMScheduler,
103
+ diffusers.schedulers.scheduling_dpmsolver_singlestep.DPMSolverSinglestepScheduler,
104
+ diffusers.schedulers.scheduling_k_dpm_2_ancestral_discrete.KDPM2AncestralDiscreteScheduler,
105
+ diffusers.schedulers.scheduling_heun_discrete.HeunDiscreteScheduler,
106
+ diffusers.schedulers.scheduling_pndm.PNDMScheduler,
107
+ diffusers.schedulers.scheduling_euler_ancestral_discrete.EulerAncestralDiscreteScheduler,
108
+ diffusers.schedulers.scheduling_ddim.DDIMScheduler,
109
+ ]
110
+ ```
111
+
112
+ Stable Diffusionモデルはデフォルトで[`PNDMScheduler`]を使用します。このスケジューラは通常~50の推論ステップを必要としますが、[`DPMSolverMultistepScheduler`]のような高性能なスケジューラでは~20または25の推論ステップで済みます。[`ConfigMixin.from_config`]メソッドを使用すると、新しいスケジューラをロードすることができます:
113
+
114
+ ```python
115
+ from diffusers import DPMSolverMultistepScheduler
116
+
117
+ pipeline.scheduler = DPMSolverMultistepScheduler.from_config(pipeline.scheduler.config)
118
+ ```
119
+
120
+ ここで `num_inference_steps` を20に設定します:
121
+
122
+ ```python
123
+ generator = torch.Generator("cuda").manual_seed(0)
124
+ image = pipeline(prompt, generator=generator, num_inference_steps=20).images[0]
125
+ image
126
+ ```
127
+
128
+ <div class="flex justify-center">
129
+ <img src="https://huggingface.co/datasets/diffusers/docs-images/resolve/main/stable_diffusion_101/sd_101_3.png">
130
+ </div>
131
+
132
+ 推論時間をわずか4秒に短縮することに成功した!⚡️
133
+
134
+ ## メモリー
135
+
136
+ パイプラインのパフォーマンスを向上させるもう1つの鍵は、消費メモリを少なくすることです。一度に生成できる画像の数を確認する最も簡単な方法は、`OutOfMemoryError`(OOM)が発生するまで、さまざまなバッチサイズを試してみることです。
137
+
138
+ 文章と `Generators` のリストから画像のバッチを生成する関数を作成します。各 `Generator` にシードを割り当てて、良い結果が得られた場合に再利用できるようにします。
139
+
140
+ ```python
141
+ def get_inputs(batch_size=1):
142
+ generator = [torch.Generator("cuda").manual_seed(i) for i in range(batch_size)]
143
+ prompts = batch_size * [prompt]
144
+ num_inference_steps = 20
145
+
146
+ return {"prompt": prompts, "generator": generator, "num_inference_steps": num_inference_steps}
147
+ ```
148
+
149
+ `batch_size=4`で開始し、どれだけメモリを消費したかを確認します:
150
+
151
+ ```python
152
+ from diffusers.utils import make_image_grid
153
+
154
+ images = pipeline(**get_inputs(batch_size=4)).images
155
+ make_image_grid(images, 2, 2)
156
+ ```
157
+
158
+ 大容量のRAMを搭載したGPUでない限り、上記のコードはおそらく`OOM`エラーを返したはずです!メモリの大半はクロスアテンションレイヤーが占めています。この処理をバッチで実行する代わりに、逐次実行することでメモリを大幅に節約できます。必要なのは、[`~DiffusionPipeline.enable_attention_slicing`]関数を使用することだけです:
159
+
160
+ ```python
161
+ pipeline.enable_attention_slicing()
162
+ ```
163
+
164
+ 今度は`batch_size`を8にしてみてください!
165
+
166
+ ```python
167
+ images = pipeline(**get_inputs(batch_size=8)).images
168
+ make_image_grid(images, rows=2, cols=4)
169
+ ```
170
+
171
+ <div class="flex justify-center">
172
+ <img src="https://huggingface.co/datasets/diffusers/docs-images/resolve/main/stable_diffusion_101/sd_101_5.png">
173
+ </div>
174
+
175
+ 以前は4枚の画像のバッチを生成することさえできませんでしたが、今では8枚の画像のバッチを1枚あたり~3.5秒で生成できます!これはおそらく、品質を犠牲にすることなくT4 GPUでできる最速の処理速度です。
176
+
177
+ ## 品質
178
+
179
+ 前の2つのセクションでは、`fp16` を使ってパイプラインの速度を最適化する方法、よりパフォーマン スなスケジューラーを使って生成ステップ数を減らす方法、アテンションスライスを有効 にしてメモリ消費量を減らす方法について学びました。今度は、生成される画像の品質を向上させる方法に焦点を当てます。
180
+
181
+ ### より良いチェックポイント
182
+
183
+ 最も単純なステップは、より良いチェックポイントを使うことです。Stable Diffusionモデルは良い出発点であり、公式発表以来、いくつかの改良版もリリースされています。しかし、新しいバージョンを使ったからといって、自動的に良い結果が得られるわけではありません。最良の結果を得るためには、自分でさまざまなチェックポイントを試してみたり、ちょっとした研究([ネガティブプロンプト](https://minimaxir.com/2022/11/stable-diffusion-negative-prompt/)の使用など)をしたりする必要があります。
184
+
185
+ こ��分野が成長するにつれて、特定のスタイルを生み出すために微調整された、より質の高いチェックポイントが増えています。[Hub](https://huggingface.co/models?library=diffusers&sort=downloads)や[Diffusers Gallery](https://huggingface.co/spaces/huggingface-projects/diffusers-gallery)を探索して、興味のあるものを見つけてみてください!
186
+
187
+ ### より良いパイプラインコンポーネント
188
+
189
+ 現在のパイプラインコンポーネントを新しいバージョンに置き換えてみることもできます。Stability AIが提供する最新の[autodecoder](https://huggingface.co/stabilityai/stable-diffusion-2-1/tree/main/vae)をパイプラインにロードし、画像を生成してみましょう:
190
+
191
+ ```python
192
+ from diffusers import AutoencoderKL
193
+
194
+ vae = AutoencoderKL.from_pretrained("stabilityai/sd-vae-ft-mse", torch_dtype=torch.float16).to("cuda")
195
+ pipeline.vae = vae
196
+ images = pipeline(**get_inputs(batch_size=8)).images
197
+ make_image_grid(images, rows=2, cols=4)
198
+ ```
199
+
200
+ <div class="flex justify-center">
201
+ <img src="https://huggingface.co/datasets/diffusers/docs-images/resolve/main/stable_diffusion_101/sd_101_6.png">
202
+ </div>
203
+
204
+ ### より良いプロンプト・エンジニアリング
205
+
206
+ 画像を生成するために使用する文章は、*プロンプトエンジニアリング*と呼ばれる分野を作られるほど、非常に重要です。プロンプト・エンジニアリングで考慮すべき点は以下の通りです:
207
+
208
+ - 生成したい画像やその類似画像は、インターネット上にどのように保存されているか?
209
+ - 私が望むスタイルにモデルを誘導するために、どのような追加詳細を与えるべきか?
210
+
211
+ このことを念頭に置いて、プロンプトに色やより質の高いディテールを含めるように改良してみましょう:
212
+
213
+ ```python
214
+ prompt += ", tribal panther make up, blue on red, side profile, looking away, serious eyes"
215
+ prompt += " 50mm portrait photography, hard rim lighting photography--beta --ar 2:3 --beta --upbeta"
216
+ ```
217
+
218
+ 新しいプロンプトで画像のバッチを生成しましょう:
219
+
220
+ ```python
221
+ images = pipeline(**get_inputs(batch_size=8)).images
222
+ make_image_grid(images, rows=2, cols=4)
223
+ ```
224
+
225
+ <div class="flex justify-center">
226
+ <img src="https://huggingface.co/datasets/diffusers/docs-images/resolve/main/stable_diffusion_101/sd_101_7.png">
227
+ </div>
228
+
229
+ かなりいいです!種が`1`の`Generator`に対応する2番目の画像に、被写体の年齢に関するテキストを追加して、もう少し手を加えてみましょう:
230
+
231
+ ```python
232
+ prompts = [
233
+ "portrait photo of the oldest warrior chief, tribal panther make up, blue on red, side profile, looking away, serious eyes 50mm portrait photography, hard rim lighting photography--beta --ar 2:3 --beta --upbeta",
234
+ "portrait photo of a old warrior chief, tribal panther make up, blue on red, side profile, looking away, serious eyes 50mm portrait photography, hard rim lighting photography--beta --ar 2:3 --beta --upbeta",
235
+ "portrait photo of a warrior chief, tribal panther make up, blue on red, side profile, looking away, serious eyes 50mm portrait photography, hard rim lighting photography--beta --ar 2:3 --beta --upbeta",
236
+ "portrait photo of a young warrior chief, tribal panther make up, blue on red, side profile, looking away, serious eyes 50mm portrait photography, hard rim lighting photography--beta --ar 2:3 --beta --upbeta",
237
+ ]
238
+
239
+ generator = [torch.Generator("cuda").manual_seed(1) for _ in range(len(prompts))]
240
+ images = pipeline(prompt=prompts, generator=generator, num_inference_steps=25).images
241
+ make_image_grid(images, 2, 2)
242
+ ```
243
+
244
+ <div class="flex justify-center">
245
+ <img src="https://huggingface.co/datasets/diffusers/docs-images/resolve/main/stable_diffusion_101/sd_101_8.png">
246
+ </div>
247
+
248
+ ## 次のステップ
249
+
250
+ このチュートリアルでは、[`DiffusionPipeline`]を最適化して計算効率とメモリ効率を向上させ、生成される出力の品質を向上させる方法を学びました。パイプラインをさらに高速化することに興味があれば、以下のリソースを参照してください:
251
+
252
+ - [PyTorch 2.0](./optimization/torch2.0)と[`torch.compile`](https://pytorch.org/docs/stable/generated/torch.compile.html)がどのように生成速度を5-300%高速化できるかを学んでください。A100 GPUの場合、画像生成は最大50%速くなります!
253
+ - PyTorch 2が使えない場合は、[xFormers](./optimization/xformers)をインストールすることをお勧めします。このライブラリのメモリ効率の良いアテンションメカニズムは PyTorch 1.13.1 と相性が良く、高速化とメモリ消費量の削減を同時に実現します。
254
+ - モデルのオフロードなど、その他の最適化テクニックは [this guide](./optimization/fp16) でカバーされています。
tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/ja/tutorials/autopipeline.md ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ Diffusersは様々なタスクをこなすことができ、テキストから画像、画像から画像、画像の修復など、複数のタスクに対して同じように事前学習された重みを再利用することができます。しかし、ライブラリや拡散モデルに慣れていない場合、どのタスクにどのパイプラインを使えばいいのかがわかりにくいかもしれません。例えば、 [stable-diffusion-v1-5/stable-diffusion-v1-5](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5) チェックポイントをテキストから画像に変換するために使用している場合、それぞれ[`StableDiffusionImg2ImgPipeline`]クラスと[`StableDiffusionInpaintPipeline`]クラスでチェックポイントをロードすることで、画像から画像や画像の修復にも使えることを知らない可能性もあります。
16
+
17
+ `AutoPipeline` クラスは、🤗 Diffusers の様々なパイプラインをよりシンプルするために設計されています。この汎用的でタスク重視のパイプラインによってタスクそのものに集中することができます。`AutoPipeline` は、使用するべき正しいパイプラインクラスを自動的に検出するため、特定のパイプラインクラス名を知らなくても、タスクのチェックポイントを簡単にロードできます。
18
+
19
+ > [!TIP]
20
+ > どのタスクがサポートされているかは、[AutoPipeline](../api/pipelines/auto_pipeline) のリファレンスをご覧ください。現在、text-to-image、image-to-image、inpaintingをサポートしています。
21
+
22
+ このチュートリアルでは、`AutoPipeline` を使用して、事前に学習された重みが与えられたときに、特定のタスクを読み込むためのパイプラインクラスを自動的に推測する方法を示します。
23
+
24
+ ## タスクに合わせてAutoPipeline を選択する
25
+ まずはチェックポイントを選ぶことから始めましょう。例えば、 [stable-diffusion-v1-5/stable-diffusion-v1-5](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5) チェックポイントでテキストから画像への変換したいなら、[`AutoPipelineForText2Image`]を使います:
26
+
27
+ ```py
28
+ from diffusers import AutoPipelineForText2Image
29
+ import torch
30
+
31
+ pipeline = AutoPipelineForText2Image.from_pretrained(
32
+ "stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16, use_safetensors=True
33
+ ).to("cuda")
34
+ prompt = "peasant and dragon combat, wood cutting style, viking era, bevel with rune"
35
+
36
+ image = pipeline(prompt, num_inference_steps=25).images[0]
37
+ image
38
+ ```
39
+
40
+ <div class="flex justify-center">
41
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/autopipeline-text2img.png" alt="generated image of peasant fighting dragon in wood cutting style"/>
42
+ </div>
43
+
44
+ [`AutoPipelineForText2Image`] を具体的に見ていきましょう:
45
+
46
+ 1. [`model_index.json`](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5/blob/main/model_index.json) ファイルから `"stable-diffusion"` クラスを自動的に検出します。
47
+ 2. `"stable-diffusion"` のクラス名に基づいて、テキストから画像へ変換する [`StableDiffusionPipeline`] を読み込みます。
48
+
49
+ 同様に、画像から画像へ変換する場合、[`AutoPipelineForImage2Image`] は `model_index.json` ファイルから `"stable-diffusion"` チェックポイントを検出し、対応する [`StableDiffusionImg2ImgPipeline`] を読み込みます。また、入力画像にノイズの量やバリエーションの追加を決めるための強さなど、パイプラインクラスに固有の追加引数を渡すこともできます:
50
+
51
+ ```py
52
+ from diffusers import AutoPipelineForImage2Image
53
+ import torch
54
+ import requests
55
+ from PIL import Image
56
+ from io import BytesIO
57
+
58
+ pipeline = AutoPipelineForImage2Image.from_pretrained(
59
+ "stable-diffusion-v1-5/stable-diffusion-v1-5",
60
+ torch_dtype=torch.float16,
61
+ use_safetensors=True,
62
+ ).to("cuda")
63
+ prompt = "a portrait of a dog wearing a pearl earring"
64
+
65
+ url = "https://upload.wikimedia.org/wikipedia/commons/thumb/0/0f/1665_Girl_with_a_Pearl_Earring.jpg/800px-1665_Girl_with_a_Pearl_Earring.jpg"
66
+
67
+ response = requests.get(url)
68
+ image = Image.open(BytesIO(response.content)).convert("RGB")
69
+ image.thumbnail((768, 768))
70
+
71
+ image = pipeline(prompt, image, num_inference_steps=200, strength=0.75, guidance_scale=10.5).images[0]
72
+ image
73
+ ```
74
+
75
+ <div class="flex justify-center">
76
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/autopipeline-img2img.png" alt="generated image of a vermeer portrait of a dog wearing a pearl earring"/>
77
+ </div>
78
+
79
+ また、画像の修復を行いたい場合は、 [`AutoPipelineForInpainting`] が、同様にベースとなる[`StableDiffusionInpaintPipeline`]クラスを読み込みます:
80
+
81
+ ```py
82
+ from diffusers import AutoPipelineForInpainting
83
+ from diffusers.utils import load_image
84
+ import torch
85
+
86
+ pipeline = AutoPipelineForInpainting.from_pretrained(
87
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16, use_safetensors=True
88
+ ).to("cuda")
89
+
90
+ img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
91
+ mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
92
+
93
+ init_image = load_image(img_url).convert("RGB")
94
+ mask_image = load_image(mask_url).convert("RGB")
95
+
96
+ prompt = "A majestic tiger sitting on a bench"
97
+ image = pipeline(prompt, image=init_image, mask_image=mask_image, num_inference_steps=50, strength=0.80).images[0]
98
+ image
99
+ ```
100
+
101
+ <div class="flex justify-center">
102
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/autopipeline-inpaint.png" alt="generated image of a tiger sitting on a bench"/>
103
+ </div>
104
+
105
+ サポートされていないチェックポイントを読み込もうとすると、エラーになります:
106
+
107
+ ```py
108
+ from diffusers import AutoPipelineForImage2Image
109
+ import torch
110
+
111
+ pipeline = AutoPipelineForImage2Image.from_pretrained(
112
+ "openai/shap-e-img2img", torch_dtype=torch.float16, use_safetensors=True
113
+ )
114
+ "ValueError: AutoPipeline can't find a pipeline linked to ShapEImg2ImgPipeline for None"
115
+ ```
116
+
117
+ ## 複数のパイプラインを使用する
118
+
119
+ いくつかのワークフローや多くのパイプラインを読み込む場合、不要なメモリを使ってしまう再読み込みをするよりも、チェックポイントから同じコンポーネントを再利用する方がメモリ効率が良いです。たとえば、テキストから画像への変換にチェックポイントを使い、画像から画像への変換にまたチェックポイントを使いたい場合、[from_pipe()](https://huggingface.co/docs/diffusers/v0.25.1/en/api/pipelines/auto_pipeline#diffusers.AutoPipelineForImage2Image.from_pipe) メソッドを使用します。このメソッドは、以前読み込まれたパイプラインのコンポーネントを使うことで追加のメモリを消費することなく、新しいパイプラインを作成します。
120
+
121
+ [from_pipe()](https://huggingface.co/docs/diffusers/v0.25.1/en/api/pipelines/auto_pipeline#diffusers.AutoPipelineForImage2Image.from_pipe) メソッドは、元のパイプラインクラスを検出し、実行したいタスクに対応する新しいパイプラインクラスにマッピングします。例えば、テキストから画像への`"stable-diffusion"` クラスのパイプラインを読み込む場合:
122
+
123
+ ```py
124
+ from diffusers import AutoPipelineForText2Image, AutoPipelineForImage2Image
125
+ import torch
126
+
127
+ pipeline_text2img = AutoPipelineForText2Image.from_pretrained(
128
+ "stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16, use_safetensors=True
129
+ )
130
+ print(type(pipeline_text2img))
131
+ "<class 'diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline'>"
132
+ ```
133
+
134
+ そして、[from_pipe()] (https://huggingface.co/docs/diffusers/v0.25.1/en/api/pipelines/auto_pipeline#diffusers.AutoPipelineForImage2Image.from_pipe)は、もとの`"stable-diffusion"` パイプラインのクラスである [`StableDiffusionImg2ImgPipeline`] にマップします:
135
+
136
+ ```py
137
+ pipeline_img2img = AutoPipelineForImage2Image.from_pipe(pipeline_text2img)
138
+ print(type(pipeline_img2img))
139
+ "<class 'diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline'>"
140
+ ```
141
+ 元のパイプラインにオプションとして引数(セーフティチェッカーの無効化など)を渡した場合、この引数も新しいパイプラインに渡されます:
142
+
143
+ ```py
144
+ from diffusers import AutoPipelineForText2Image, AutoPipelineForImage2Image
145
+ import torch
146
+
147
+ pipeline_text2img = AutoPipelineForText2Image.from_pretrained(
148
+ "stable-diffusion-v1-5/stable-diffusion-v1-5",
149
+ torch_dtype=torch.float16,
150
+ use_safetensors=True,
151
+ requires_safety_checker=False,
152
+ ).to("cuda")
153
+
154
+ pipeline_img2img = AutoPipelineForImage2Image.from_pipe(pipeline_text2img)
155
+ print(pipeline_img2img.config.requires_safety_checker)
156
+ "False"
157
+ ```
158
+
159
+ 新しいパイプラインの動作を変更したい場合は、元のパイプラインの引数や設定を上書きすることが��きます。例えば、セーフティチェッカーをオンに戻し、`strength` 引数を追加します:
160
+
161
+ ```py
162
+ pipeline_img2img = AutoPipelineForImage2Image.from_pipe(pipeline_text2img, requires_safety_checker=True, strength=0.3)
163
+ print(pipeline_img2img.config.requires_safety_checker)
164
+ "True"
165
+ ```
tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/ja/tutorials/tutorial_overview.md ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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へ!拡散モデル(diffusion models)や生成AIの初心者で、さらに学びたいのであれば、このチュートリアルが最適です。この初心者向けのチュートリアルは、拡散モデルについて丁寧に解説し、ライブラリの基礎(核となるコンポーネントと 🧨Diffusersの使用方法)を理解することを目的としています。
16
+
17
+ まず、推論のためのパイプラインを使って、素早く生成する方法を学んでいきます。次に、独自の拡散システムを構築するためのモジュラーツールボックスとしてライブラリをどのように使えば良いかを理解するために、そのパイプラインを分解してみましょう。次のレッスンでは、あなたの欲しいものを生成できるように拡散モデルをトレーニングする方法を学びましょう。
18
+
19
+ このチュートリアルがすべて完了したら、ライブラリを自分で調べ、自分のプロジェクトやアプリケーションにどのように使えるかを知るために必要なスキルを身につけることができます。
20
+
21
+ そして、 [Discord](https://discord.com/invite/JfAtkvEtRb) や [forums](https://discuss.huggingface.co/c/discussion-related-to-httpsgithubcomhuggingfacediffusers/63) でDiffusersコミュニティに参加してユーザーや開発者と繋がって協力していきましょう。
22
+
23
+ さあ、「拡散」をはじめていきましょう!🧨
tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/ko/_toctree.yml ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - sections:
2
+ - local: index
3
+ title: 🧨 Diffusers
4
+ - local: quicktour
5
+ title: "훑어보기"
6
+ - local: stable_diffusion
7
+ title: Stable Diffusion
8
+ - local: installation
9
+ title: 설치
10
+ title: 시작하기
11
+ - sections:
12
+ - local: tutorials/tutorial_overview
13
+ title: 개요
14
+ - local: using-diffusers/write_own_pipeline
15
+ title: 모델과 스케줄러 이해하기
16
+ - local: in_translation # tutorials/autopipeline
17
+ title: (번역중) AutoPipeline
18
+ - local: tutorials/basic_training
19
+ title: Diffusion 모델 학습하기
20
+ - local: in_translation # tutorials/using_peft_for_inference
21
+ title: (번역중) 추론을 위한 LoRAs 불러오기
22
+ - local: in_translation # tutorials/fast_diffusion
23
+ title: (번역중) Text-to-image diffusion 모델 추론 가속화하기
24
+ - local: in_translation # tutorials/inference_with_big_models
25
+ title: (번역중) 큰 모델로 작업하기
26
+ title: 튜토리얼
27
+ - sections:
28
+ - local: using-diffusers/loading
29
+ title: 파이프라인 불러오기
30
+ - local: using-diffusers/custom_pipeline_overview
31
+ title: 커뮤니티 파이프라인과 컴포넌트 불러오기
32
+ - local: using-diffusers/schedulers
33
+ title: 스케줄러와 모델 불러오기
34
+ - local: using-diffusers/other-formats
35
+ title: 모델 파일과 레이아웃
36
+ - local: using-diffusers/loading_adapters
37
+ title: 어댑터 불러오기
38
+ - local: using-diffusers/push_to_hub
39
+ title: 파일들을 Hub로 푸시하기
40
+ title: 파이프라인과 어댑터 불러오기
41
+ - sections:
42
+ - local: using-diffusers/unconditional_image_generation
43
+ title: Unconditional 이미지 생성
44
+ - local: using-diffusers/conditional_image_generation
45
+ title: Text-to-image
46
+ - local: using-diffusers/img2img
47
+ title: Image-to-image
48
+ - local: using-diffusers/inpaint
49
+ title: 인페인팅
50
+ - local: in_translation # using-diffusers/text-img2vid
51
+ title: (번역중) Text 또는 image-to-video
52
+ - local: using-diffusers/depth2img
53
+ title: Depth-to-image
54
+ title: 생성 태스크
55
+ - sections:
56
+ - local: in_translation # using-diffusers/overview_techniques
57
+ title: (번역중) 개요
58
+ - local: training/distributed_inference
59
+ title: 여러 GPU를 사용한 분산 추론
60
+ - local: in_translation # using-diffusers/merge_loras
61
+ title: (번역중) LoRA 병합
62
+ - local: in_translation # using-diffusers/scheduler_features
63
+ title: (번역중) 스케줄러 기능
64
+ - local: in_translation # using-diffusers/callback
65
+ title: (번역중) 파이프라인 콜백
66
+ - local: in_translation # using-diffusers/reusing_seeds
67
+ title: (번역중) 재현 가능한 파이프라인
68
+ - local: in_translation # using-diffusers/image_quality
69
+ title: (번역중) 이미지 퀄리티 조절하기
70
+ - local: using-diffusers/weighted_prompts
71
+ title: 프롬프트 기술
72
+ title: 추론 테크닉
73
+ - sections:
74
+ - local: in_translation # advanced_inference/outpaint
75
+ title: (번역중) Outpainting
76
+ title: 추론 심화
77
+ - sections:
78
+ - local: in_translation # using-diffusers/sdxl
79
+ title: (번역중) Stable Diffusion XL
80
+ - local: using-diffusers/sdxl_turbo
81
+ title: SDXL Turbo
82
+ - local: using-diffusers/kandinsky
83
+ title: Kandinsky
84
+ - local: in_translation # using-diffusers/ip_adapter
85
+ title: (번역중) IP-Adapter
86
+ - local: in_translation # using-diffusers/pag
87
+ title: (번역중) PAG
88
+ - local: in_translation # using-diffusers/controlnet
89
+ title: (번역중) ControlNet
90
+ - local: in_translation # using-diffusers/t2i_adapter
91
+ title: (번역중) T2I-Adapter
92
+ - local: in_translation # using-diffusers/inference_with_lcm
93
+ title: (번역중) Latent Consistency Model
94
+ - local: using-diffusers/textual_inversion_inference
95
+ title: Textual inversion
96
+ - local: using-diffusers/shap-e
97
+ title: Shap-E
98
+ - local: using-diffusers/diffedit
99
+ title: DiffEdit
100
+ - local: in_translation # using-diffusers/inference_with_tcd_lora
101
+ title: (번역중) Trajectory Consistency Distillation-LoRA
102
+ - local: using-diffusers/svd
103
+ title: Stable Video Diffusion
104
+ - local: in_translation # using-diffusers/marigold_usage
105
+ title: (번역중) Marigold 컴퓨터 비전
106
+ title: 특정 파이프라인 예시
107
+ - sections:
108
+ - local: training/overview
109
+ title: 개요
110
+ - local: training/create_dataset
111
+ title: 학습을 위한 데이터셋 생성하기
112
+ - local: training/adapt_a_model
113
+ title: 새로운 태스크에 모델 적용하기
114
+ - isExpanded: false
115
+ sections:
116
+ - local: training/unconditional_training
117
+ title: Unconditional 이미지 생성
118
+ - local: training/text2image
119
+ title: Text-to-image
120
+ - local: in_translation # training/sdxl
121
+ title: (번역중) Stable Diffusion XL
122
+ - local: in_translation # training/kandinsky
123
+ title: (번역중) Kandinsky 2.2
124
+ - local: in_translation # training/wuerstchen
125
+ title: (번역중) Wuerstchen
126
+ - local: training/controlnet
127
+ title: ControlNet
128
+ - local: in_translation # training/t2i_adapters
129
+ title: (번역중) T2I-Adapters
130
+ - local: training/instructpix2pix
131
+ title: InstructPix2Pix
132
+ title: 모델
133
+ - isExpanded: false
134
+ sections:
135
+ - local: training/text_inversion
136
+ title: Textual Inversion
137
+ - local: training/dreambooth
138
+ title: DreamBooth
139
+ - local: training/lora
140
+ title: LoRA
141
+ - local: training/custom_diffusion
142
+ title: Custom Diffusion
143
+ - local: in_translation # training/lcm_distill
144
+ title: (번역중) Latent Consistency Distillation
145
+ - local: in_translation # training/ddpo
146
+ title: (번역중) DDPO 강화학습 훈련
147
+ title: 메서드
148
+ title: 학습
149
+ - sections:
150
+ - local: optimization/fp16
151
+ title: 추론 스피드업
152
+ - local: in_translation # optimization/memory
153
+ title: (번역중) 메모리 사용량 줄이기
154
+ - local: optimization/torch2.0
155
+ title: PyTorch 2.0
156
+ - local: optimization/xformers
157
+ title: xFormers
158
+ - local: optimization/tome
159
+ title: Token merging
160
+ - local: in_translation # optimization/deepcache
161
+ title: (번역중) DeepCache
162
+ - local: in_translation # optimization/tgate
163
+ title: (번역중) TGATE
164
+ - sections:
165
+ - local: using-diffusers/stable_diffusion_jax_how_to
166
+ title: JAX/Flax
167
+ - local: optimization/onnx
168
+ title: ONNX
169
+ - local: optimization/open_vino
170
+ title: OpenVINO
171
+ - local: optimization/coreml
172
+ title: Core ML
173
+ title: 최적화된 모델 형식
174
+ - sections:
175
+ - local: optimization/mps
176
+ title: Metal Performance Shaders (MPS)
177
+ - local: optimization/habana
178
+ title: Intel Gaudi
179
+ title: 최적화된 하드웨어
180
+ title: 추론 가속화와 메모리 줄이기
181
+ - sections:
182
+ - local: conceptual/philosophy
183
+ title: 철학
184
+ - local: using-diffusers/controlling_generation
185
+ title: 제어된 생성
186
+ - local: conceptual/contribution
187
+ title: 어떻게 기여하나요?
188
+ - local: conceptual/ethical_guidelines
189
+ title: Diffusers의 윤리적 가이드라인
190
+ - local: conceptual/evaluation
191
+ title: Diffusion Models 평가하기
192
+ title: 개념 가이드
193
+ - sections:
194
+ - sections:
195
+ - sections:
196
+ - local: api/pipelines/stable_diffusion/stable_diffusion_xl
197
+ title: Stable Diffusion XL
198
+ title: Stable Diffusion
199
+ title: Pipelines
200
+ title: API
tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/ko/api/pipelines/stable_diffusion/stable_diffusion_xl.md ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ Stable Diffusion XL은 Dustin Podell, Zion English, Kyle Lacey, Andreas Blattmann, Tim Dockhorn, Jonas Müller, Joe Penna, Robin Rombach에 의해 [SDXL: Improving Latent Diffusion Models for High-Resolution Image Synthesis](https://huggingface.co/papers/2307.01952)에서 제안되었습니다.
16
+
17
+ 논문 초록은 다음을 따릅니다:
18
+
19
+ *text-to-image의 latent diffusion 모델인 SDXL을 소개합니다. 이전 버전의 Stable Diffusion과 비교하면, SDXL은 세 배 더큰 규모의 UNet 백본을 포함합니다: 모델 파라미터의 증가는 많은 attention 블럭을 사용하고 더 큰 cross-attention context를 SDXL의 두 번째 텍스트 인코더에 사용하기 때문입니다. 다중 종횡비에 다수의 새로운 conditioning 방법을 구성했습니다. 또한 후에 수정하는 image-to-image 기술을 사용함으로써 SDXL에 의해 생성된 시각적 품질을 향상하기 위해 정제된 모델을 소개합니다. SDXL은 이전 버전의 Stable Diffusion보다 성능이 향상되었고, 이러한 black-box 최신 이미지 생성자와 경쟁력있는 결과를 달성했습니다.*
20
+
21
+ ## 팁
22
+
23
+ - Stable Diffusion XL은 특히 786과 1024사이의 이미지에 잘 작동합니다.
24
+ - Stable Diffusion XL은 아래와 같이 학습된 각 텍스트 인코더에 대해 서로 다른 프롬프트를 전달할 수 있습니다. 동일한 프롬프트의 다른 부분을 텍스트 인코더에 전달할 수도 있습니다.
25
+ - Stable Diffusion XL 결과 이미지는 아래에 보여지듯이 정제기(refiner)를 사용함으로써 향상될 수 있습니다.
26
+
27
+ ### 이용가능한 체크포인트:
28
+
29
+ - *Text-to-Image (1024x1024 해상도)*: [`StableDiffusionXLPipeline`]을 사용한 [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
30
+ - *Image-to-Image / 정제기(refiner) (1024x1024 해상도)*: [`StableDiffusionXLImg2ImgPipeline`]를 사용한 [stabilityai/stable-diffusion-xl-refiner-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-refiner-1.0)
31
+
32
+ ## 사용 예시
33
+
34
+ SDXL을 사용하기 전에 `transformers`, `accelerate`, `safetensors` 와 `invisible_watermark`를 설치하세요.
35
+ 다음과 같이 라이브러리를 설치할 수 있습니다:
36
+
37
+ ```sh
38
+ pip install transformers
39
+ pip install accelerate
40
+ pip install safetensors
41
+ pip install invisible-watermark>=0.2.0
42
+ ```
43
+
44
+ ### 워터마커
45
+
46
+ Stable Diffusion XL로 이미지를 생성할 때 워터마크가 보이지 않도록 추가하는 것을 권장하는데, 이는 다운스트림(downstream) 어플리케이션에서 기계에 합성되었는지를 식별하는데 도움을 줄 수 있습니다. 그렇게 하려면 [invisible_watermark 라이브러리](https://pypi.org/project/invisible-watermark/)를 통해 설치해주세요:
47
+
48
+
49
+ ```sh
50
+ pip install invisible-watermark>=0.2.0
51
+ ```
52
+
53
+ `invisible-watermark` 라이브러리가 설치되면 워터마커가 **기본적으로** 사용될 것입니다.
54
+
55
+ 생성 또는 안전하게 이미지를 배포하기 위해 다른 규정이 있다면, 다음과 같이 워터마커를 비활성화할 수 있습니다:
56
+
57
+ ```py
58
+ pipe = StableDiffusionXLPipeline.from_pretrained(..., add_watermarker=False)
59
+ ```
60
+
61
+ ### Text-to-Image
62
+
63
+ *text-to-image*를 위해 다음과 같이 SDXL을 사용할 수 있습니다:
64
+
65
+ ```py
66
+ from diffusers import StableDiffusionXLPipeline
67
+ import torch
68
+
69
+ pipe = StableDiffusionXLPipeline.from_pretrained(
70
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16, variant="fp16", use_safetensors=True
71
+ )
72
+ pipe.to("cuda")
73
+
74
+ prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
75
+ image = pipe(prompt=prompt).images[0]
76
+ ```
77
+
78
+ ### Image-to-image
79
+
80
+ *image-to-image*를 위해 다음과 같이 SDXL을 사용할 수 있습니다:
81
+
82
+ ```py
83
+ import torch
84
+ from diffusers import StableDiffusionXLImg2ImgPipeline
85
+ from diffusers.utils import load_image
86
+
87
+ pipe = StableDiffusionXLImg2ImgPipeline.from_pretrained(
88
+ "stabilityai/stable-diffusion-xl-refiner-1.0", torch_dtype=torch.float16, variant="fp16", use_safetensors=True
89
+ )
90
+ pipe = pipe.to("cuda")
91
+ url = "https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/aa_xl/000000009.png"
92
+
93
+ init_image = load_image(url).convert("RGB")
94
+ prompt = "a photo of an astronaut riding a horse on mars"
95
+ image = pipe(prompt, image=init_image).images[0]
96
+ ```
97
+
98
+ ### 인페인팅
99
+
100
+ *inpainting*를 위해 다음과 같이 SDXL을 사용할 수 있습니다:
101
+
102
+ ```py
103
+ import torch
104
+ from diffusers import StableDiffusionXLInpaintPipeline
105
+ from diffusers.utils import load_image
106
+
107
+ pipe = StableDiffusionXLInpaintPipeline.from_pretrained(
108
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16, variant="fp16", use_safetensors=True
109
+ )
110
+ pipe.to("cuda")
111
+
112
+ img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
113
+ mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
114
+
115
+ init_image = load_image(img_url).convert("RGB")
116
+ mask_image = load_image(mask_url).convert("RGB")
117
+
118
+ prompt = "A majestic tiger sitting on a bench"
119
+ image = pipe(prompt=prompt, image=init_image, mask_image=mask_image, num_inference_steps=50, strength=0.80).images[0]
120
+ ```
121
+
122
+ ### 이미지 결과물을 정제하기
123
+
124
+ [base 모델 체크포인트](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)에서, StableDiffusion-XL 또한 고주파 품질을 향상시키는 이미지를 생성하기 위해 낮은 노이즈 단계 이미지를 제거하는데 특화된 [refiner 체크포인트](https://huggingface.co/stabilityai/stable-diffusion-xl-refiner-1.0)를 포함하고 있습니다. 이 refiner 체크포인트는 이미지 품질을 향상시키기 위해 base 체크포인트를 실행한 후 "두 번째 단계" 파이프라인에 사용될 수 있습니다.
125
+
126
+ refiner를 사용할 때, 쉽게 사용할 수 있습니다
127
+ - 1.) base 모델과 refiner을 사용하는데, 이는 *Denoisers의 앙상블*을 위한 첫 번째 제안된 [eDiff-I](https://research.nvidia.com/labs/dir/eDiff-I/)를 사용하거나
128
+ - 2.) base 모델을 거친 후 [SDEdit](https://huggingface.co/papers/2108.01073) 방법으로 단순하게 refiner를 실행시킬 수 있습니다.
129
+
130
+ **참고**: SD-XL base와 refiner를 앙상블로 사용하는 아이디어는 커뮤니티 기여자들이 처음으로 제안했으며, 이는 다음과 같은 `diffusers`를 구현하는 데도 도움을 주셨습니다.
131
+ - [SytanSD](https://github.com/SytanSD)
132
+ - [bghira](https://github.com/bghira)
133
+ - [Birch-san](https://github.com/Birch-san)
134
+ - [AmericanPresidentJimmyCarter](https://github.com/AmericanPresidentJimmyCarter)
135
+
136
+ #### 1.) Denoisers의 앙상블
137
+
138
+ base와 refiner 모델을 denoiser의 앙상블로 사용할 때, base 모델은 고주파 diffusion 단계를 위한 전문가의 역할을 해야하고, refiner는 낮은 노이즈 diffusion 단계를 위한 전문가의 역할을 해야 합니다.
139
+
140
+ 2.)에 비해 1.)의 장점은 전체적으로 denoising 단계가 덜 필요하므로 속도가 훨씬 더 빨라집니다. 단점은 base 모델의 결과를 검사할 수 없다는 것입니다. 즉, 여전히 노이즈가 심하게 제거됩니다.
141
+
142
+ base 모델과 refiner를 denoiser의 앙상블로 사용하기 위해 각각 고노이즈(high-nosise) (*즉* base 모델)와 저노이즈 (*즉* refiner 모델)의 노이즈를 제거하는 단계를 거쳐야하는 타임스텝의 기간을 정의해야 합니다.
143
+ base 모델의 [`denoising_end`](https://huggingface.co/docs/diffusers/main/en/api/pipelines/stable_diffusion/stable_diffusion_xl#diffusers.StableDiffusionXLPipeline.__call__.denoising_end)와 refiner 모델의 [`denoising_start`](https://huggingface.co/docs/diffusers/main/en/api/pipelines/stable_diffusion/stable_diffusion_xl#diffusers.StableDiffusionXLImg2ImgPipeline.__call__.denoising_start)를 사용해 간격을 정합니다.
144
+
145
+ `denoising_end`와 `denoising_start` 모두 0과 1사이의 실수 값으로 전달되어야 합니다.
146
+ 전달되면 노이즈 제거의 끝과 시작은 모델 스케줄에 의해 정의된 이산적(discrete) 시간 간격의 비율로 정의됩니다.
147
+ 노이즈 제거 단계의 수는 모델이 학습된 불연속적인 시간 간격과 선언된 fractional cutoff에 의해 결정되므로 '강도' 또한 선언된 경우 이 값이 '강도'를 재정의합니다.
148
+
149
+ 예시를 들어보겠습니다.
150
+ 우선, 두 개의 파이프라인을 가져옵니다. 텍스트 인코더와 variational autoencoder는 동일하므로 refiner를 위해 다시 불러오지 않아도 됩니다.
151
+
152
+ ```py
153
+ from diffusers import DiffusionPipeline
154
+ import torch
155
+
156
+ base = DiffusionPipeline.from_pretrained(
157
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16, variant="fp16", use_safetensors=True
158
+ )
159
+ pipe.to("cuda")
160
+
161
+ refiner = DiffusionPipeline.from_pretrained(
162
+ "stabilityai/stable-diffusion-xl-refiner-1.0",
163
+ text_encoder_2=base.text_encoder_2,
164
+ vae=base.vae,
165
+ torch_dtype=torch.float16,
166
+ use_safetensors=True,
167
+ variant="fp16",
168
+ )
169
+ refiner.to("cuda")
170
+ ```
171
+
172
+ 이제 추론 단계의 수와 고노이즈에서 노이즈를 제거하는 단계(*즉* base 모델)를 거쳐 실행되는 지점을 정의합니다.
173
+
174
+ ```py
175
+ n_steps = 40
176
+ high_noise_frac = 0.8
177
+ ```
178
+
179
+ Stable Diffusion XL base 모델은 타임스텝 0-999에 학습되며 Stable Diffusion XL refiner는 포괄적인 낮은 노이즈 타임스텝인 0-199에 base 모델로 부터 파인튜닝되어, 첫 800 타임스텝 (높은 노이즈)에 base 모델을 사용하고 마지막 200 타입스텝 (낮은 노이즈)에서 refiner가 사용됩니다. 따라서, `high_noise_frac`는 0.8로 설정하고, 모든 200-999 스텝(노이즈 제거 타임스텝의 첫 80%)은 base 모델에 의해 수행되며 0-199 스텝(노이즈 제거 타임스텝의 마지막 20%)은 refiner 모델에 의해 수행됩니다.
180
+
181
+ 기억하세요, 노이즈 제거 절차는 **높은 값**(높은 노이즈) 타임스텝에서 시작되고, **낮은 값** (낮은 노이즈) 타임스텝에서 끝납니다.
182
+
183
+ 이제 두 파이프라인을 실행해봅시다. `denoising_end`과 `denoising_start`를 같은 값으로 설정하고 `num_inference_steps`는 상수로 유지합니다. 또한 base 모델의 출력은 잠재 공간에 있어야 한다는 점을 기억하세요:
184
+
185
+ ```py
186
+ prompt = "A majestic lion jumping from a big stone at night"
187
+
188
+ image = base(
189
+ prompt=prompt,
190
+ num_inference_steps=n_steps,
191
+ denoising_end=high_noise_frac,
192
+ output_type="latent",
193
+ ).images
194
+ image = refiner(
195
+ prompt=prompt,
196
+ num_inference_steps=n_steps,
197
+ denoising_start=high_noise_frac,
198
+ image=image,
199
+ ).images[0]
200
+ ```
201
+
202
+ 이미지를 살펴보겠습니다.
203
+
204
+ | 원래의 이미지 | Denoiser들의 앙상블 |
205
+ |---|---|
206
+ | ![lion_base](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/lion_base.png) | ![lion_ref](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/lion_refined.png)
207
+
208
+ 동일한 40 단계에서 base 모델을 실행한다면, 이미지의 디테일(예: 사자의 눈과 코)이 떨어졌을 것입니다:
209
+
210
+ > [!TIP]
211
+ > 앙상블 방식은 사용 가능한 모든 스케줄러에서 잘 작동합니다!
212
+
213
+ #### 2.) 노이즈가 완전히 제거된 기본 이미지에서 이미지 출력을 정제하기
214
+
215
+ 일반적인 [`StableDiffusionImg2ImgPipeline`] 방식에서, 기본 모델에서 생성된 완전히 노이즈가 제거된 이미지는 [refiner checkpoint](https://huggingface.co/stabilityai/stable-diffusion-xl-refiner-1.0)를 사용해 더 향상시킬 수 있습니다.
216
+
217
+ 이를 위해, 보통의 "base" text-to-image 파이프라인을 수행 후에 image-to-image 파이프라인으로써 refiner를 실행시킬 수 있습니다. base 모델의 출력을 잠재 공간에 남겨둘 수 있습니다.
218
+
219
+ ```py
220
+ from diffusers import DiffusionPipeline
221
+ import torch
222
+
223
+ pipe = DiffusionPipeline.from_pretrained(
224
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16, variant="fp16", use_safetensors=True
225
+ )
226
+ pipe.to("cuda")
227
+
228
+ refiner = DiffusionPipeline.from_pretrained(
229
+ "stabilityai/stable-diffusion-xl-refiner-1.0",
230
+ text_encoder_2=pipe.text_encoder_2,
231
+ vae=pipe.vae,
232
+ torch_dtype=torch.float16,
233
+ use_safetensors=True,
234
+ variant="fp16",
235
+ )
236
+ refiner.to("cuda")
237
+
238
+ prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
239
+
240
+ image = pipe(prompt=prompt, output_type="latent" if use_refiner else "pil").images[0]
241
+ image = refiner(prompt=prompt, image=image[None, :]).images[0]
242
+ ```
243
+
244
+ | 원래의 이미지 | 정제된 이미지 |
245
+ |---|---|
246
+ | ![](https://huggingface.co/datasets/diffusers/docs-images/resolve/main/sd_xl/init_image.png) | ![](https://huggingface.co/datasets/diffusers/docs-images/resolve/main/sd_xl/refined_image.png) |
247
+
248
+ > [!TIP]
249
+ > refiner는 또한 인페인팅 설정에 잘 사용될 수 있습니다. 아래에 보여지듯이 [`StableDiffusionXLInpaintPipeline`] 클래스를 사용해서 만들어보세요.
250
+
251
+ Denoiser 앙상블 설정에서 인페인팅에 refiner를 사용하려면 다음을 수행하면 됩니다:
252
+
253
+ ```py
254
+ from diffusers import StableDiffusionXLInpaintPipeline
255
+ from diffusers.utils import load_image
256
+
257
+ pipe = StableDiffusionXLInpaintPipeline.from_pretrained(
258
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16, variant="fp16", use_safetensors=True
259
+ )
260
+ pipe.to("cuda")
261
+
262
+ refiner = StableDiffusionXLInpaintPipeline.from_pretrained(
263
+ "stabilityai/stable-diffusion-xl-refiner-1.0",
264
+ text_encoder_2=pipe.text_encoder_2,
265
+ vae=pipe.vae,
266
+ torch_dtype=torch.float16,
267
+ use_safetensors=True,
268
+ variant="fp16",
269
+ )
270
+ refiner.to("cuda")
271
+
272
+ img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
273
+ mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
274
+
275
+ init_image = load_image(img_url).convert("RGB")
276
+ mask_image = load_image(mask_url).convert("RGB")
277
+
278
+ prompt = "A majestic tiger sitting on a bench"
279
+ num_inference_steps = 75
280
+ high_noise_frac = 0.7
281
+
282
+ image = pipe(
283
+ prompt=prompt,
284
+ image=init_image,
285
+ mask_image=mask_image,
286
+ num_inference_steps=num_inference_steps,
287
+ denoising_start=high_noise_frac,
288
+ output_type="latent",
289
+ ).images
290
+ image = refiner(
291
+ prompt=prompt,
292
+ image=image,
293
+ mask_image=mask_image,
294
+ num_inference_steps=num_inference_steps,
295
+ denoising_start=high_noise_frac,
296
+ ).images[0]
297
+ ```
298
+
299
+ 일반적인 SDE 설정에서 인페인팅에 refiner를 사용하기 위해, `denoising_end`와 `denoising_start`를 제거하고 refiner의 추론 단계의 수를 적게 선택하세요.
300
+
301
+ ### 단독 체크포인트 파일 / 원래의 파일 형식으로 불러오기
302
+
303
+ [`~diffusers.loaders.FromSingleFileMixin.from_single_file`]를 사용함으로써 원래의 파일 형식을 `diffusers` 형식으로 불러올 수 있습니다:
304
+
305
+ ```py
306
+ from diffusers import StableDiffusionXLPipeline, StableDiffusionXLImg2ImgPipeline
307
+ import torch
308
+
309
+ pipe = StableDiffusionXLPipeline.from_single_file(
310
+ "./sd_xl_base_1.0.safetensors", torch_dtype=torch.float16
311
+ )
312
+ pipe.to("cuda")
313
+
314
+ refiner = StableDiffusionXLImg2ImgPipeline.from_single_file(
315
+ "./sd_xl_refiner_1.0.safetensors", torch_dtype=torch.float16
316
+ )
317
+ refiner.to("cuda")
318
+ ```
319
+
320
+ ### 모델 offloading을 통해 메모리 최적화하기
321
+
322
+ out-of-memory 에러가 난다면, [`StableDiffusionXLPipeline.enable_model_cpu_offload`]을 사용하는 것을 권장합니다.
323
+
324
+ ```diff
325
+ - pipe.to("cuda")
326
+ + pipe.enable_model_cpu_offload()
327
+ ```
328
+
329
+ 그리고
330
+
331
+ ```diff
332
+ - refiner.to("cuda")
333
+ + refiner.enable_model_cpu_offload()
334
+ ```
335
+
336
+ ### `torch.compile`로 추론 속도를 올리기
337
+
338
+ `torch.compile`를 사용함으로써 추론 속도를 올릴 수 있습니다. 이는 **ca.** 20% 속도 향상이 됩니다.
339
+
340
+ ```diff
341
+ + pipe.unet = torch.compile(pipe.unet, mode="reduce-overhead", fullgraph=True)
342
+ + refiner.unet = torch.compile(refiner.unet, mode="reduce-overhead", fullgraph=True)
343
+ ```
344
+
345
+ ### `torch < 2.0`일 때 실행하기
346
+
347
+ **참고** Stable Diffusion XL을 `torch`가 2.0 버전 미만에서 실행시키고 싶을 때, xformers 어텐션을 사용해주세요:
348
+
349
+ ```sh
350
+ pip install xformers
351
+ ```
352
+
353
+ ```diff
354
+ +pipe.enable_xformers_memory_efficient_attention()
355
+ +refiner.enable_xformers_memory_efficient_attention()
356
+ ```
357
+
358
+ ## StableDiffusionXLPipeline
359
+
360
+ [[autodoc]] StableDiffusionXLPipeline
361
+ - all
362
+ - __call__
363
+
364
+ ## StableDiffusionXLImg2ImgPipeline
365
+
366
+ [[autodoc]] StableDiffusionXLImg2ImgPipeline
367
+ - all
368
+ - __call__
369
+
370
+ ## StableDiffusionXLInpaintPipeline
371
+
372
+ [[autodoc]] StableDiffusionXLInpaintPipeline
373
+ - all
374
+ - __call__
375
+
376
+ ### 각 텍스트 인코더에 다른 프롬프트를 전달하기
377
+
378
+ Stable Diffusion XL는 두 개의 텍스트 인코더에 학습되었습니다. 기본 동작은 각 프롬프트에 동일한 프롬프트를 전달하는 것입니다. 그러나 [일부 사용자](https://github.com/huggingface/diffusers/issues/4004#issuecomment-1627764201)가 품질을 향상시킬 수 있다고 지적한 것처럼 텍스트 인코더마다 다른 프롬프트를 전달할 수 있습니다. 그렇게 하려면, `prompt_2`와 `negative_prompt_2`를 `prompt`와 `negative_prompt`에 전달해야 합니다. 그렇게 함으로써, 원래의 프롬프트들(`prompt`)과 부정 프롬프트들(`negative_prompt`)를 `텍스트 인코더`에 전달할 것입니다.(공식 SDXL 0.9/1.0의 [OpenAI CLIP-ViT/L-14](https://huggingface.co/openai/clip-vit-large-patch14)에서 볼 수 있습니다.) 그리고 `prompt_2`와 `negative_prompt_2`는 `text_encoder_2`에 전달됩니다.(공식 SDXL 0.9/1.0의 [OpenCLIP-ViT/bigG-14](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)에서 볼 수 있습니다.)
379
+
380
+ ```py
381
+ from diffusers import StableDiffusionXLPipeline
382
+ import torch
383
+
384
+ pipe = StableDiffusionXLPipeline.from_pretrained(
385
+ "stabilityai/stable-diffusion-xl-base-0.9", torch_dtype=torch.float16, variant="fp16", use_safetensors=True
386
+ )
387
+ pipe.to("cuda")
388
+
389
+ # OAI CLIP-ViT/L-14에 prompt가 전달됩니다
390
+ prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
391
+ # OpenCLIP-ViT/bigG-14에 prompt_2가 전달됩니다
392
+ prompt_2 = "monet painting"
393
+ image = pipe(prompt=prompt, prompt_2=prompt_2).images[0]
394
+ ```
tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/ko/conceptual/contribution.md ADDED
@@ -0,0 +1,511 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Diffusers에 기여하는 방법 🧨 [[how-to-contribute-to-diffusers-]]
14
+
15
+ 오픈 소스 커뮤니티에서의 기여를 환영합니다! 누구나 참여할 수 있으며, 코드뿐만 아니라 질문에 답변하거나 문서를 개선하는 등 모든 유형의 참여가 가치 있고 감사히 여겨집니다. 질문에 답변하고 다른 사람들을 도와주며 소통하고 문서를 개선하는 것은 모두 커뮤니티에게 큰 도움이 됩니다. 따라서 관심이 있다면 두려워하지 말고 참여해보세요!
16
+
17
+ 누구나 우리의 공개 Discord 채널에서 👋 인사하며 시작할 수 있도록 장려합니다. 우리는 diffusion 모델의 최신 동향을 논의하고 질문을 하며 개인 프로젝트를 자랑하고 기여에 대해 서로 도와주거나 그냥 어울리기 위해 모이는 곳입니다☕. <a href="https://Discord.gg/G7tWnz98XR"><img alt="Join us on Discord" src="https://img.shields.io/discord/823813159592001537?color=5865F2&logo=discord&logoColor=white"></a>
18
+
19
+ 어떤 방식으로든 기여하려는 경우, 우리는 개방적이고 환영하며 친근한 커뮤니티의 일부가 되기 위해 노력하고 있습니다. 우리의 [행동 강령](https://github.com/huggingface/diffusers/blob/main/CODE_OF_CONDUCT.md)을 읽고 상호 작용 중에 이를 존중하도록 주의해주시기 바랍니다. 또한 프로젝트를 안내하는 [윤리 지침](https://huggingface.co/docs/diffusers/conceptual/ethical_guidelines)에 익숙해지고 동일한 투명성과 책임성의 원칙을 준수해주시기를 부탁드립니다.
20
+
21
+ 우리는 커뮤니티로부터의 피드백을 매우 중요하게 생각하므로, 라이브러리를 개선하는 데 도움이 될 가치 있는 피드백이 있다고 생각되면 망설이지 말고 의견을 제시해주세요 - 모든 메시지, 댓글, 이슈, Pull Request(PR)는 읽히고 고려됩니다.
22
+
23
+ ## 개요 [[overview]]
24
+
25
+ 이슈에 있는 질문에 답변하는 것에서부터 코어 라이브러리에 새로운 diffusion 모델을 추가하는 것까지 다양한 방법으로 기여를 할 수 있습니다.
26
+
27
+ 이어지는 부분에서 우리는 다양한 방법의 기여에 대한 개요를 난이도에 따라 오름차순으로 정리하였습니다. 모든 기여는 커뮤니티에게 가치가 있습니다.
28
+
29
+ 1. [Diffusers 토론 포럼](https://discuss.huggingface.co/c/discussion-related-to-httpsgithubcomhuggingfacediffusers)이나 [Discord](https://discord.gg/G7tWnz98XR)에서 질문에 대답하거나 질문을 할 수 있습니다.
30
+ 2. [GitHub Issues 탭](https://github.com/huggingface/diffusers/issues/new/choose)에서 새로운 이슈를 열 수 있습니다.
31
+ 3. [GitHub Issues 탭](https://github.com/huggingface/diffusers/issues)에서 이슈에 대답할 수 있습니다.
32
+ 4. "Good first issue" 라벨이 지정된 간단한 이슈를 수정할 수 있습니다. [여기](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22)를 참조하세요.
33
+ 5. [문서](https://github.com/huggingface/diffusers/tree/main/docs/source)에 기여할 수 있습니다.
34
+ 6. [Community Pipeline](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3Acommunity-examples)에 기여할 수 있습니다.
35
+ 7. [예제](https://github.com/huggingface/diffusers/tree/main/examples)에 기여할 수 있습니다.
36
+ 8. "Good second issue" 라벨이 지정된 어려운 이슈를 수정할 수 있습니다. [여기](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22Good+second+issue%22)를 참조하세요.
37
+ 9. 새로운 파이프라인, 모델 또는 스케줄러를 추가할 수 있습니다. ["새로운 파이프라인/모델"](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22New+pipeline%2Fmodel%22) 및 ["새로운 스케줄러"](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22New+scheduler%22) 이슈를 참조하세요. 이 기여에 대해서는 [디자인 철학](https://huggingface.co/docs/diffusers/main/ko/conceptual/philosophy)을 확인해주세요.
38
+
39
+ 앞서 말한 대로, **모든 기여는 커뮤니티에게 가치가 있습니다**. 이어지는 부분에서 각 기여에 대해 조금 더 자세히 설명하겠습니다.
40
+
41
+ 4부터 9까지의 모든 기여에는 Pull Request을 열어야 합니다. [Pull Request 열기](#how-to-open-a-pr)에서 자세�� 설명되어 있습니다.
42
+
43
+ ### 1. Diffusers 토론 포럼이나 Diffusers Discord에서 질문하고 답변하기 [[1-asking-and-answering-questions-on-the-diffusers-discussion-forum-or-on-the-diffusers-discord]]
44
+
45
+ Diffusers 라이브러리와 관련된 모든 질문이나 의견은 [토론 포럼](https://discuss.huggingface.co/c/discussion-related-to-httpsgithubcomhuggingfacediffusers/63)이나 [Discord](https://discord.gg/G7tWnz98XR)에서 할 수 있습니다. 이러한 질문과 의견에는 다음과 같은 내용이 포함됩니다(하지만 이에 국한되지는 않습니다):
46
+ - 지식을 공유하기 위해서 훈련 또는 추론 실험에 대한 결과 보고
47
+ - 개인 프로젝트 소개
48
+ - 비공식 훈련 예제에 대한 질문
49
+ - 프로젝트 제안
50
+ - 일반적인 피드백
51
+ - 논문 요약
52
+ - Diffusers 라이브러리를 기반으로 하는 개인 프로젝트에 대한 도움 요청
53
+ - 일반적인 질문
54
+ - Diffusion 모델에 대한 윤리적 질문
55
+ - ...
56
+
57
+ 포럼이나 Discord에서 질문을 하면 커뮤니티가 지식을 공개적으로 공유하도록 장려되며, 향후 동일한 질문을 가진 초보자에게도 도움이 될 수 있습니다. 따라서 궁금한 질문은 언제든지 하시기 바랍니다.
58
+ 또한, 이러한 질문에 답변하는 것은 커뮤니티에게 매우 큰 도움이 됩니다. 왜냐하면 이렇게 하면 모두가 학습할 수 있는 공개적인 지식을 문서화하기 때문입니다.
59
+
60
+ **주의**하십시오. 질문이나 답변에 투자하는 노력이 많을수록 공개적으로 문서화된 지식의 품질이 높아집니다. 마찬가지로, 잘 정의되고 잘 답변된 질문은 모두에게 접근 가능한 고품질 지식 데이터베이스를 만들어줍니다. 반면에 잘못된 질문이나 답변은 공개 지식 데이터베이스의 전반적인 품질을 낮출 수 있습니다.
61
+ 간단히 말해서, 고품질의 질문이나 답변은 *명확하고 간결하며 관련성이 있으며 이해하기 쉽고 접근 가능하며 잘 형식화되어 있어야* 합니다. 자세한 내용은 [좋은 이슈 작성 방법](#how-to-write-a-good-issue) 섹션을 참조하십시오.
62
+
63
+ **채널에 대한 참고사항**:
64
+ [*포럼*](https://discuss.huggingface.co/c/discussion-related-to-httpsgithubcomhuggingfacediffusers/63)은 구글과 같은 검색 엔진에서 더 잘 색인화됩니다. 게시물은 인기에 따라 순위가 매겨지며, 시간순으로 정렬되지 않습니다. 따라서 이전에 게시한 질문과 답변을 쉽게 찾을 수 있습니다.
65
+ 또한, 포럼에 게시된 질문과 답변은 쉽게 링크할 수 있습니다.
66
+ 반면 *Discord*는 채팅 형식으로 되어 있어 빠른 대화를 유도합니다.
67
+ 질문에 대한 답변을 빠르게 받을 수는 있겠지만, 시간이 지나면 질문이 더 이상 보이지 않습니다. 또한, Discord에서 이전에 게시된 정보를 찾는 것은 훨씬 어렵습니다. 따라서 포럼을 사용하여 고품질의 질문과 답변을 하여 커뮤니티를 위한 오래 지속되는 지식을 만들기를 권장합니다. Discord에서의 토론이 매우 흥미로운 답변과 결론을 이끌어내는 경우, 해당 정보를 포럼에 게시하여 향후 독자들에게 더 쉽게 액세스할 수 있도록 권장합니다.
68
+
69
+ ### 2. GitHub 이슈 탭에서 새로운 이슈 열기 [[2-opening-new-issues-on-the-github-issues-tab]]
70
+
71
+ 🧨 Diffusers 라이브러리는 사용자들이 마주치는 문제를 알려주는 덕분에 견고하고 신뢰할 수 있습니다. 따라서 이슈를 보고해주셔서 감사합니다.
72
+
73
+ 기억해주세요, GitHub 이슈는 Diffusers 라이브러리와 직접적으로 관련된 기술적인 질문, 버그 리포트, 기능 요청 또는 라이브러리 디자인에 대한 피드백에 사용됩니다.
74
+
75
+ 간단히 말해서, Diffusers 라이브러리의 **코드와 관련되지 않은** 모든 것(문서 포함)은 GitHub가 아닌 [포럼](https://discuss.huggingface.co/c/discussion-related-to-httpsgithubcomhuggingfacediffusers/63)이나 [Discord](https://discord.gg/G7tWnz98XR)에서 질문해야 합니다.
76
+
77
+ **새로운 이슈를 열 때 다음 가이드라인을 고려해주세요**:
78
+ - 이미 같은 이슈가 있는지 검색했는지 확인해주세요(GitHub의 이슈 탭에서 검색 기능을 사용하세요).
79
+ - 다른(관련된) 이슈에 새로운 이슈를 보고하지 말아주세요. 다른 이슈와 관련이 높다면, 새로운 이슈를 열고 관련 이슈에 링크를 걸어주세요.
80
+ - 이슈를 영어로 작성해주세요. 영어에 익숙하지 않다면, [DeepL](https://www.deepl.com/translator)과 같은 뛰어난 무료 온라인 번역 서비스를 사용하여 모국어에서 영어로 번역해주세요.
81
+ - 이슈가 최신 Diffusers 버전으로 업데이트하면 해결될 수 있는지 확인해주세요. 이슈를 게시하기 전에 `python -c "import diffusers; print(diffusers.__version__)"` 명령을 실행하여 현재 사용 중인 Diffusers 버전이 최신 버전과 ��치하거나 더 높은지 확인해주세요.
82
+ - 새로운 이슈를 열 때 투자하는 노력이 많을수록 답변의 품질이 높아지고 Diffusers 이슈 전체의 품질도 향상됩니다.
83
+
84
+ #### 2.1 재현 가능한 최소한의 버그 리포트 [[21-reproducible-minimal-bug-reports]]
85
+
86
+
87
+ 버그 리포트는 항상 재현 가능한 코드 조각을 포함하고 가능한 한 최소한이어야 하며 간결해야 합니다.
88
+ 자세히 말하면:
89
+ - 버그를 가능한 한 좁혀야 합니다. **전체 코드 파일을 그냥 던지지 마세요**.
90
+ - 코드의 서식을 지정해야 합니다.
91
+ - Diffusers가 의존하는 외부 라이브러리를 제외한 다른 외부 라이브러리는 포함하지 마십시오.
92
+ - **항상** 사용자 환경에 대한 모든 필요한 정보를 제공하세요. 이를 위해 쉘에서 `diffusers-cli env`를 실행하고 표시된 정보를 이슈에 복사하여 붙여넣을 수 있습니다.
93
+ - 이슈를 설명해야 합니다. 독자가 문제가 무엇인지, 왜 문제가 되는지 모른다면 이슈를 해결할 수 없습니다.
94
+ - **항상** 독자가 가능한 한 적은 노력으로 문제를 재현할 수 있어야 합니다. 코드 조각이 라이브러리가 없거나 정의되지 않은 변수 때문에 실행되지 않는 경우 독자가 도움을 줄 수 없습니다. 재현 가능한 코드 조각이 가능한 한 최소화되고 간단한 Python 셸에 복사하여 붙여넣을 수 있도록 해야 합니다.
95
+ - 문제를 재현하기 위해 모델과/또는 데이터셋이 필요한 경우 독자가 해당 모델이나 데이터셋에 접근할 수 있도록 해야 합니다. 모델이나 데이터셋을 [Hub](https://huggingface.co)에 업로드하여 쉽게 다운로드할 수 있도록 할 수 있습니다. 문제 재현을 가능한 한 쉽게하기 위해 모델과 데이터셋을 가능한 한 작게 유지하려고 노력하세요.
96
+
97
+ 자세한 내용은 [좋은 이슈 작성 방법](#how-to-write-a-good-issue) 섹션을 참조하세요.
98
+
99
+ 버그 리포트를 열려면 [여기](https://github.com/huggingface/diffusers/issues/new?assignees=&labels=bug&projects=&template=bug-report.yml)를 클릭하세요.
100
+
101
+
102
+ #### 2.2. 기능 요청 [[22-feature-requests]]
103
+
104
+ 세계적인 기능 요청은 다음 사항을 다룹니다:
105
+
106
+ 1. 먼저 동기부여:
107
+ * 라이브러리와 관련된 문제/불만이 있나요? 그렇다면 왜 그런지 설명해주세요. 문제를 보여주는 코드 조각을 제공하는 것이 가장 좋습니다.
108
+ * 프로젝트에 필요한 기능인가요? 우리는 그에 대해 듣고 싶습니다!
109
+ * 커뮤니티에 도움이 될 수 있는 것을 작업했고 그것에 대해 생각하고 있는가요? 멋지네요! 어떤 문제를 해결했는지 알려주세요.
110
+ 2. 기능을 *상세히 설명하는* 문단을 작성해주세요;
111
+ 3. 향후 사용을 보여주는 **코드 조각**을 제공해주세요;
112
+ 4. 논문과 관련된 내용인 경우 링크를 첨부해주세요;
113
+ 5. 도움이 될 수 있다고 생각되는 추가 정보(그림, 스크린샷 등)를 첨부해주세요.
114
+
115
+ 기능 요청은 [여기](https://github.com/huggingface/diffusers/issues/new?assignees=&labels=&template=feature_request.md&title=)에서 열 수 있습니다.
116
+
117
+ #### 2.3 피드백 [[23-feedback]]
118
+
119
+ 라이브러리 디자인과 그것이 왜 좋은지 또는 나쁜지에 대한 이유에 대한 피드백은 핵심 메인테이너가 사용자 친화적인 라이브러리를 만드는 데 엄청난 도움이 됩니다. 현재 디자인 철학을 이해하려면 [여기](https://huggingface.co/docs/diffusers/conceptual/philosophy)를 참조해 주세요. 특정 디자인 선택이 현재 디자인 철학과 맞지 않는다고 생각되면, 그 이유와 어떻게 변경되어야 하는지 설명해 주세요. 반대로 특정 디자인 선택이 디자인 철학을 너무 따르기 때문에 사용 사례를 제한한다고 생각되면, 그 이유와 어떻게 변경되어야 하는지 설명해 주세요. 특정 디자인 선택이 매우 유용하다고 생각되면, 향후 디자인 결정에 큰 도움이 되므로 이에 대한 의견을 남겨 주세요.
120
+
121
+ 피드백에 관한 이슈는 [여기](https://github.com/huggingface/diffusers/issues/new?assignees=&labels=&template=feedback.md&title=)에서 열 수 있습니다.
122
+
123
+ #### 2.4 기술적인 질문 [[24-technical-questions]]
124
+
125
+ 기술적인 질문은 주로 라이브러리의 특정 코드가 왜 특정 방식으로 작성되었는지 또는 코드의 특정 부분이 무엇을 하는지에 대한 질문입니다. 질문하신 코드 부분에 대한 링크를 제공하고 해당 코드 부분이 이해하기 어려운 이유에 대한 자세한 설명을 해주시기 바랍니다.
126
+
127
+ 기술적인 질문에 관한 이슈를 [여기](https://github.com/huggingface/diffusers/issues/new?assignees=&labels=bug&template=bug-report.yml)에서 열 수 있습니다.
128
+
129
+ #### 2.5 새로운 모델, 스케줄러 또는 파이프라인 추가 제안 [[25-proposal-to-add-a-new-model-scheduler-or-pipeline]]
130
+
131
+ 만약 diffusion 모델 커뮤니티에서 Diffusers 라이브러리에 추가하고 싶은 새로운 모델, 파이프라인 또는 스케줄러가 있다면, 다음 정보를 제공해주세요:
132
+
133
+ * Diffusion 파이프라인, 모델 또는 스케줄러에 대한 간단한 설명과 논문 또는 공개된 버전의 링크
134
+ * 해당 모델의 오픈 소스 구현에 대한 링크
135
+ * 모델 가중치가 있는 경우, 가중치의 링크
136
+
137
+ 직접 모델에 기여하고 싶다면, 가장 잘 안내해드릴 수 있습니다. 또한, 가능하다면 구성 요소(모델, 스케줄러, 파이프라인 등)의 원저자를 GitHub 핸들로 태그하는 것을 잊지 마세요.
138
+
139
+ 모델/파이프라인/스케줄러에 대한 요청을 [여기](https://github.com/huggingface/diffusers/issues/new?assignees=&labels=New+model%2Fpipeline%2Fscheduler&template=new-model-addition.yml)에서 열 수 있습니다.
140
+
141
+ ### 3. GitHub 이슈 탭에서 문제에 대한 답변하기 [[3-answering-issues-on-the-github-issues-tab]]
142
+
143
+ GitHub에서 이슈에 대한 답변을 하기 위해서는 Diffusers에 대한 기술적인 지식이 필요할 수 있지만, 정확한 답변이 아니더라도 모두가 시도해기를 권장합니다. 이슈에 대한 고품질 답변을 제공하기 위한 몇 가지 팁:
144
+ - 가능한 한 간결하고 최소한으로 유지합니다.
145
+ - 주제에 집중합니다. 이슈에 대한 답변은 해당 이슈에 관련된 내용에만 집중해야 합니다.
146
+ - 자신의 주장을 증명하거나 장려하는 코드, 논문 또는 기타 출처는 링크를 제공하세요.
147
+ - 코드로 답변합니다. 간단한 코드 조각이 이슈에 대한 답변이거나 이슈를 해결하는 방법을 보여준다면, 완전히 재현 가능한 코드 조각을 제공해주세요.
148
+
149
+ 또한, 많은 이슈들은 단순히 주제와 무관하거나 다른 이슈의 중복이거나 관련이 없는 경우가 많습니다. 이러한 이슈들에 대한 답변을 제공하고, 이슈 작성자에게 더 정확한 정보를 제공하거나, 중복된 이슈에 대한 링크를 제공하거나, [포럼](https://discuss.huggingface.co/c/discussion-related-to-httpsgithubcomhuggingfacediffusers/63) 이나 [Discord](https://discord.gg/G7tWnz98XR)로 리디렉션하는 것은 메인테이너에게 큰 도움이 됩니다.
150
+
151
+ 이슈가 올바른 버그 보고서이고 소스 코드에서 수정이 필요하다고 확인한 경우, 다음 섹션을 살펴보세요.
152
+
153
+ 다음 모든 기여에 대해서는 PR을 열여야 합니다. [Pull Request 열기](#how-to-open-a-pr) 섹션에서 자세히 설명되어 있습니다.
154
+
155
+ ### 4. "Good first issue" 고치기 [[4-fixing-a-good-first-issue]]
156
+
157
+ *Good first issues*는 [Good first issue](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22) 라벨로 표시됩니다. 일반적으로, 이슈는 이미 잠재적인 해결책이 어떻게 보이는지 설명하고 있어서 수정하기 쉽습니다.
158
+ 만약 이슈가 아직 닫히지 않았고 이 문제를 해결해보고 싶다면, "이 이슈를 해결해보고 싶습니다."라는 메시지를 남기면 됩니다. 일반적으로 세 가지 시나리오가 있습니다:
159
+ - a.) 이슈 설명에 이미 수정 사항을 제안하는 경우, 해결책이 이해되고 합리적으로 보인다면, PR 또는 드래프트 PR을 열어서 수정할 수 있습니다.
160
+ - b.) 이슈 설명에 수정 사항이 제안되어 있지 않은 경우, 제안한 수정 사항이 가능할지 물어볼 수 있고, Diffusers 팀의 누군가가 곧 답변해줄 것입니다. 만약 어떻게 수정할지 좋은 아이디어가 있다면, 직접 PR을 열어도 됩니다.
161
+ - c.) 이미 이 문제를 해결하기 위해 열린 PR이 있지만, 이슈가 아직 닫히지 않았습니다. PR이 더 이상 진행되지 않았다면, 새로운 PR을 열고 이전 PR에 링크를 걸면 됩니다. PR은 종종 원래 기여자가 갑자기 시간을 내지 못해 더 이상 진행하지 못하는 경우에 더 이상 진행되지 않게 됩니다. 이는 오픈 소스에서 자주 발생하는 일이며 매우 정상적인 상황입니다. 이 경우, 커뮤니티는 새로 시도하고 기존 PR의 지식을 활용해주면 매우 기쁠 것입니다. 이미 PR이 있고 활성화되어 있다면, 제안을 해주거나 PR을 검토하거나 PR에 기여할 수 있는지 물어보는 등 작성자를 도와줄 수 있습니다.
162
+
163
+
164
+ ### 5. 문서에 기여하기 [[5-contribute-to-the-documentation]]
165
+
166
+ 좋은 라이브러리는 항상 좋은 문서를 갖고 있습니다! 공식 문서는 라이브러리를 처음 사용하는 사용자들에게 첫 번째 접점 중 하나이며, 따라서 문서에 기여하는 것은 매우 가치 있는 기여입니다.
167
+
168
+ 라이브러리에 기여하는 방법은 다양합니다:
169
+
170
+ - 맞춤법이나 문법 오류를 수정합니다.
171
+ - 공식 문서가 이상하게 표시되거나 링크가 깨진 경우, 올바르게 수정하는 데 시간을 내주시�� 매우 기쁠 것입니다.
172
+ - 문서의 입력 또는 출력 텐서의 모양이나 차원을 수정합니다.
173
+ - 이해하기 어렵거나 잘못된 문서를 명확하게 합니다.
174
+ - 오래된 코드 예제를 업데이트합니다.
175
+ - 문서를 다른 언어로 번역합니다.
176
+
177
+ [공식 Diffusers 문서 페이지](https://huggingface.co/docs/diffusers/index)에 표시된 모든 내용은 공식 문서의 일부이며, 해당 [문서 소스](https://github.com/huggingface/diffusers/tree/main/docs/source)에서 수정할 수 있습니다.
178
+
179
+ 문서에 대한 변경 사항을 로컬에서 확인하는 방법은 [이 페이지](https://github.com/huggingface/diffusers/tree/main/docs)를 참조해주세요.
180
+
181
+
182
+ ### 6. 커뮤니티 파이프라인에 기여하기 [[6-contribute-a-community-pipeline]]
183
+
184
+ > [!TIP]
185
+ > 커뮤니티 파이프라인에 대해 자세히 알아보려면 [커뮤니티 파이프라인](../using-diffusers/custom_pipeline_overview#community-pipelines) 가이드를 읽어보세요. 커뮤니티 파이프라인이 왜 필요한지 궁금하다면 GitHub 이슈 [#841](https://github.com/huggingface/diffusers/issues/841)를 확인해보세요 (기본적으로, 우리는 diffusion 모델이 추론에 사용될 수 있는 모든 방법을 유지할 수 없지만 커뮤니티가 이를 구축하는 것을 방해하고 싶지 않습니다).
186
+
187
+ 커뮤니티 파이프라인에 기여하는 것은 창의성과 작업을 커뮤니티와 공유하는 좋은 방법입니다. [`DiffusionPipeline`]을 기반으로 빌드하여 `custom_pipeline` 매개변수를 설정함으로써 누구나 로드하고 사용할 수 있도록 할 수 있습니다. 이 섹션에서는 UNet이 단일 순방향 패스만 수행하고 스케줄러를 한 번 호출하는 간단한 파이프라인 (단계별 파이프라인)을 만드는 방법을 안내합니다.
188
+
189
+ 1. 커뮤니티 파이프라인을 위한 one_step_unet.py 파일을 생성하세요. 이 파일은 사용자에 의해 설치되는 패키지를 포함할 수 있지만, [`DiffusionPipeline`]에서 모델 가중치와 스케줄러 구성을 로드하기 위해 하나의 파이프라인 클래스만 있어야 합니다. `__init__` 함수에 UNet과 스케줄러를 추가하세요.
190
+
191
+ 또한 [`~DiffusionPipeline.save_pretrained`]를 사용하여 파이프라인과 그 구성 요소를 저장할 수 있도록 `register_modules` 함수를 추가해야 합니다.
192
+
193
+ ```py
194
+ from diffusers import DiffusionPipeline
195
+ import torch
196
+
197
+ class UnetSchedulerOneForwardPipeline(DiffusionPipeline):
198
+ def __init__(self, unet, scheduler):
199
+ super().__init__()
200
+
201
+ self.register_modules(unet=unet, scheduler=scheduler)
202
+ ```
203
+
204
+ 1. forward 패스에서 (`__call__`로 정의하는 것을 추천합니다), 원하는 어떤 기능이든 추가할 수 있습니다. "one-step" 파이프라인의 경우, 무작위 이미지를 생성하고 `timestep=1`로 설정하여 UNet과 스케줄러를 한 번 호출합니다.
205
+
206
+ ```py
207
+ from diffusers import DiffusionPipeline
208
+ import torch
209
+
210
+ class UnetSchedulerOneForwardPipeline(DiffusionPipeline):
211
+ def __init__(self, unet, scheduler):
212
+ super().__init__()
213
+
214
+ self.register_modules(unet=unet, scheduler=scheduler)
215
+
216
+ def __call__(self):
217
+ image = torch.randn(
218
+ (1, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size),
219
+ )
220
+ timestep = 1
221
+
222
+ model_output = self.unet(image, timestep).sample
223
+ scheduler_output = self.scheduler.step(model_output, timestep, image).prev_sample
224
+
225
+ return scheduler_output
226
+ ```
227
+
228
+ 이제 UNet과 스케줄러를 전달하여 파이프라인을 실행하거나, 파이프라인 구조가 동일한 경우 사전 학습된 가중치를 로드할 수 있습니다.
229
+
230
+ ```py
231
+ from diffusers import DDPMScheduler, UNet2DModel
232
+
233
+ scheduler = DDPMScheduler()
234
+ unet = UNet2DModel()
235
+
236
+ pipeline = UnetSchedulerOneForwardPipeline(unet=unet, scheduler=scheduler)
237
+ output = pipeline()
238
+ # load pretrained weights
239
+ pipeline = UnetSchedulerOneForwardPipeline.from_pretrained("google/ddpm-cifar10-32", use_safetensors=True)
240
+ output = pipeline()
241
+ ```
242
+
243
+ 파이프라인을 GitHub 커뮤니티 파이프라인 또는 Hub 커뮤니티 파이프라인으로 공유할 수 있습니다.
244
+
245
+ <hfoptions id="pipeline type">
246
+ <hfoption id="GitHub pipeline">
247
+
248
+ GitHub 파이프라인을 공유하려면 Diffusers [저장소](https://github.com/huggingface/diffusers)에서 Pull Request를 열고 one_step_unet.py 파일을 [examples/community](https://github.com/huggingface/diffusers/tree/main/examples/community) 하위 폴더에 추가하세요.
249
+
250
+ </hfoption>
251
+ <hfoption id="Hub pipeline">
252
+
253
+ Hub 파이프라인을 공유하려면, 허브에 모델 저장소를 생성하고 one_step_unet.py 파일을 업로드하세요.
254
+
255
+ </hfoption>
256
+ </hfoptions>
257
+
258
+ ### 7. 훈련 예제에 기여하기 [[7-contribute-to-training-examples]]
259
+
260
+ Diffusers 예제는 [examples](https://github.com/huggingface/diffusers/tree/main/examples) 폴���에 있는 훈련 스크립트의 모음입니다.
261
+
262
+ 두 가지 유형의 훈련 예제를 지원합니다:
263
+
264
+ - 공식 훈련 예제
265
+ - 연구용 훈련 예제
266
+
267
+ 연구용 훈련 예제는 [examples/research_projects](https://github.com/huggingface/diffusers/tree/main/examples/research_projects)에 위치하며, 공식 훈련 예제는 `research_projects` 및 `community` 폴더를 제외한 [examples](https://github.com/huggingface/diffusers/tree/main/examples)의 모든 폴더를 포함합니다.
268
+ 공식 훈련 예제는 Diffusers의 핵심 메인테이너가 유지 관리하며, 연구용 훈련 예제는 커뮤니티가 유지 관리합니다.
269
+ 이는 공식 파이프라인 vs 커뮤니티 파이프라인에 대한 [6. 커뮤니티 파이프라인 기여하기](#6-contribute-a-community-pipeline)에서 제시한 이유와 동일합니다: 핵심 메인테이너가 diffusion 모델의 모든 가능한 훈련 방법을 유지 관리하는 것은 현실적으로 불가능합니다.
270
+ Diffusers 핵심 메인테이너와 커뮤니티가 특정 훈련 패러다임을 너무 실험적이거나 충분히 대중적이지 않다고 판단한다면, 해당 훈련 코드는 `research_projects` 폴더에 넣고 작성자에 의해 관리되어야 합니다.
271
+
272
+ 공식 훈련 및 연구 예제는 하나 이상의 훈련 스크립트, requirements.txt 파일 및 README.md 파일을 포함하는 디렉토리로 구성됩니다. 사용자가 훈련 예제를 사용하려면 리포지토리를 복제해야 합니다:
273
+
274
+ ```bash
275
+ git clone https://github.com/huggingface/diffusers
276
+ ```
277
+
278
+ 그리고 훈련에 필요한 모든 추가적인 의존성도 설치해야 합니다:
279
+
280
+ ```bash
281
+ pip install -r /examples/<your-example-folder>/requirements.txt
282
+ ```
283
+
284
+ 따라서 예제를 추가할 때, `requirements.txt` 파일은 훈련 예제에 필요한 모든 pip 종속성을 정의해야 합니다. 이렇게 설치된 모든 종속성을 사용하여 사용자가 예제의 훈련 스크립트를 실행할 수 있어야 합니다. 예를 들어, [DreamBooth `requirements.txt` 파일](https://github.com/huggingface/diffusers/blob/main/examples/dreambooth/requirements.txt)을 참조하세요.
285
+
286
+ Diffusers 라이브러리의 훈련 예제는 다음 철학을 따라야 합니다:
287
+ - 예제를 실행하는 데 필요한 모든 코드는 하나의 Python 파일에 있어야 합니다.
288
+ - 사용자는 명령 줄에서 `python <your-example>.py --args`와 같이 예제를 실행할 수 있어야 합니다.
289
+ - 예제는 간단하게 유지되어야 하며, Diffusers를 사용한 훈련 방법을 보여주는 **예시**로 사용되어야 합니다. 예제 스크립트의 목적은 최첨단 diffusion 모델을 만드는 것이 아니라, 너무 많은 사용자 정의 로직을 추가하지 않고 이미 알려진 훈련 방법을 재현하는 것입니다. 이 점의 부산물로서, 예제는 좋은 교육 자료로써의 역할을 하기 위해 노력합니다.
290
+
291
+ 예제에 기여하기 위해서는, 이미 존재하는 예제인 [dreambooth](https://github.com/huggingface/diffusers/blob/main/examples/dreambooth/train_dreambooth.py)와 같은 예제를 참고하여 어떻게 보여야 하는지에 대한 아이디어를 얻는 것이 매우 권장됩니다.
292
+ Diffusers와 긴밀하게 통합되어 있기 때문에, 기여자들이 [Accelerate 라이브러리](https://github.com/huggingface/accelerate)를 사용하는 것을 강력히 권장합니다.
293
+ 예제 스크립트가 작동하는 경우, 반드시 예제를 정확하게 사용하는 방법을 설명하는 포괄적인 `README.md`를 추가해야 합니다. 이 README에는 다음이 포함되어야 합니다:
294
+ - [여기](https://github.com/huggingface/diffusers/tree/main/examples/dreambooth#running-locally-with-pytorch)에 표시된 예제 스크립트를 실행하는 방법에 대한 예제 명령어.
295
+ - [여기](https://api.wandb.ai/report/patrickvonplaten/xm6cd5q5)에 표시된 훈련 결과 (로그, 모델 등)에 대한 링크로 사용자가 기대할 수 있는 내용을 보여줍니다.
296
+ - 비공식/연구용 훈련 예제를 추가하는 경우, **반드시** git 핸들을 포함하여 이 훈련 예제를 유지 관리할 것임을 명시하는 문장을 추가해야 합니다. [여기](https://github.com/huggingface/diffusers/tree/main/examples/research_projects/intel_opts#diffusers-examples-with-intel-optimizations)에 표시된 것과 같습니다.
297
+
298
+ 만약 공식 훈련 예제에 기여하는 경우, [examples/test_examples.py](https://github.com/huggingface/diffusers/blob/main/examples/test_examples.py)에 테스트를 추가하는 것도 확인해주세요. 비공식 훈련 예제에는 이 작업이 필요하지 않습니다.
299
+
300
+ ### 8. "Good second issue" 고치기 [[8-fixing-a-good-second-issue]]
301
+
302
+ "Good second issue"는 [Good second issue](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22Good+second+issue%22) 라벨로 표시됩니다. Good second issue는 [Good first issues](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22)보다 해결하기가 더 복잡합니다.
303
+ 이슈 설명은 일반적으로 이슈를 해결하는 방법에 대해 덜 구체적이며, 관심 있는 기여자는 라이브러리에 대한 꽤 깊은 이해가 필요합니다.
304
+ Good second issue를 해결하고자 하는 경우, 해당 이슈를 해결하기 위해 PR을 열고 PR을 이슈에 링크하세요. 이미 해당 이슈에 대한 PR이 열려있지만 병합되지 않은 경우, 왜 병합되지 않았는지 이해하기 위해 살펴보고 개선된 PR을 열어보세요.
305
+ Good second issue는 일반적으로 Good first issue 이슈보다 병합하기가 더 어려우므로, 핵심 메인테이너에게 도움을 요청하는 것이 좋습니다. PR이 거의 완료된 경우, 핵심 메인테이너는 PR에 참여하여 커밋하고 병합을 진행할 수 있습니다.
306
+
307
+ ### 9. 파이프라인, 모델, 스케줄러 추가하기 [[9-adding-pipelines-models-schedulers]]
308
+
309
+ 파이프라인, 모델, 스케줄러는 Diffusers 라이브러리에서 가장 중요한 부분입니다.
310
+ 이들은 최첨단 diffusion 기술에 쉽게 접근하도록 하며, 따라서 커뮤니티가 강력한 생성형 AI 애플리케이션을 만들 수 있도록 합니다.
311
+
312
+ 새로운 모델, 파이프라인 또는 스케줄러를 추가함으로써, 사용자 인터페이스에 새로운 강력한 사용 사례를 활성화할 수 있으며, 이는 전체 생성형 AI 생태계에 매우 중요한 가치를 제공할 수 있습니다.
313
+
314
+ Diffusers에는 세 가지 구성 요소에 대한 여러 개발 요청이 있습니다. 특정 구성 요소를 아직 정확히 어떤 것을 추가하고 싶은지 모르는 경우, 다음 링크를 참조하세요:
315
+ - [모델 또는 파이프라인](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22New+pipeline%2Fmodel%22)
316
+ - [스케줄러](https://github.com/huggingface/diffusers/issues?q=is%3Aopen+is%3Aissue+label%3A%22New+scheduler%22)
317
+
318
+
319
+ 세 가지 구성 요소를 추가하기 전에, [철학 가이드](philosophy)를 읽어보는 것을 강력히 권장합니다. 세 가지 구성 요소 중 어느 것을 추가하든, 디자인 철학과 관련된 API 일관성을 유지하기 위해 우리의 디자인 철학과 크게 다른 구성 요소는 병합할 수 없습니다. 디자인 선택에 근본적으로 동의하지 않는 경우, [피드백 이슈](https://github.com/huggingface/diffusers/issues/new?assignees=&labels=&template=feedback.md&title=)를 열어 해당 디자인 패턴/선택이 라이브러리 전체에서 변경되어야 하는지, 디자인 철학을 업데이트해야 하는지에 대해 논의할 수 있습니다. 라이브러리 전체의 일관성은 우리에게 매우 중요합니다.
320
+
321
+ PR에 원본 코드베이스/논문 링크를 추가하고, 가능하면 PR에서 원래 작성자에게 직접 알림을 보내어 진행 상황을 따라갈 수 있도록 해주세요.
322
+
323
+ PR에서 막힌 경우나 도움이 필요한 경우, 첫 번째 리뷰나 도움을 요청하는 메시지를 남기는 것을 주저하지 마세요.
324
+
325
+ #### Copied from mechanism [[copied-from-mechanism]]
326
+
327
+ `# Copied from mechanism` 은 파이프라인, 모델 또는 스케줄러 코드를 추가할 때 이해해야 할 독특하고 중요한 기능입니다. 이것은 Diffusers 코드베이스 전반에서 볼 수 있으며, 이를 사용하는 이유는 코드베이스를 이해하고 유지 관리하기 쉽게 만들기 위해서입니다. `# Copied from mechanism` 으로 표시된 코드는 복사한 코드와 정확히 동일하도록 강제됩니다. 이렇게 하면 `make fix-copies`를 실행할 때마다 여러 파일에 걸쳐 변경 사항을 쉽게 업데이트하고 전파할 수 있습니다.
328
+
329
+ 예를 들어, 아래 코드 예제에서 [`~diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput`]은 원래 코드이며, `AltDiffusionPipelineOutput`은 `# Copied from mechanism`을 사용하여 복사합니다. 유일한 차이점은 클래스 접두사를 `Stable`에서 `Alt`로 변경한 것입니다.
330
+
331
+ ```py
332
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_output.StableDiffusionPipelineOutput with Stable->Alt
333
+ class AltDiffusionPipelineOutput(BaseOutput):
334
+ """
335
+ Output class for Alt Diffusion pipelines.
336
+
337
+ Args:
338
+ images (`List[PIL.Image.Image]` or `np.ndarray`)
339
+ List of denoised PIL images of length `batch_size` or NumPy array of shape `(batch_size, height, width,
340
+ num_channels)`.
341
+ nsfw_content_detected (`List[bool]`)
342
+ List indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content or
343
+ `None` if safety checking could not be performed.
344
+ """
345
+ ```
346
+
347
+ 더 자세히 알고 싶다면 [~Don't~ Repeat Yourself*](https://huggingface.co/blog/transformers-design-philosophy#4-machine-learning-models-are-static) 블로그 포스트의 이 섹션을 읽어보세요.
348
+
349
+ ## 좋은 이슈 작성 방법 [[how-to-write-a-good-issue]]
350
+
351
+ **이슈를 잘 작성할수록 빠르게 해결될 가능성이 높아집니다.**
352
+
353
+ 1. 이슈에 적절한 템플릿을 사용했는지 확인하세요. [새 이슈를 열 때](https://github.com/huggingface/diffusers/issues/new/choose) 올바른 템플릿을 선택해야 합니다. *버그 보고서*, *기능 요청*, *API 디자인에 대한 피드백*, *새로운 모델/파이프라인/스케줄러 추가*, *포럼*, 또는 빈 이슈 중에서 선택하세요. 이슈를 열 때 올바른 템플릿을 선택하는 것이 중요합니다.
354
+ 2. **명확성**: 이슈에 적합한 제목을 지정하세요. 이슈 설명을 가능한 간단하게 작성하세요. 이슈를 이해하고 해결하는 데 걸리는 시간을 줄이기 위해 가능한 한 명확하게 작성하세요. 하나의 이슈에 대해 여러 문제를 포함하지 않도록 주의하세요. 여러 문제를 발견한 경우, 각각의 이슈를 개별적으로 열어주세요. 버그인 경우, 어떤 버그인지 가능한 한 정확하게 설명해야 합니다. "diffusers에서 오류"와 같이 간단히 작성하지 마세요.
355
+ 3. **재현 가능성**: 재현 가능한 코드 조각이 없으면 해결할 수 없습니다. 버그를 발견한 경우, 유지 관리자는 그 버그를 재현할 수 있어야 합니다. 이슈에 재현 가능한 코드 조각을 포함해야 합니다. 코드 조각은 Python 인터프리터에 복사하여 붙여넣을 수 있는 형태여야 합니다. 코드 조각이 작동해야 합니다. 즉, 누락된 import나 이미지에 대한 링크가 없어야 합니다. 이슈에는 오류 메시지와 정확히 동일한 오류 메시지를 재현하기 위해 수정하지 않고 복사하여 붙여넣을 수 있는 코드 조각이 포함되어야 합니다. 이슈에 사용자의 로컬 모델 가중치나 로컬 데이터를 사용하는 경우, 독자가 액세스할 수 없는 경우 이슈를 해결할 수 없습니다. 데이터나 모델을 공유할 수 없는 경우, 더미 모델이나 더미 데이터를 만들어 사용해보세요.
356
+ 4. **간결성**: 가능한 한 간결하게 유지하여 독자가 문제를 빠르게 이해할 수 있도록 도와주세요. 문제와 관련이 없는 코드나 정보는 모두 제거해주세요. 버그를 발견한 경우, 문제를 설명하는 가장 간단한 코드 예제를 만들어보세요. 버그를 발견한 후에는 작업 흐름 전체를 문제에 던지는 것이 아니라, 에러가 발생하는 훈련 코드의 어느 부분이 문제인지 먼저 이해하고 몇 줄로 재현해보세요. 전체 데이터셋 대신 더미 데이터를 사용해보세요.
357
+ 5. 링크 추가하기. 특정한 이름, 메서드, 또는 모델을 참조하는 경우, 독자가 더 잘 이해할 수 있도록 링크를 제공해주세요. 특정 PR이나 이슈를 참조하는 경우, 해당 이슈에 링크를 걸어주세요. 독자가 무엇을 말하는지 알고 있다고 가정하지 마세요. 이슈에 링크를 추가할수록 좋습니다.
358
+ 6. 포맷팅. 코드를 파이썬 코드 구문으로, 에러 메시지를 일반 코드 구문으로 형식화하여 이슈를 깔끔하게 작성하세요. 자세한 내용은 [GitHub 공식 포맷팅 문서](https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax)를 참조하세요.
359
+ 7. 여러분의 이슈를 단순히 해결해야 할 티켓으로 생각하지 말고, 잘 작성된 백과사전 항목으로 생각해보세요. 추가된 모든 이슈는 공개적으로 이용 가능한 지식에 대한 기여입니다. 잘 작성된 이슈를 추가함으로써 메인테이너가 여러분의 이슈를 더 쉽게 해결할 수 있게 할 뿐만 아니라, 전체 커뮤니티가 라이브러리의 특정 측면을 더 잘 이해할 수 있도록 도움을 주게 됩니다.
360
+
361
+ ## 좋은 PR 작성 방법 [[how-to-write-a-good-pr]]
362
+
363
+ 1. 카멜레온이 되세요. 기존의 디자인 패턴과 구문을 이해하고, 여러분이 추가하는 코드가 기존 코드베이스와 자연스럽게 어우러지도록 해야 합니다. 기존 디자인 패턴이나 사용자 인터페이스와 크게 다른 Pull Request들은 병합되지 않습니다.
364
+ 2. 레이저처럼 집중하세요. Pull Request는 하나의 문제, 오직 하나의 문제만 해결해야 합니다. "이왕 추가하는 김에 다른 문제도 고치자"는 함정에 빠지지 않도록 주의하세요. 여러 개의 관련 없는 문제를 해결하는 한 번에 해결하는 Pull Request들은 검토하기가 훨씬 더 어렵습니다.
365
+ 3. 도움이 되는 경우, 추가한 내용이 어떻게 사용되는지 예제 코드 조각을 추가해보세요.
366
+ 4. Pull Request의 제목은 기여 내용을 요약해야 합니다.
367
+ 5. Pull Request가 이슈를 해결하는 경우, Pull Request의 설명에 이슈 번호를 언급하여 연결되도록 해주세요 (이슈를 참조하는 사람들이 작업 중임을 알 수 있도록).
368
+ 6. 진행 중인 작업을 나타내려면 제목에 `[WIP]`를 접두사로 붙여주세요. 이는 중복 작업을 피하고, 병합 준비가 된 PR과 구분할 수 있도록 도움이 됩니다.
369
+ 7. [좋은 이슈를 작성하는 방법](#how-to-write-a-good-issue)에 설명된 대로 텍스트를 구성하고 형식을 지정해보세요.
370
+ 8. 기존 테스트가 통과하는지 확인하세요
371
+ 9. 높은 커버리지를 가진 테스트를 추가하세요. 품질 테스트가 없으면 병합할 수 없습니다.
372
+ - 새로운 `@slow` 테스트를 추가하는 경우, 다음 명령을 사용하여 통과하는지 확인하세요.
373
+ `RUN_SLOW=1 python -m pytest tests/test_my_new_model.py`.
374
+ CircleCI는 느린 테스트를 실행하지 않지만, GitHub Actions는 매일 실행합니다!
375
+ 10. 모든 공개 메서드는 마크다운과 잘 작동하는 정보성 docstring을 가져야 합니다. 예시로 [`pipeline_latent_diffusion.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py)를 참조하세요.
376
+ 11. 리포지토리가 빠르게 성장하고 있기 때문에, 리포지토리에 큰 부담을 주는 파일이 추가되지 않도록 주의해야 합니다. 이미지, 비디오 및 기타 텍스트가 아닌 파일을 포함합니다. 이러한 파일을 배치하기 위해 hf.co 호스팅 `dataset`인 [`hf-internal-testing`](https://huggingface.co/hf-internal-testing) 또는 [huggingface/documentation-images](https://huggingface.co/datasets/huggingface/documentation-images)를 활용하는 것이 우선입니다.
377
+ 외부 기여인 경우, 이미지를 PR에 추가하고 Hugging Face 구성원에게 이미지를 이 데이터셋으로 이동하도록 요청하세요.
378
+
379
+ ## PR을 열기 위한 방법 [[how-to-open-a-pr]]
380
+
381
+ 코드를 작성하기 전에, 이미 누군가가 같은 작업을 하고 있는지 확인하기 위해 기존의 PR이나 이슈를 검색하는 것이 좋습니다. 확실하지 않은 경우, 피드백을 받기 위해 이슈를 열어보는 것이 항상 좋은 아이디어입니다.
382
+
383
+ 🧨 Diffusers에 기여하기 위해서는 기본적인 `git` 사용법을 알아야 합니다. `git`은 가장 쉬운 도구는 아니지만, 가장 훌륭한 매뉴얼을 가지고 있습니다. 셸에서 `git --help`을 입력하고 즐기세요. 책을 선호하는 경우, [Pro Git](https://git-scm.com/book/en/v2)은 매우 좋은 참고 자료입니다.
384
+
385
+ 다음 단계를 따라 기여를 시작하세요 ([지원되는 Python 버전](https://github.com/huggingface/diffusers/blob/main/setup.py#L244)):
386
+
387
+ 1. 저장소 페이지에서 'Fork' 버튼을 클릭하여 [저장소](https://github.com/huggingface/diffusers)를 포크합니다. 이렇게 하면 코드의 사본이 GitHub 사용자 계정에 생성됩니다.
388
+
389
+ 2. 포크한 저장소를 로컬 디스크에 클론하고, 기본 저장소를 원격으로 추가하세요:
390
+
391
+ ```bash
392
+ $ git clone git@github.com:<your GitHub handle>/diffusers.git
393
+ $ cd diffusers
394
+ $ git remote add upstream https://github.com/huggingface/diffusers.git
395
+ ```
396
+
397
+ 3. 개발 변경 사항을 보관할 새로운 브랜치를 생성하세요:
398
+
399
+ ```bash
400
+ $ git checkout -b a-descriptive-name-for-my-changes
401
+ ```
402
+
403
+ `main` 브랜치 위에서 **절대** 작업하지 마세요.
404
+
405
+ 4. 가상 환경에서 다음 명령을 실행하여 개발 환경을 설정하세요:
406
+
407
+ ```bash
408
+ $ pip install -e ".[dev]"
409
+ ```
410
+
411
+ 만약 저장소를 이미 클론한 경우, 가장 최신 변경 사항을 가져오기 위해 `git pull`을 실행해야 할 수도 있습니다.
412
+
413
+ 5. 기능을 브랜치에서 개발하세요.
414
+
415
+ 기능을 작업하는 동안 테스트 스위트가 통과되는지 확인해야 합니다. 다음과 같이 변경 사항에 영향을 받는 테스트를 실행해야 합니다:
416
+
417
+ ```bash
418
+ $ pytest tests/<TEST_TO_RUN>.py
419
+ ```
420
+
421
+ 테스트를 실행하기 전에 테스트를 위해 필요한 의존성들을 설치하였는지 확인하세요. 다음의 커맨드를 통해서 확인할 수 있습니다:
422
+
423
+ ```bash
424
+ $ pip install -e ".[test]"
425
+ ```
426
+
427
+ 다음 명령어로 전체 테스트 묶음 실행할 수도 있지만, Diffusers가 많이 성장하였기 때문에 결과를 적당한 시간 내에 생성하기 위해서는 강력한 컴퓨터가 필요합니다. 다음은 해당 명령어입니다:
428
+
429
+ ```bash
430
+ $ make test
431
+ ```
432
+
433
+ 🧨 Diffusers는 소스 코드를 일관되게 포맷팅하기 위해 `black`과 `isort`를 사용합니다. 변경 사항을 적용한 후에는 다음과 같이 자동 스타일 수정 및 코드 검증을 적용할 수 있습니다:
434
+
435
+
436
+ ```bash
437
+ $ make style
438
+ ```
439
+
440
+ 🧨 Diffusers `ruff`와 몇개의 커스텀 스크립트를 이용하여 코딩 실수를 확인합니다. 품질 제어는 CI에서 작동하지만, 동일한 검사를 다음을 통해서도 할 수 있습니다:
441
+
442
+ ```bash
443
+ $ make quality
444
+ ```
445
+
446
+ 변경사항에 대해 만족한다면 `git add`를 사용하여 변경된 파일을 추가하고 `git commit`을 사용하여 변경사항에 대해 로컬상으로 저장���다:
447
+
448
+ ```bash
449
+ $ git add modified_file.py
450
+ $ git commit -m "A descriptive message about your changes."
451
+ ```
452
+
453
+ 코드를 정기적으로 원본 저장소와 동기화하는 것은 좋은 아이디어입니다. 이렇게 하면 변경 사항을 빠르게 반영할 수 있습니다:
454
+
455
+ ```bash
456
+ $ git pull upstream main
457
+ ```
458
+
459
+ 변경 사항을 계정에 푸시하려면 다음을 사용하세요:
460
+
461
+ ```bash
462
+ $ git push -u origin a-descriptive-name-for-my-changes
463
+ ```
464
+
465
+ 6. 만족하셨다면, GitHub에서 포크한 웹페이지로 이동하여 'Pull request'를 클릭하여 변경사항을 프로젝트 메인테이너에게 검토를 요청합니다.
466
+
467
+ 7. 메인테이너가 변경 사항을 요청하는 것은 괜찮습니다. 핵심 기여자들에게도 일어나는 일입니다! 따라서 변경 사항을 Pull request에서 볼 수 있도록 로컬 브랜치에서 작업하고 변경 사항을 포크에 푸시하면 자동으로 Pull request에 나타납니다.
468
+
469
+ ### 테스트 [[tests]]
470
+
471
+ 라이브러리 동작과 여러 예제를 테스트하기 위해 포괄적인 테스트 묶음이 포함되어 있습니다. 라이브러리 테스트는 [tests 폴더](https://github.com/huggingface/diffusers/tree/main/tests)에서 찾을 수 있습니다.
472
+
473
+ `pytest`와 `pytest-xdist`를 선호하는 이유는 더 빠르기 때문입니다. 루트 디렉토리에서 라이브러리를 위해 `pytest`로 테스트를 실행하는 방법은 다음과 같습니다:
474
+
475
+ ```bash
476
+ $ python -m pytest -n auto --dist=loadfile -s -v ./tests/
477
+ ```
478
+
479
+ 사실, `make test`는 이렇게 구현되어 있습니다!
480
+
481
+ 작업 중인 기능만 테스트하기 위해 더 작은 테스트 세트를 지정할 수 있습니다.
482
+
483
+ 기본적으로 느린 테스트는 건너뜁니다. `RUN_SLOW` 환경 변수를 `yes`로 설정하여 실행할 수 있습니다. 이는 많은 기가바이트의 모델을 다운로드합니다. 충분한 디스크 공간과 좋은 인터넷 연결 또는 많은 인내심이 필요합니다!
484
+
485
+ ```bash
486
+ $ RUN_SLOW=yes python -m pytest -n auto --dist=loadfile -s -v ./tests/
487
+ ```
488
+
489
+ `unittest`는 완전히 지원됩니다. 다음은 `unittest`를 사용하여 테스트를 실행하는 방법입니다:
490
+
491
+ ```bash
492
+ $ python -m unittest discover -s tests -t . -v
493
+ $ python -m unittest discover -s examples -t examples -v
494
+ ```
495
+
496
+ ### upstream(HuggingFace) main과 forked main 동기화하기 [[syncing-forked-main-with-upstream-huggingface-main]]
497
+
498
+ upstream 저장소에 불필요한 참조 노트를 추가하고 관련 개발자에게 알림을 보내는 것을 피하기 위해,
499
+ forked 저장소의 main 브랜치를 동기화할 때 다음 단계를 따르세요:
500
+ 1. 가능한 경우, forked 저장소에서 브랜치와 PR을 사용하여 upstream과 동기화하는 것을 피하세요. 대신 forked main으로 직접 병합하세요.
501
+ 2. PR이 절대적으로 필요한 경우, 브랜치를 체크아웃한 후 다음 단계를 사용하세요:
502
+ ```bash
503
+ $ git checkout -b your-branch-for-syncing
504
+ $ git pull --squash --no-commit upstream main
505
+ $ git commit -m '<your message without GitHub references>'
506
+ $ git push --set-upstream origin your-branch-for-syncing
507
+ ```
508
+
509
+ ### 스타일 가이드 [[style-guide]]
510
+
511
+ Documentation string에 대해서는, 🧨 Diffusers는 [Google 스타일](https://google.github.io/styleguide/pyguide.html)을 따릅니다.
tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/ko/conceptual/ethical_guidelines.md ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # 🧨 Diffusers의 윤리 지침 [[-diffusers-ethical-guidelines]]
14
+
15
+ ## 서문 [[preamble]]
16
+
17
+ [Diffusers](https://huggingface.co/docs/diffusers/index)는 사전 훈련된 diffusion 모델을 제공하며, 추론과 훈련을 위한 모듈형 툴박스로 활용됩니다.
18
+
19
+ 이 기술의 실제 적용 사례와 사회에 미칠 수 있는 잠재적 부정적 영향을 고려할 때, Diffusers 라이브러리의 개발, 사용자 기여, 사용에 윤리 지침을 제공하는 것이 중요하다고 생각합니다.
20
+
21
+ 이 기술 사용과 관련된 위험은 여전히 검토 중이지만, 예를 들면: 예술가의 저작권 문제, 딥페이크 악용, 부적절한 맥락에서의 성적 콘텐츠 생성, 비동의 사칭, 소수자 집단 억압을 영속화하는 유해한 사회적 편견 등이 있습니다.
22
+ 우리는 이러한 위험을 지속적으로 추적하고, 커뮤니티의 반응과 소중한 피드백에 따라 아래 지침을 조정할 것입니다.
23
+
24
+ ## 범위 [[scope]]
25
+
26
+ Diffusers 커뮤니티는 프로젝트 개발에 다음 윤리 지침을 적용하며, 특히 윤리적 문제와 관련된 민감한 주제에 대해 커뮤니티의 기여를 조정하는 데 도움을 줄 것입니다.
27
+
28
+ ## 윤리 지침 [[ethical-guidelines]]
29
+
30
+ 다음 윤리 지침은 일반적으로 적용되지만, 윤리적으로 민감한 문제와 관련된 기술적 선택을 할 때 우선적으로 적용됩니다. 또한, 해당 기술의 최신 동향과 관련된 새로운 위험이 발생함에 따라 이러한 윤리 원칙을 지속적으로 조정할 것을 약속합니다.
31
+
32
+ - **투명성**: 우리는 PR 관리, 사용자에게 선택의 이유 설명, 기술적 의사결정 과정에서 투명성을 유지할 것을 약속합니다.
33
+
34
+ - **일관성**: 프로젝트 관리에서 모든 사용자에게 동일한 수준의 관심을 보장하고, 기술적으로 안정적이고 일관된 상태를 유지할 것을 약속합니다.
35
+
36
+ - **간결성**: Diffusers 라이브러리를 쉽게 사용하고 활용할 수 있도록, 프로젝트의 목표를 간결하고 일관성 있게 유지할 것을 약속합니다.
37
+
38
+ - **접근성**: Diffusers 프로젝트는 기술적 전문지식이 없어도 기여할 수 있도록 진입장벽을 낮춥니다. 이를 통해 연구 결과물이 커뮤니티에 더 잘 접근될 수 있습니다.
39
+
40
+ - **재현성**: 우리는 Diffusers 라이브러리를 통해 제공되는 업스트림 코드, 모델, 데이터셋의 재현성에 대해 투명하게 공개하는 것을 목표로 합니다.
41
+
42
+ - **책임**: 커뮤니티와 팀워크를 통해, 이 기술의 잠재적 위험을 예측하고 완화하는 데 공동 책임을 집니다.
43
+
44
+ ## 구현 사례: 안전 기능과 메커니즘 [[examples-of-implementations-safety-features-and-mechanisms]]
45
+
46
+ 팀은 diffusion 기술과 관련된 잠재적 윤리 및 사회적 위험에 대응하기 위해 기술적·비기술적 도구를 제공하고자 노력하고 있습니다. 또한, 커뮤니티의 참여는 이러한 기능 구현과 인식 제고에 매우 중요합니다.
47
+
48
+ - [**커뮤니티 탭**](https://huggingface.co/docs/hub/repositories-pull-requests-discussions): 커뮤니티가 프로젝트에 대해 토론하고 더 나은 협업을 할 수 있도록 지원합니다.
49
+
50
+ - **편향 탐색 및 평가**: Hugging Face 팀은 Stable Diffusion 모델의 편향성을 대화형으로 보여주는 [space](https://huggingface.co/spaces/society-ethics/DiffusionBiasExplorer)를 제공합니다. 우리는 이러한 편향 탐색과 평가를 지원하고 장려합니다.
51
+
52
+ - **배포에서의 안전 유도**
53
+
54
+ - [**안전한 Stable Diffusion**](https://huggingface.co/docs/diffusers/main/en/api/pipelines/stable_diffusion/stable_diffusion_safe): 필터링되지 않은 웹 크롤링 데이터셋으로 훈련된 Stable Diffusion과 같은 모델이 부적절하게 변질되는 문제를 완화합니다. 관련 논문: [Safe Latent Diffusion: Mitigating Inappropriate Degeneration in Diffusion Models](https://huggingface.co/papers/2211.05105).
55
+
56
+ - [**안전 검사기**](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/safety_checker.py): 생성된 이미지가 임베딩 공간에서 하드코딩된 유해 개념 클래스와 일치할 확률을 확인하고 비교합니다. 유해 개념은 역공학을 방지하기 위해 의도적으로 숨겨져 있습니다.
57
+
58
+ - **Hub에서의 단계적 배포**: 특히 민감한 상황에서는 일부 리포지토리에 대한 접근을 제한할 수 있습니다. 단계적 배포는 리포지토리 작성자가 사용에 대해 더 많은 통제권을 갖도록 하는 중간 단계입니다.
59
+
60
+ - **라이선싱**: [OpenRAILs](https://huggingface.co/blog/open_rail)와 같은 새로운 유형의 라이선스를 통해 자유로운 접근을 보장하면서도 보다 책임 있는 사용을 위한 일련의 제한을 둘 수 있습니다.
tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/ko/conceptual/evaluation.md ADDED
@@ -0,0 +1,542 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Diffusion 모델 평가하기[[evaluating-diffusion-models]]
14
+
15
+ <a target="_blank" href="https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/evaluation.ipynb">
16
+ <img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/>
17
+ </a>
18
+
19
+ [Stable Diffusion](https://huggingface.co/docs/diffusers/stable_diffusion)와 같은 생성 모델의 평가는 주관적인 성격을 가지고 있습니다. 그러나 실무자와 연구자로서 우리는 종종 다양한 가능성 중에서 신중한 선택을 해야 합니다. 그래서 다양한 생성 모델 (GAN, Diffusion 등)을 사용할 때 어떻게 선택해야 할까요?
20
+
21
+ 정성적인 평가는 모델의 이미지 품질에 대한 주관적인 평가이므로 오류가 발생할 수 있고 결정에 잘못된 영향을 미칠 수 있습니다. 반면, 정량적인 평가는 이미지 품질과 직접적인 상관관계를 갖지 않을 수 있습니다. 따라서 일반적으로 정성적 평가와 정량적 평가를 모두 고려하는 것이 더 강력한 신호를 제공하여 모델 선택에 도움이 됩니다.
22
+
23
+ 이 문서에서는 Diffusion 모델을 평가하기 위한 정성적 및 정량적 방법에 대해 상세히 설명합니다. 정량적 방법에 대해서는 특히 `diffusers`와 함께 구현하는 방법에 초점을 맞추었습니다.
24
+
25
+ 이 문서에서 보여진 방법들은 기반 생성 모델을 고정시키고 다양한 [노이즈 스케줄러](https://huggingface.co/docs/diffusers/main/en/api/schedulers/overview)를 평가하는 데에도 사용할 수 있습니다.
26
+
27
+ ## 시나리오[[scenarios]]
28
+ 다음과 같은 파이프라인을 사용하여 Diffusion 모델을 다룹니다:
29
+
30
+ - 텍스트로 안내된 이미지 생성 (예: [`StableDiffusionPipeline`](https://huggingface.co/docs/diffusers/main/en/api/pipelines/stable_diffusion/text2img)).
31
+ - 입력 이미지에 추가로 조건을 건 텍스트로 안내된 이미지 생성 (예: [`StableDiffusionImg2ImgPipeline`](https://huggingface.co/docs/diffusers/main/en/api/pipelines/stable_diffusion/img2img) 및 [`StableDiffusionInstructPix2PixPipeline`](https://huggingface.co/docs/diffusers/main/en/api/pipelines/pix2pix)).
32
+ - 클래스 조건화된 이미지 생성 모델 (예: [`DiTPipeline`](https://huggingface.co/docs/diffusers/main/en/api/pipelines/dit)).
33
+
34
+ ## 정성적 평가[[qualitative-evaluation]]
35
+
36
+ 정성적 평가는 일반적으로 생성된 이미지의 인간 평가를 포함합니다. 품질은 구성성, 이미지-텍스트 일치, 공간 관계 등과 같은 측면에서 측정됩니다. 일반적인 프롬프트는 주관적인 지표에 대한 일정한 기준을 제공합니다.
37
+ DrawBench와 PartiPrompts는 정성적인 벤치마킹에 사용되는 프롬프트 데이터셋입니다. DrawBench와 PartiPrompts는 각각 [Imagen](https://imagen.research.google/)과 [Parti](https://parti.research.google/)에서 소개되었습니다.
38
+
39
+ [Parti 공식 웹사이트](https://parti.research.google/)에서 다음과 같이 설명하고 있습니다:
40
+
41
+ > PartiPrompts (P2)는 이 작업의 일부로 공개되는 영어로 된 1600개 이상의 다양한 프롬프트 세트입니다. P2는 다양한 범주와 도전 측면에서 모델의 능력을 측정하는 데 사용할 수 있습니다.
42
+
43
+ ![parti-prompts](https://huggingface.co/datasets/diffusers/docs-images/resolve/main/evaluation_diffusion_models/parti-prompts.png)
44
+
45
+ PartiPrompts는 다음과 같은 열을 가지고 있습니다:
46
+
47
+ - 프롬프트 (Prompt)
48
+ - 프롬프트의 카테고리 (예: "Abstract", "World Knowledge" 등)
49
+ - 난이도를 반영한 챌린지 (예: "Basic", "Complex", "Writing & Symbols" 등)
50
+
51
+ 이러한 벤치마크는 서로 다른 이미지 생성 모델을 인간 평가로 비교할 수 있도록 합니다.
52
+
53
+ 이를 위해 🧨 Diffusers 팀은 **Open Parti Prompts**를 구축했습니다. 이는 Parti Prompts를 기반으로 한 커뮤니티 기반의 질적 벤치마크로, 최첨단 오픈 소스 확산 모델을 비교하는 데 사용됩니다:
54
+ - [Open Parti Prompts 게임](https://huggingface.co/spaces/OpenGenAI/open-parti-prompts): 10개의 parti prompt에 대해 4개의 생성된 이미지가 제시되며, 사용자는 프롬프트에 가장 적합한 이미지를 선택합니다.
55
+ - [Open Parti Prompts 리더보드](https://huggingface.co/spaces/OpenGenAI/parti-prompts-leaderboard): 현재 최고의 오픈 소스 diffusion 모델들을 서로 비교하는 리더보드입니다.
56
+
57
+ 이미지를 수동으로 비교하려면, `diffusers`를 사용하여 몇가지 PartiPrompts를 어떻게 활용할 수 있는지 알아봅시다.
58
+
59
+ 다음은 몇 가지 다른 도전에서 샘플링한 프롬프트를 보여줍니다: Basic, Complex, Linguistic Structures, Imagination, Writing & Symbols. 여기서는 PartiPrompts를 [데이터셋](https://huggingface.co/datasets/nateraw/parti-prompts)으로 사용합니다.
60
+
61
+ ```python
62
+ from datasets import load_dataset
63
+
64
+ # prompts = load_dataset("nateraw/parti-prompts", split="train")
65
+ # prompts = prompts.shuffle()
66
+ # sample_prompts = [prompts[i]["Prompt"] for i in range(5)]
67
+
68
+ # Fixing these sample prompts in the interest of reproducibility.
69
+ sample_prompts = [
70
+ "a corgi",
71
+ "a hot air balloon with a yin-yang symbol, with the moon visible in the daytime sky",
72
+ "a car with no windows",
73
+ "a cube made of porcupine",
74
+ 'The saying "BE EXCELLENT TO EACH OTHER" written on a red brick wall with a graffiti image of a green alien wearing a tuxedo. A yellow fire hydrant is on a sidewalk in the foreground.',
75
+ ]
76
+ ```
77
+ 이제 이런 프롬프트를 사용하여 Stable Diffusion ([v1-4 checkpoint](https://huggingface.co/CompVis/stable-diffusion-v1-4))를 사용한 이미지 생성을 할 수 있습니다 :
78
+
79
+ ```python
80
+ import torch
81
+
82
+ seed = 0
83
+ generator = torch.manual_seed(seed)
84
+
85
+ images = sd_pipeline(sample_prompts, num_images_per_prompt=1, generator=generator).images
86
+ ```
87
+
88
+ ![parti-prompts-14](https://huggingface.co/datasets/diffusers/docs-images/resolve/main/evaluation_diffusion_models/parti-prompts-14.png)
89
+
90
+
91
+ `num_images_per_prompt`를 설정하여 동일한 프롬프트에 대해 다른 이미지를 비교할 수도 있습니다. 다른 체크포인트([v1-5](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5))로 동일한 파이프라인을 실행하면 다음과 같은 결과가 나옵니다:
92
+
93
+ ![parti-prompts-15](https://huggingface.co/datasets/diffusers/docs-images/resolve/main/evaluation_diffusion_models/parti-prompts-15.png)
94
+
95
+
96
+ 다양한 모델을 사용하여 모든 프롬프트에서 생성된 여러 이미지들이 생성되면 (평가 과정에서) 이러한 결과물들은 사람 평가자들에게 점수를 매기기 위해 제시됩니다. DrawBench와 PartiPrompts 벤치마크에 대한 자세한 내용은 각각의 논문을 참조하십시오.
97
+
98
+ > [!TIP]
99
+ > 모델이 훈련 중일 때 추론 샘플을 살펴보는 것은 훈련 진행 상황을 측정하는 데 유용합니다. [훈련 스크립트](https://github.com/huggingface/diffusers/tree/main/examples/)에서는 TensorBoard와 Weights & Biases에 대한 추가 지원과 함께 이 유틸리티를 지원합니다.
100
+
101
+ ## 정량적 평가[[quantitative-evaluation]]
102
+
103
+ 이 섹션에서는 세 가지 다른 확산 파이프라인을 평가하는 방법을 안내합니다:
104
+
105
+ - CLIP 점수
106
+ - CLIP 방향성 유사도
107
+ - FID
108
+
109
+ ### 텍스트 안내 이미지 생성[[text-guided-image-generation]]
110
+
111
+ [CLIP 점수](https://huggingface.co/papers/2104.08718)는 이미지-캡션 쌍의 호환성을 측정합니다. 높은 CLIP 점수는 높은 호환성🔼을 나타냅니다. CLIP 점수는 이미지와 캡션 사이의 의미적 유사성으로 생각할 수도 있습니다. CLIP 점수는 인간 판단과 높은 상관관계를 가지고 있습니다.
112
+
113
+ [`StableDiffusionPipeline`]을 일단 로드해봅시다:
114
+
115
+ ```python
116
+ from diffusers import StableDiffusionPipeline
117
+ import torch
118
+
119
+ model_ckpt = "CompVis/stable-diffusion-v1-4"
120
+ sd_pipeline = StableDiffusionPipeline.from_pretrained(model_ckpt, torch_dtype=torch.float16).to("cuda")
121
+ ```
122
+
123
+ 여러 개의 프롬프트를 사용하여 이미지를 생성합니다:
124
+
125
+ ```python
126
+ prompts = [
127
+ "a photo of an astronaut riding a horse on mars",
128
+ "A high tech solarpunk utopia in the Amazon rainforest",
129
+ "A pikachu fine dining with a view to the Eiffel Tower",
130
+ "A mecha robot in a favela in expressionist style",
131
+ "an insect robot preparing a delicious meal",
132
+ "A small cabin on top of a snowy mountain in the style of Disney, artstation",
133
+ ]
134
+
135
+ images = sd_pipeline(prompts, num_images_per_prompt=1, output_type="np").images
136
+
137
+ print(images.shape)
138
+ # (6, 512, 512, 3)
139
+ ```
140
+
141
+ 그러고 나서 CLIP 점수를 계산합니다.
142
+
143
+ ```python
144
+ from torchmetrics.functional.multimodal import clip_score
145
+ from functools import partial
146
+
147
+ clip_score_fn = partial(clip_score, model_name_or_path="openai/clip-vit-base-patch16")
148
+
149
+ def calculate_clip_score(images, prompts):
150
+ images_int = (images * 255).astype("uint8")
151
+ clip_score = clip_score_fn(torch.from_numpy(images_int).permute(0, 3, 1, 2), prompts).detach()
152
+ return round(float(clip_score), 4)
153
+
154
+ sd_clip_score = calculate_clip_score(images, prompts)
155
+ print(f"CLIP score: {sd_clip_score}")
156
+ # CLIP score: 35.7038
157
+ ```
158
+
159
+ 위의 예제에서는 각 프롬프트 당 하나의 이미지를 생성했습니다. 만약 프롬프트 당 여러 이미지를 생성한다면, 프롬프트 당 생성된 이미지의 평균 점수를 사용해야 합니다.
160
+
161
+ 이제 [`StableDiffusionPipeline`]과 호환되는 두 개의 체크포인트를 비교하려면, 파이프라인을 호출할 때 generator를 전달해야 합니다. 먼저, 고정된 시드로 [v1-4 Stable Diffusion 체크포인트](https://huggingface.co/CompVis/stable-diffusion-v1-4)를 사용하여 이미지를 생성합니다:
162
+
163
+ ```python
164
+ seed = 0
165
+ generator = torch.manual_seed(seed)
166
+
167
+ images = sd_pipeline(prompts, num_images_per_prompt=1, generator=generator, output_type="np").images
168
+ ```
169
+
170
+ 그런 다음 [v1-5 checkpoint](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5)를 로드하여 이미지를 생성합니다:
171
+
172
+ ```python
173
+ model_ckpt_1_5 = "stable-diffusion-v1-5/stable-diffusion-v1-5"
174
+ sd_pipeline_1_5 = StableDiffusionPipeline.from_pretrained(model_ckpt_1_5, torch_dtype=weight_dtype).to(device)
175
+
176
+ images_1_5 = sd_pipeline_1_5(prompts, num_images_per_prompt=1, generator=generator, output_type="np").images
177
+ ```
178
+
179
+ 그리고 마지막으로 CLIP 점수를 비교합니다:
180
+
181
+ ```python
182
+ sd_clip_score_1_4 = calculate_clip_score(images, prompts)
183
+ print(f"CLIP Score with v-1-4: {sd_clip_score_1_4}")
184
+ # CLIP Score with v-1-4: 34.9102
185
+
186
+ sd_clip_score_1_5 = calculate_clip_score(images_1_5, prompts)
187
+ print(f"CLIP Score with v-1-5: {sd_clip_score_1_5}")
188
+ # CLIP Score with v-1-5: 36.2137
189
+ ```
190
+
191
+ [v1-5](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5) 체크포인트가 이전 버전보다 더 나은 성능을 보이는 것 같습니다. 그러나 CLIP 점수를 계산하기 위해 사용한 프롬프트의 수가 상당히 적습니다. 보다 실용적인 평가를 위해서는 이 수를 훨씬 높게 설정하고, 프롬프트를 다양하게 사용해야 합니다.
192
+
193
+ > [!WARNING]
194
+ > 이 점수에는 몇 가지 제한 사항이 있습니다. 훈련 데이터셋의 캡션은 웹에서 크롤링되어 이미지와 관련된 `alt` 및 유사한 태그에서 추출되었습니다. 이들은 인간이 이미지를 설명하는 데 사용할 수 있는 것과 일치하지 않을 수 있습니다. 따라서 여기서는 몇 가지 프롬프트를 "엔지니어링"해야 했습니다.
195
+
196
+ ### 이미지 조건화된 텍스트-이미지 생성[[image-conditioned-text-to-image-generation]]
197
+
198
+ 이 경우, 생성 파이프라인을 입력 이미지와 텍스트 프롬프트로 조건화합니다. [`StableDiffusionInstructPix2PixPipeline`]을 예로 들어보겠습니다. 이는 편집 지시문을 입력 프롬프트로 사용하고 편집할 입력 이미지를 사용합니다.
199
+
200
+ 다음은 하나의 예시입니다:
201
+
202
+ ![edit-instruction](https://huggingface.co/datasets/diffusers/docs-images/resolve/main/evaluation_diffusion_models/edit-instruction.png)
203
+
204
+ 모델을 평가하는 한 가지 전략은 두 이미지 캡션 간의 변경과([CLIP-Guided Domain Adaptation of Image Generators](https://huggingface.co/papers/2108.00946)에서 보여줍니다) 함께 두 이미지 사이의 변경의 일관성을 측정하는 것입니다 ([CLIP](https://huggingface.co/docs/transformers/model_doc/clip) 공간에서). 이를 "**CLIP 방향성 유사성**"이라고 합니다.
205
+
206
+ - 캡션 1은 편집할 이미지 (이미지 1)에 해당합니다.
207
+ - 캡션 2는 편집된 이미지 (이미지 2)에 해당합니다. 편집 지시를 반영해야 합니다.
208
+
209
+ 다음은 그림으로 된 개요입니다:
210
+
211
+ ![edit-consistency](https://huggingface.co/datasets/diffusers/docs-images/resolve/main/evaluation_diffusion_models/edit-consistency.png)
212
+
213
+ 우리는 이 측정 항목을 구현하기 위해 미니 데이터 세트를 준비했습니다. 먼저 데이터 세트를 로드해 보겠습니다.
214
+
215
+ ```python
216
+ from datasets import load_dataset
217
+
218
+ dataset = load_dataset("sayakpaul/instructpix2pix-demo", split="train")
219
+ dataset.features
220
+ ```
221
+
222
+ ```bash
223
+ {'input': Value(dtype='string', id=None),
224
+ 'edit': Value(dtype='string', id=None),
225
+ 'output': Value(dtype='string', id=None),
226
+ 'image': Image(decode=True, id=None)}
227
+ ```
228
+
229
+ 여기에는 다음과 같은 항목이 있습니다:
230
+
231
+ - `input`은 `image`에 해당하는 캡션입니다.
232
+ - `edit`은 편집 지시사항을 나타냅니다.
233
+ - `output`은 `edit` 지시사항을 반영한 수정된 캡션입니다.
234
+
235
+ 샘플을 살펴보겠습니다.
236
+
237
+ ```python
238
+ idx = 0
239
+ print(f"Original caption: {dataset[idx]['input']}")
240
+ print(f"Edit instruction: {dataset[idx]['edit']}")
241
+ print(f"Modified caption: {dataset[idx]['output']}")
242
+ ```
243
+
244
+ ```bash
245
+ Original caption: 2. FAROE ISLANDS: An archipelago of 18 mountainous isles in the North Atlantic Ocean between Norway and Iceland, the Faroe Islands has 'everything you could hope for', according to Big 7 Travel. It boasts 'crystal clear waterfalls, rocky cliffs that seem to jut out of nowhere and velvety green hills'
246
+ Edit instruction: make the isles all white marble
247
+ Modified caption: 2. WHITE MARBLE ISLANDS: An archipelago of 18 mountainous white marble isles in the North Atlantic Ocean between Norway and Iceland, the White Marble Islands has 'everything you could hope for', according to Big 7 Travel. It boasts 'crystal clear waterfalls, rocky cliffs that seem to jut out of nowhere and velvety green hills'
248
+ ```
249
+
250
+ 다음은 이미지입니다:
251
+
252
+ ```python
253
+ dataset[idx]["image"]
254
+ ```
255
+
256
+ ![edit-dataset](https://huggingface.co/datasets/diffusers/docs-images/resolve/main/evaluation_diffusion_models/edit-dataset.png)
257
+
258
+ 먼저 편집 지시사항을 사용하여 데이터 세트의 이미지를 편집하고 방향 유사도를 계산합니다.
259
+
260
+ [`StableDiffusionInstructPix2PixPipeline`]를 먼저 로드합니다:
261
+
262
+ ```python
263
+ from diffusers import StableDiffusionInstructPix2PixPipeline
264
+
265
+ instruct_pix2pix_pipeline = StableDiffusionInstructPix2PixPipeline.from_pretrained(
266
+ "timbrooks/instruct-pix2pix", torch_dtype=torch.float16
267
+ ).to(device)
268
+ ```
269
+
270
+ 이제 편집을 수행합니다:
271
+
272
+ ```python
273
+ import numpy as np
274
+
275
+
276
+ def edit_image(input_image, instruction):
277
+ image = instruct_pix2pix_pipeline(
278
+ instruction,
279
+ image=input_image,
280
+ output_type="np",
281
+ generator=generator,
282
+ ).images[0]
283
+ return image
284
+
285
+ input_images = []
286
+ original_captions = []
287
+ modified_captions = []
288
+ edited_images = []
289
+
290
+ for idx in range(len(dataset)):
291
+ input_image = dataset[idx]["image"]
292
+ edit_instruction = dataset[idx]["edit"]
293
+ edited_image = edit_image(input_image, edit_instruction)
294
+
295
+ input_images.append(np.array(input_image))
296
+ original_captions.append(dataset[idx]["input"])
297
+ modified_captions.append(dataset[idx]["output"])
298
+ edited_images.append(edited_image)
299
+ ```
300
+ 방향 유사도를 계산하기 위해서는 먼저 CLIP의 이미지와 텍스트 인코더를 로드합니다:
301
+
302
+ ```python
303
+ from transformers import (
304
+ CLIPTokenizer,
305
+ CLIPTextModelWithProjection,
306
+ CLIPVisionModelWithProjection,
307
+ CLIPImageProcessor,
308
+ )
309
+
310
+ clip_id = "openai/clip-vit-large-patch14"
311
+ tokenizer = CLIPTokenizer.from_pretrained(clip_id)
312
+ text_encoder = CLIPTextModelWithProjection.from_pretrained(clip_id).to(device)
313
+ image_processor = CLIPImageProcessor.from_pretrained(clip_id)
314
+ image_encoder = CLIPVisionModelWithProjection.from_pretrained(clip_id).to(device)
315
+ ```
316
+
317
+ 주목할 점은 특정한 CLIP 체크포인트인 `openai/clip-vit-large-patch14`를 사용하고 있다는 것입니다. 이는 Stable Diffusion 사전 훈련이 이 CLIP 변형체와 함께 수행되었기 때문입니다. 자세한 내용은 [문서](https://huggingface.co/docs/transformers/model_doc/clip)를 참조하세요.
318
+
319
+ 다음으로, 방향성 유사도를 계산하기 위해 PyTorch의 `nn.Module`을 준비합니다:
320
+
321
+ ```python
322
+ import torch.nn as nn
323
+ import torch.nn.functional as F
324
+
325
+
326
+ class DirectionalSimilarity(nn.Module):
327
+ def __init__(self, tokenizer, text_encoder, image_processor, image_encoder):
328
+ super().__init__()
329
+ self.tokenizer = tokenizer
330
+ self.text_encoder = text_encoder
331
+ self.image_processor = image_processor
332
+ self.image_encoder = image_encoder
333
+
334
+ def preprocess_image(self, image):
335
+ image = self.image_processor(image, return_tensors="pt")["pixel_values"]
336
+ return {"pixel_values": image.to(device)}
337
+
338
+ def tokenize_text(self, text):
339
+ inputs = self.tokenizer(
340
+ text,
341
+ max_length=self.tokenizer.model_max_length,
342
+ padding="max_length",
343
+ truncation=True,
344
+ return_tensors="pt",
345
+ )
346
+ return {"input_ids": inputs.input_ids.to(device)}
347
+
348
+ def encode_image(self, image):
349
+ preprocessed_image = self.preprocess_image(image)
350
+ image_features = self.image_encoder(**preprocessed_image).image_embeds
351
+ image_features = image_features / image_features.norm(dim=1, keepdim=True)
352
+ return image_features
353
+
354
+ def encode_text(self, text):
355
+ tokenized_text = self.tokenize_text(text)
356
+ text_features = self.text_encoder(**tokenized_text).text_embeds
357
+ text_features = text_features / text_features.norm(dim=1, keepdim=True)
358
+ return text_features
359
+
360
+ def compute_directional_similarity(self, img_feat_one, img_feat_two, text_feat_one, text_feat_two):
361
+ sim_direction = F.cosine_similarity(img_feat_two - img_feat_one, text_feat_two - text_feat_one)
362
+ return sim_direction
363
+
364
+ def forward(self, image_one, image_two, caption_one, caption_two):
365
+ img_feat_one = self.encode_image(image_one)
366
+ img_feat_two = self.encode_image(image_two)
367
+ text_feat_one = self.encode_text(caption_one)
368
+ text_feat_two = self.encode_text(caption_two)
369
+ directional_similarity = self.compute_directional_similarity(
370
+ img_feat_one, img_feat_two, text_feat_one, text_feat_two
371
+ )
372
+ return directional_similarity
373
+ ```
374
+
375
+ 이제 `DirectionalSimilarity`를 사용해 보겠습니다.
376
+
377
+ ```python
378
+ dir_similarity = DirectionalSimilarity(tokenizer, text_encoder, image_processor, image_encoder)
379
+ scores = []
380
+
381
+ for i in range(len(input_images)):
382
+ original_image = input_images[i]
383
+ original_caption = original_captions[i]
384
+ edited_image = edited_images[i]
385
+ modified_caption = modified_captions[i]
386
+
387
+ similarity_score = dir_similarity(original_image, edited_image, original_caption, modified_caption)
388
+ scores.append(float(similarity_score.detach().cpu()))
389
+
390
+ print(f"CLIP directional similarity: {np.mean(scores)}")
391
+ # CLIP directional similarity: 0.0797976553440094
392
+ ```
393
+
394
+ CLIP 점수와 마찬가지로, CLIP 방향 유사성이 높을수록 좋습니다.
395
+
396
+ `StableDiffusionInstructPix2PixPipeline`은 `image_guidance_scale`과 `guidance_scale`이라는 두 가지 인자를 노출시킵니다. 이 두 인자를 조정하여 최종 편집된 이미지의 품질을 제어할 수 있습니다. 이 두 인자의 영향을 실험해보고 방향 유사성에 미치는 영향을 확인해보기를 권장합니다.
397
+
398
+ 이러한 메트릭의 개념을 확장하여 원본 이미지와 편집된 버전의 유사성을 측정할 수 있습니다. 이를 위해 `F.cosine_similarity(img_feat_two, img_feat_one)`을 사용할 수 있습니다. 이러한 종류의 편집에서는 이미지의 주요 의미가 최대한 보존되어야 합니다. 즉, 높은 유사성 점수를 얻어야 합니다.
399
+
400
+ [`StableDiffusionPix2PixZeroPipeline`](https://huggingface.co/docs/diffusers/main/en/api/pipelines/pix2pix_zero#diffusers.StableDiffusionPix2PixZeroPipeline)와 같은 유사한 파이프라인에도 이러한 메트릭을 사용할 수 있습니다.
401
+
402
+ > [!TIP]
403
+ > CLIP 점수와 CLIP 방향 유사성 모두 CLIP 모델에 의존하기 때문에 평가가 편향될 수 있습니다
404
+
405
+ ***IS, FID (나중에 설명할 예정), 또는 KID와 같은 메트릭을 확장하는 것은 어려울 수 있습니다***. 평가 중인 모델이 대규모 이미지 캡셔닝 데이터셋 (예: [LAION-5B 데이터셋](https://laion.ai/blog/laion-5b/))에서 사전 훈련되었을 때 이는 문제가 될 수 있습니다. 왜냐하면 이러한 메트릭의 기반에는 중간 이미지 특징을 추출하기 위해 ImageNet-1k 데이터셋에서 사전 훈련된 InceptionNet이 사용되기 때문입니다. Stable Diffusion의 사전 훈련 데이터셋은 InceptionNet의 사전 훈련 데이터셋과 겹치는 부분이 제한적일 수 있으므로 따라서 여기에는 좋은 후보가 아닙니다.
406
+
407
+ ***위의 메트릭을 사용하면 클래스 조건이 있는 모델을 평가할 수 있습니다. 예를 들어, [DiT](https://huggingface.co/docs/diffusers/main/en/api/pipelines/dit). 이는 ImageNet-1k 클래스에 조건을 걸고 사전 훈련되었습니다.***
408
+
409
+ ### 클래스 조건화 이미지 생성[[class-conditioned-image-generation]]
410
+
411
+ 클래스 조건화 생성 모델은 일반적으로 [ImageNet-1k](https://huggingface.co/datasets/imagenet-1k)와 같은 클래스 레이블이 지정된 데이터셋에서 사전 훈련됩니다. 이러한 모델을 평가하는 인기있는 지표에는 Fréchet Inception Distance (FID), Kernel Inception Distance (KID) 및 Inception Score (IS)가 있습니다. 이 문서에서는 FID ([Heusel et al.](https://huggingface.co/papers/1706.08500))에 초점을 맞추고 있습니다. [`DiTPipeline`](https://huggingface.co/docs/diffusers/api/pipelines/dit)을 사용하여 FID를 계산하는 방법을 보여줍니다. 이는 내부적으로 [DiT 모델](https://huggingface.co/papers/2212.09748)을 사용합니다.
412
+
413
+ FID는 두 개의 이미지 데이터셋이 얼마나 유사한지를 측정하는 것을 목표로 합니다. [이 자료](https://mmgeneration.readthedocs.io/en/latest/quick_run.html#fid)에 따르면:
414
+
415
+ > Fréchet Inception Distance는 두 개의 이미지 데이터셋 간의 유사성을 측정하는 지표입니다. 시각적 품질에 대한 인간 판단과 잘 상관되는 것으로 나타났으며, 주로 생성적 적대 신경망의 샘플 품질을 평가하는 데 사용됩니다. FID는 Inception 네트워크의 특징 표현에 맞게 적합한 두 개의 가우시안 사이의 Fréchet 거리를 계산하여 구합니다.
416
+
417
+ 이 두 개의 데이터셋은 실제 이미지 데이터셋과 가짜 이미지 데이터셋(우리의 경우 생성된 이미지)입니다. FID는 일반적으로 두 개의 큰 데이터셋으로 계산됩니다. 그러나 이 문서에서는 두 개의 미니 데이터셋으로 작업할 것입니다.
418
+
419
+ 먼저 ImageNet-1k 훈련 세트에서 몇 개의 이미지를 다운로드해 봅시다:
420
+
421
+ ```python
422
+ from zipfile import ZipFile
423
+ import requests
424
+
425
+
426
+ def download(url, local_filepath):
427
+ r = requests.get(url)
428
+ with open(local_filepath, "wb") as f:
429
+ f.write(r.content)
430
+ return local_filepath
431
+
432
+ dummy_dataset_url = "https://hf.co/datasets/sayakpaul/sample-datasets/resolve/main/sample-imagenet-images.zip"
433
+ local_filepath = download(dummy_dataset_url, dummy_dataset_url.split("/")[-1])
434
+
435
+ with ZipFile(local_filepath, "r") as zipper:
436
+ zipper.extractall(".")
437
+ ```
438
+
439
+ ```python
440
+ from PIL import Image
441
+ import os
442
+
443
+ dataset_path = "sample-imagenet-images"
444
+ image_paths = sorted([os.path.join(dataset_path, x) for x in os.listdir(dataset_path)])
445
+
446
+ real_images = [np.array(Image.open(path).convert("RGB")) for path in image_paths]
447
+ ```
448
+
449
+ 다음은 ImageNet-1k classes의 이미지 10개입니다 : "cassette_player", "chain_saw" (x2), "church", "gas_pump" (x3), "parachute" (x2), 그리고 "tench".
450
+
451
+ <p align="center">
452
+ <img src="https://huggingface.co/datasets/diffusers/docs-images/resolve/main/evaluation_diffusion_models/real-images.png" alt="real-images"><br>
453
+ <em>Real images.</em>
454
+ </p>
455
+
456
+ 이제 이미지가 로드되었으므로 이미지에 가벼운 전처리를 적용하여 FID 계산에 사용해 보겠습니다.
457
+
458
+ ```python
459
+ from torchvision.transforms import functional as F
460
+
461
+
462
+ def preprocess_image(image):
463
+ image = torch.tensor(image).unsqueeze(0)
464
+ image = image.permute(0, 3, 1, 2) / 255.0
465
+ return F.center_crop(image, (256, 256))
466
+
467
+ real_images = torch.cat([preprocess_image(image) for image in real_images])
468
+ print(real_images.shape)
469
+ # torch.Size([10, 3, 256, 256])
470
+ ```
471
+
472
+ 이제 위에서 언급한 클래스에 따라 조건화 된 이미지를 생성하기 위해 [`DiTPipeline`](https://huggingface.co/docs/diffusers/api/pipelines/dit)를 로드합니다.
473
+
474
+ ```python
475
+ from diffusers import DiTPipeline, DPMSolverMultistepScheduler
476
+
477
+ dit_pipeline = DiTPipeline.from_pretrained("facebook/DiT-XL-2-256", torch_dtype=torch.float16)
478
+ dit_pipeline.scheduler = DPMSolverMultistepScheduler.from_config(dit_pipeline.scheduler.config)
479
+ dit_pipeline = dit_pipeline.to("cuda")
480
+
481
+ words = [
482
+ "cassette player",
483
+ "chainsaw",
484
+ "chainsaw",
485
+ "church",
486
+ "gas pump",
487
+ "gas pump",
488
+ "gas pump",
489
+ "parachute",
490
+ "parachute",
491
+ "tench",
492
+ ]
493
+
494
+ class_ids = dit_pipeline.get_label_ids(words)
495
+ output = dit_pipeline(class_labels=class_ids, generator=generator, output_type="np")
496
+
497
+ fake_images = output.images
498
+ fake_images = torch.tensor(fake_images)
499
+ fake_images = fake_images.permute(0, 3, 1, 2)
500
+ print(fake_images.shape)
501
+ # torch.Size([10, 3, 256, 256])
502
+ ```
503
+
504
+ 이제 [`torchmetrics`](https://torchmetrics.readthedocs.io/)를 사용하여 FID를 계산할 수 있습니다.
505
+
506
+ ```python
507
+ from torchmetrics.image.fid import FrechetInceptionDistance
508
+
509
+ fid = FrechetInceptionDistance(normalize=True)
510
+ fid.update(real_images, real=True)
511
+ fid.update(fake_images, real=False)
512
+
513
+ print(f"FID: {float(fid.compute())}")
514
+ # FID: 177.7147216796875
515
+ ```
516
+
517
+ FID는 낮을수록 좋습니다. 여러 가지 요소가 FID에 영향을 줄 수 있습니다:
518
+
519
+ - 이미지의 수 (실제 이미지와 가짜 이미지 모두)
520
+ - diffusion 과정에서 발생하는 무작위성
521
+ - diffusion 과정에서의 추론 단계 수
522
+ - diffusion 과정에서 사용되는 스케줄러
523
+
524
+ 마지막 두 가지 요소에 대해서는, 다른 시드와 추론 단계에서 평가를 실행하고 평균 결과를 보고하는 것은 좋은 실천 방법입니다
525
+
526
+ > [!WARNING]
527
+ > FID 결과는 많은 요소에 의존하기 때문에 취약할 수 있습니다:
528
+ >
529
+ > * 계산 중 사용되는 특정 Inception 모델.
530
+ > * 계산의 구현 정확도.
531
+ > * 이미지 형식 (PNG 또는 JPG에서 시작하는 경우가 다릅니다).
532
+ >
533
+ > 이러한 사항을 염두에 두면, FID는 유사한 실행을 비교할 때 가장 유용하지만, 저자가 FID 측정 코드를 주의 깊게 공개하지 않는 한 논문 결과를 재현하기는 어렵습니다.
534
+ >
535
+ > 이러한 사항은 KID 및 IS와 같은 다른 관련 메트릭에도 적용됩니다.
536
+
537
+ 마지막 단계로, `fake_images`를 시각적으로 검사해 봅시다.
538
+
539
+ <p align="center">
540
+ <img src="https://huggingface.co/datasets/diffusers/docs-images/resolve/main/evaluation_diffusion_models/fake-images.png" alt="fake-images"><br>
541
+ <em>Fake images.</em>
542
+ </p>
tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/ko/conceptual/philosophy.md ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # 철학 [[philosophy]]
14
+
15
+ 🧨 Diffusers는 다양한 모달리티에서 **최신의** 사전 훈련된 diffusion 모델을 제공합니다.
16
+ 그 목적은 추론과 훈련을 위한 **모듈식 툴박스**로 사용되는 것입니다.
17
+
18
+ 저희는 시간이 지나도 변치 않는 라이브러리를 구축하는 것을 목표로 하기에 API 설계를 매우 중요하게 생각합니다.
19
+
20
+ 간단히 말해서, Diffusers는 PyTorch를 자연스럽게 확장할 수 있도록 만들어졌습니다. 따라서 대부분의 설계 선택은 [PyTorch의 설계 원칙](https://pytorch.org/docs/stable/community/design.html#pytorch-design-philosophy)에 기반합니다. 이제 가장 중요한 것들을 살펴보겠습니다:
21
+
22
+ ## 성능보다는 사용성을 [[usability-over-performance]]
23
+
24
+ - Diffusers는 다양한 성능 향상 기능이 내장되어 있지만 (자세한 내용은 [메모리와 속도](https://huggingface.co/docs/diffusers/optimization/fp16) 참조), 모델은 항상 가장 높은 정밀도와 최소한의 최적화로 로드됩니다. 따라서 사용자가 별도로 정의하지 않는 한 기본적으로 diffusion 파이프라인은 항상 float32 정밀도로 CPU에 인스턴스화됩니다. 이는 다양한 플랫폼과 가속기에서의 사용성을 보장하며, 라이브러리를 실행하기 위해 복잡한 설치가 필요하지 않다는 것을 의미합니다.
25
+ - Diffusers는 **가벼운** 패키지를 지향하기 때문에 필수 종속성은 거의 없지만 성능을 향상시킬 수 있는 많은 선택적 종속성이 있습니다 (`accelerate`, `safetensors`, `onnx` 등). 저희는 라이브러리를 가능한 한 가볍게 유지하여 다른 패키지에 대한 종속성 걱정이 없도록 노력하고 있습니다.
26
+ - Diffusers는 간결하고 이해하기 쉬운 코드를 선호합니다. 이는 람다 함수나 고급 PyTorch 연산자와 같은 압축된 코드 구문을 자주 사용하지 않는 것을 의미합니다.
27
+
28
+ ## 쉬움보다는 간단함을 [[simple-over-easy]]
29
+
30
+ PyTorch에서는 **명시적인 것이 암시적인 것보다 낫다**와 **단순한 것이 복잡한 것보다 낫다**라고 말합니다. 이 설계 철학은 라이브러리의 여러 부분에 반영되어 있습니다:
31
+ - [`DiffusionPipeline.to`](https://huggingface.co/docs/diffusers/main/en/api/diffusion_pipeline#diffusers.DiffusionPipeline.to)와 같은 메소드를 사용하여 사용자가 장치 관리를 할 수 있도록 PyTorch의 API를 따릅니다.
32
+ - 잘못된 입력을 조용히 수정하는 대신 간결한 오류 메시지를 발생시키는 것이 우선입니다. Diffusers는 라이브러리를 가능한 한 쉽게 사용할 수 있도록 하는 것보다 사용자를 가르치는 것을 목표로 합니다.
33
+ - 복잡한 모델과 스케줄러 로직이 내부에서 마법처럼 처리하는 대신 노출됩니다. 스케줄러/샘플러는 서로에게 최소한의 종속성을 가지고 분리되어 있습니다. 이로써 사용자는 언롤된 노이즈 제거 루프를 작성해야 합니다. 그러나 이 분리는 디버깅을 더 쉽게하고 노이즈 제거 과정을 조정하거나 diffusers 모델이나 스케줄러를 교체하는 데 사용자에게 더 많은 제어권을 제공합니다.
34
+ - diffusers 파이프라인의 따로 훈련된 구성 요소인 text encoder, unet 및 variational autoencoder는 각각 자체 모델 클래스를 갖습니다. 이로써 사용자는 서로 다른 모델의 구성 요소 간의 상호 작용을 처리해야 하며, 직렬화 형식은 모델 구성 요소를 다른 파일로 분리합니다. 그러나 이는 디버깅과 커스터마이징을 더 쉽게합니다. DreamBooth나 Textual Inversion 훈련은 Diffusers의 'diffusion 파이프라인의 단일 구성 요소들을 분리할 수 있는 능력' 덕분에 매우 간단합니다.
35
+
36
+ ## 추상화보다는 수정 가능하고 기여하기 쉬움을 [[tweakable-contributor-friendly-over-abstraction]]
37
+
38
+ 라이브러리의 대부분에 대해 Diffusers는 [Transformers 라이브러리](https://github.com/huggingface/transformers)의 중요한 설계 원칙을 채택합니다, 바로 성급한 추상화보다는 copy-pasted 코드를 선호한다는 것입니다. 이 설계 원칙은 [Don't repeat yourself (DRY)](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself)와 같은 인기 있는 설계 원칙과는 대조적으로 매우 의견이 분분한데요.
39
+ 간단히 말해서, Transformers가 모델링 파일에 대해 수행하는 것처럼, Diffusers는 매우 낮은 수준의 추상화와 매우 독립적인 코드를 유지하는 것을 선호합니다. 함수, 긴 코드 블록, 심지어 클래스도 여러 파일에 복사할 수 있으며, 이는 처음에는 라이브러리를 유지할 수 없게 만드는 나쁜, 서투른 설계 선택으로 보일 수 있습니다. 하지만 이러한 설계는 매우 성공적이며, 커뮤니티 기반의 오픈 소스 기계 학습 라이브러리에 매우 적합합니다. 그 이유는 다음과 같습니다:
40
+ - 기계 학습은 패러다임, 모델 아키텍처 및 알고리즘이 빠르게 변화하는 매우 빠르게 움직이는 분야이기 때문에 오랜 기간 지속되는 코드 추상화를 정의하기가 매우 어렵습니다.
41
+ - 기계 학습 전문가들은 아이디어와 연구를 위해 기존 코드를 빠르게 조정할 수 있어야 하므로, 많은 추상화보다는 독립적인 코드를 선호합니다.
42
+ - 오픈 소스 라이브러리는 커뮤니티 기여에 의존하므로, 기여하기 쉬운 라이브러리를 구축해야 합니다. 코드가 추상화되면 의존성이 많아지고 읽기 어렵고 기여하기 어려워집니다. 기여자들은 중요한 기능을 망가뜨릴까 두려워하여 매우 추상화된 라이브러리에 기여하지 않게 됩니다. 라이브러리에 기여하는 것이 다른 기본 코드를 망가뜨릴 수 없다면, 잠재적인 새로운 기여자에게 더욱 환영받을 수 있을 뿐만 아니라 여러 부분에 대해 병렬적으로 검토하고 기여하기가 더 쉬워집니다.
43
+
44
+ Hugging Face에서는 이 설계를 **단일 파일 정책**이라고 부르며, 특정 클래스의 대부분의 코드가 단일하고 독립적인 파일에 작성되어야 한다는 의미입니다. 철학에 대해 자세히 알아보려면 [이 블로그 글](https://huggingface.co/blog/transformers-design-philosophy)을 참조할 수 있습니다.
45
+
46
+ Diffusers에서는 이러한 철학을 파이프라인과 스케줄러에 모두 따르지만, diffusion 모델에 대해서는 일부만 따릅니다. 일부만 따르는 이유는 Diffusion 파이프라인인 [DDPM](https://huggingface.co/docs/diffusers/api/pipelines/ddpm), [Stable Diffusion](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/overview#stable-diffusion-pipelines), [unCLIP (DALL·E 2)](https://huggingface.co/docs/diffusers/api/pipelines/unclip) 및 [Imagen](https://imagen.research.google/) 등 대부분의 diffusion 파이프라인은 동일한 diffusion 모델인 [UNet](https://huggingface.co/docs/diffusers/api/models/unet2d-cond)에 의존하기 때문입니다.
47
+
48
+ 좋아요, 이제 🧨 Diffusers가 설계된 방식을 대략적으로 이해했을 것입니다 🤗.
49
+ 우리는 이러한 설계 원칙을 일관되게 라이브러리 전체에 적용하려고 노력하고 있습니다. 그럼에도 불구하고 철학에 대한 일부 예외 사항이나 불행한 설계 선택이 있을 수 있습니다. 디자인에 대한 피드백이 있다면 [GitHub에서 직접](https://github.com/huggingface/diffusers/issues/new?assignees=&labels=&template=feedback.md&title=) 알려주시면 감사하겠습니다.
50
+
51
+ ## 디자인 철학 자세히 알아보기 [[design-philosophy-in-details]]
52
+
53
+ 이제 디자인 철학의 세부 사항을 좀 더 자세히 살펴보겠습니다. Diffusers는 주로 세 가지 주요 클래스로 구성됩니다: [파이프라인](https://github.com/huggingface/diffusers/tree/main/src/diffusers/pipelines), [모델](https://github.com/huggingface/diffusers/tree/main/src/diffusers/models), 그리고 [스케줄러](https://github.com/huggingface/diffusers/tree/main/src/diffusers/schedulers). 각 클래스에 대한 더 자세한 설계 결정 사항을 살펴보겠습니다.
54
+
55
+ ### 파이프라인 [[pipelines]]
56
+
57
+ 파이프라인은 사용하기 쉽도록 설계되었으며 (따라서 [*쉬움보다는 간단함을*](#쉬움보다는-간단함을)을 100% 따르지는 않음), feature-complete하지 않으며, 추론을 위한 [모델](#모델)과 [스케줄러](#스케줄러)를 사용하는 방법의 예시로 간주될 수 있습니다.
58
+
59
+ 다음과 같은 설계 원칙을 따릅니다:
60
+ - 파이프라인은 단일 파일 정책을 따릅니다. 모든 파이프라인은 src/diffusers/pipelines의 개별 디렉토리에 있습니다. 하나의 파이프라인 폴더는 하나의 diffusion 논문/프로젝트/릴리스에 해당합니다. 여러 파이프라인 파일은 하나의 파이프라인 폴더에 모을 수 있습니다. 예를 들어 [`src/diffusers/pipelines/stable-diffusion`](https://github.com/huggingface/diffusers/tree/main/src/diffusers/pipelines/stable_diffusion)에서 그렇게 하고 있습니다. 파이프라인이 유사한 기능을 공유하는 경우, [# Copied from mechanism](https://github.com/huggingface/diffusers/blob/125d783076e5bd9785beb05367a2d2566843a271/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py#L251)을 사용할 수 있습니다.
61
+ - 파이프라인은 모두 [`DiffusionPipeline`]을 상속합니다.
62
+ - 각 파이프라인은 서로 다른 모델 및 스케줄러 구성 요소로 구성되어 있으며, 이는 [`model_index.json` 파일](https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5/blob/main/model_index.json)에 문서화되어 있으며, 파이프라인의 속성 이름과 동일한 이름으로 액세스할 수 있으며, [`DiffusionPipeline.components`](https://huggingface.co/docs/diffusers/main/en/api/diffusion_pipeline#diffusers.DiffusionPipeline.components) 함수를 통해 파이프라인 간에 공유할 수 있습니다.
63
+ - 각 파이프라인은 [`DiffusionPipeline.from_pretrained`](https://huggingface.co/docs/diffusers/main/en/api/diffusion_pipeline#diffusers.DiffusionPipeline.from_pretrained) 함수를 통해 로드할 수 있어야 합니다.
64
+ - 파이프라인은 추론에**만** 사용되어야 합니다.
65
+ - 파이프라인은 매우 가독성이 좋고, 이해하기 쉽고, 쉽게 조정할 수 있도록 설계되어야 합니다.
66
+ - 파이프라인은 서로 상호작용하고, 상위 수준 API에 쉽게 통합할 수 있도록 설계되어야 합니다.
67
+ - 파이프라인은 사용자 인터페이스가 feature-complete하지 않게 하는 것을 목표로 합니다. future-complete한 사용자 인터페이스를 원한다면 [InvokeAI](https://github.com/invoke-ai/InvokeAI), [Diffuzers](https://github.com/abhishekkrthakur/diffuzers), [lama-cleaner](https://github.com/Sanster/lama-cleaner)를 참조해야 합니다.
68
+ - 모든 파이프라인은 오로지 `__call__` 메소드를 통해 실행할 수 있어야 합니다. `__call__` 인자의 이름은 모든 파이프라인에서 공유되어야 합니다.
69
+ - 파이프라인은 해결하고자 하는 작업의 이름으로 지정되어야 합니다.
70
+ - 대부분의 경우에 새로운 diffusion 파이프라인은 새로운 파이프라인 폴더/파일에 구현되어야 합니다.
71
+
72
+ ### 모델 [[models]]
73
+
74
+ 모델은 [PyTorch의 Module 클래스](https://pytorch.org/docs/stable/generated/torch.nn.Module.html)의 자연스러운 확장이 되도록, 구성 가능한 툴박스로 설계되었습니다. 그리고 모델은 **단일 파일 정책**을 일부만 따릅니다.
75
+
76
+ 다음과 같은 설계 원칙을 따릅니다:
77
+ - 모델은 **모델 아키텍처 유형**에 해당합니다. 예를 들어 [`UNet2DConditionModel`] 클래스는 2D 이미지 입력을 기대하고 일부 context에 의존하는 모든 UNet 변형들에 사용됩니다.
78
+ - 모든 모델은 [`src/diffusers/models`](https://github.com/huggingface/diffusers/tree/main/src/diffusers/models)에서 찾을 수 있으며, 각 모델 아키텍처는 해당 파일에 정의되어야 합니다. 예를 들어 [`unet_2d_condition.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/unet_2d_condition.py), [`transformer_2d.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/transformer_2d.py) 등이 있습니다.
79
+ - 모델은 **단일 파일 정책**을 따르지 않으며, [`attention.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention.py), [`resnet.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/resnet.py), [`embeddings.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/embeddings.py) 등과 같은 작은 모델 구성 요소를 사용해야 합니다. **참고**: 이는 Transformers의 모델링 파일과는 대조적으로 모델이 실제로 단일 파일 정책을 따르지 않음을 보여줍니다.
80
+ - 모델은 PyTorch의 `Module` 클래스와 마찬가지로 복잡성을 노출하고 명확한 오류 메시지를 제공해야 합니다.
81
+ - 모든 모델은 `ModelMixin`과 `ConfigMixin`을 상속합니다.
82
+ - 모델은 주요 코드 변경이 필요하지 않고, 역호환성을 유지하며, 메모리 또는 컴퓨팅과 관련한 중요한 이득을 제공할 때 성능을 위해 최적화할 수 있습니다.
83
+ - 모델은 기본적으로 가장 높은 정밀도와 가장 낮은 성능 설정을 가져야 합니다.
84
+ - Diffusers에 이미 있는 모델 아키텍처로 분류할 수 있는 새로운 모델 체크포인트를 통합할 때는 기존 모델 아키텍처를 새로운 체크포인트와 호환되도록 수정해야 합니다. 새로운 파일을 만들어야 하는 경우는 모델 아키텍처가 근본적으로 다른 경우에만 해당합니다.
85
+ - 모델은 미래의 변경 사항을 쉽게 확장할 수 있도록 설계되어야 합니다. 이는 공개 함수 인수들과 구성 인수들을 제한하고,미래의 변경 사항을 "예상"하는 것을 통해 달성할 수 있습니다. 예를 들어, 불리언 `is_..._type` 인수보다는 새로운 미래 유형에 쉽게 확장할 수 있는 문자열 "...type" 인수를 추가하는 것이 일반적으로 더 좋습니다. 새로운 모델 체크포인트가 작동하도록 하기 위해 기존 아키텍처에 최소한의 변경만을 가해야 합���다.
86
+ - 모델 디자인은 코드의 가독성과 간결성을 유지하는 것과 많은 모델 체크포인트를 지원하는 것 사이의 어려운 균형 조절입니다. 모델링 코드의 대부분은 새로운 모델 체크포인트를 위해 클래스를 수정하는 것이 좋지만, [UNet 블록](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/unet_2d_blocks.py) 및 [Attention 프로세서](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py)와 같이 코드를 장기적으로 간결하고 읽기 쉽게 유지하기 위해 새로운 클래스를 추가하는 예외도 있습니다.
87
+
88
+ ### 스케줄러 [[schedulers]]
89
+
90
+ 스케줄러는 추론을 위한 노이즈 제거 과정을 안내하고 훈련을 위한 노이즈 스케줄을 정의하는 역할을 합니다. 스케줄러는 개별 클래스로 설계되어 있으며, 로드 가능한 구성 파일과 **단일 파일 정책**을 엄격히 따릅니다.
91
+
92
+ 다음과 같은 설계 원칙을 따릅니다:
93
+ - 모든 스케줄러는 [`src/diffusers/schedulers`](https://github.com/huggingface/diffusers/tree/main/src/diffusers/schedulers)에서 찾을 수 있습니다.
94
+ - 스케줄러는 큰 유틸리티 파일에서 가져오지 **않아야** 하며, 자체 포함성을 유지해야 합니다.
95
+ - 하나의 스케줄러 Python 파일은 하나의 스케줄러 알고리즘(논문에서 정의된 것과 같은)에 해당합니다.
96
+ - 스케줄러가 유사한 기능을 공유하는 경우, `# Copied from` 메커니즘을 사용할 수 있습니다.
97
+ - 모든 스케줄러는 `SchedulerMixin`과 `ConfigMixin`을 상속합니다.
98
+ - [`ConfigMixin.from_config`](https://huggingface.co/docs/diffusers/main/en/api/configuration#diffusers.ConfigMixin.from_config) 메소드를 사용하여 스케줄러를 쉽게 교체할 수 있습니다. 자세한 내용은 [여기](../using-diffusers/schedulers.md)에서 설명합니다.
99
+ - 모든 스케줄러는 `set_num_inference_steps`와 `step` 함수를 가져야 합니다. `set_num_inference_steps(...)`는 각 노이즈 제거 과정(즉, `step(...)`이 호출되기 전) 이전에 호출되어야 합니다.
100
+ - 각 스케줄러는 모델이 호출될 타임스텝의 배열인 `timesteps` 속성을 통해 루프를 돌 수 있는 타임스텝을 노출합니다.
101
+ - `step(...)` 함수는 예측된 모델 출력과 "현재" 샘플(x_t)을 입력으로 받고, "이전" 약간 더 노이즈가 제거된 샘플(x_t-1)을 반환합니다.
102
+ - 노이즈 제거 스케줄러의 복잡성을 고려하여, `step` 함수는 모든 복잡성을 노출하지 않으며, "블랙 박스"일 수 있습니다.
103
+ - 거의 모든 경우에 새로운 스케줄러는 새로운 스케줄링 파일에 구현되어야 합니다.
tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/ko/in_translation.md ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
15
+ 열심히 번역을 진행중입니다. 조금만 기다려주세요.
16
+ 감사합니다!
tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/ko/index.md ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--Copyright 2025 The HuggingFace Team. All rights reserved.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4
+ the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10
+ specific language governing permissions and limitations under the License.
11
+ -->
12
+
13
+ <p align="center">
14
+ <br>
15
+ <img src="https://raw.githubusercontent.com/huggingface/diffusers/77aadfee6a891ab9fcfb780f87c693f7a5beeb8e/docs/source/imgs/diffusers_library.jpg" width="400"/>
16
+ <br>
17
+ </p>
18
+
19
+
20
+ # Diffusers
21
+
22
+ 🤗 Diffusers는 이미지, 오디오, 심지어 분자의 3D 구조를 생성하기 위한 최첨단 사전 훈련된 diffusion 모델을 위한 라이브러리입니다. 간단한 추론 솔루션을 찾고 있든, 자체 diffusion 모델을 훈련하고 싶든, 🤗 Diffusers는 두 가지 모두를 지원하는 모듈식 툴박스입니다. 저희 라이브러리는 [성능보다 사용성](conceptual/philosophy#usability-over-performance), [간편함보다 단순함](conceptual/philosophy#simple-over-easy), 그리고 [추상화보다 사용자 지정 가능성](conceptual/philosophy#tweakable-contributorfriendly-over-abstraction)에 중점을 두고 설계되었습니다.
23
+
24
+ 이 라이브러리에는 세 가지 주요 구성 요소가 있습니다:
25
+
26
+ - 몇 줄의 코드만으로 추론할 수 있는 최첨단 [diffusion 파이프라인](api/pipelines/overview).
27
+ - 생성 속도와 품질 간의 균형을 맞추기 위해 상호교환적으로 사용할 수 있는 [노이즈 스케줄러](api/schedulers/overview).
28
+ - 빌딩 블록으로 사용할 수 있고 스케줄러와 결합하여 자체적인 end-to-end diffusion 시스템을 만들 수 있는 사전 학습된 [모델](api/models).
29
+
30
+ <div class="mt-10">
31
+ <div class="w-full flex flex-col space-y-4 md:space-y-0 md:grid md:grid-cols-2 md:gap-y-4 md:gap-x-5">
32
+ <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./tutorials/tutorial_overview"
33
+ ><div class="w-full text-center bg-gradient-to-br from-blue-400 to-blue-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Tutorials</div>
34
+ <p class="text-gray-700">결과물을 생성하고, 나만의 diffusion 시스템을 구축하고, 확산 모델을 훈련하는 데 필요한 기본 기술을 배워보세요. 🤗 Diffusers를 처음 사용하는 경우 여기에서 시작하는 것이 좋습니다!</p>
35
+ </a>
36
+ <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./using-diffusers/loading_overview"
37
+ ><div class="w-full text-center bg-gradient-to-br from-indigo-400 to-indigo-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">How-to guides</div>
38
+ <p class="text-gray-700">파이프라인, 모델, 스케줄러를 로드하는 데 도움이 되는 실용적인 가이드입니다. 또한 특정 작업에 파이프라인을 사용하고, 출력 생성 방식을 제어하고, 추론 속도에 맞게 최적화하고, 다양한 학습 기법을 사용하는 방법도 배울 수 있습니다.</p>
39
+ </a>
40
+ <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./conceptual/philosophy"
41
+ ><div class="w-full text-center bg-gradient-to-br from-pink-400 to-pink-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Conceptual guides</div>
42
+ <p class="text-gray-700">라이브러리가 왜 이런 방식으로 설계되었는지 이해하고, 라이브러리 이용에 대한 윤리적 가이드라인과 안전 구현에 대해 자세히 알아보세요.</p>
43
+ </a>
44
+ <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./api/models"
45
+ ><div class="w-full text-center bg-gradient-to-br from-purple-400 to-purple-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Reference</div>
46
+ <p class="text-gray-700">🤗 Diffusers 클래스 및 메서드의 작동 방식에 대한 기술 설명.</p>
47
+ </a>
48
+ </div>
49
+ </div>
tasks/tasksmith-7bc616ce49d7/environment/source/docs/source/ko/installation.md ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
15
+ 사용하시는 라이브러리에 맞는 🤗 Diffusers를 설치하세요.
16
+
17
+ 🤗 Diffusers는 Python 3.8+, PyTorch 1.7.0+ 및 flax에서 테스트되었습니다. 사용중인 딥러닝 라이브러리에 대한 아래의 설치 안내를 따르세요.
18
+
19
+ - [PyTorch 설치 안내](https://pytorch.org/get-started/locally/)
20
+ - [Flax 설치 안내](https://flax.readthedocs.io/en/latest/)
21
+
22
+ ## pip를 이용한 설치
23
+
24
+ [가상 환경](https://docs.python.org/3/library/venv.html)에 🤗 Diffusers를 설치해야 합니다.
25
+ Python 가상 환경에 익숙하지 않은 경우 [가상환경 pip 설치 가이드](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/)를 살펴보세요.
26
+ 가상 환경을 사용하면 서로 다른 프로젝트를 더 쉽게 관리하고, 종속성간의 호환성 문제를 피할 수 있습니다.
27
+
28
+ 프로젝트 디렉토리에 가상 환경을 생성하는 것으로 시작하세요:
29
+
30
+ ```bash
31
+ python -m venv .env
32
+ ```
33
+
34
+ 그리고 가상 환경을 활성화합니다:
35
+
36
+ ```bash
37
+ source .env/bin/activate
38
+ ```
39
+
40
+ 이제 다음의 명령어로 🤗 Diffusers를 설치할 준비가 되었습니다:
41
+
42
+ **PyTorch의 경우**
43
+
44
+ ```bash
45
+ pip install diffusers["torch"]
46
+ ```
47
+
48
+ **Flax의 경우**
49
+
50
+ ```bash
51
+ pip install diffusers["flax"]
52
+ ```
53
+
54
+ ## 소스로부터 설치
55
+
56
+ 소스에서 `diffusers`를 설치하기 전에, `torch` 및 `accelerate`이 설치되어 있는지 확인하세요.
57
+
58
+ `torch` 설치에 대해서는 [torch docs](https://pytorch.org/get-started/locally/#start-locally)를 참고하세요.
59
+
60
+ 다음과 같이 `accelerate`을 설치하세요.
61
+
62
+ ```bash
63
+ pip install accelerate
64
+ ```
65
+
66
+ 다음 명령어를 사용하여 소스에서 🤗 Diffusers를 설치하세요:
67
+
68
+ ```bash
69
+ pip install git+https://github.com/huggingface/diffusers
70
+ ```
71
+
72
+ 이 명령어는 최신 `stable` 버전이 아닌 최첨단 `main` 버전을 설치합니다.
73
+ `main` 버전은 최신 개발 정보를 최신 상태로 유지하는 데 유용합니다.
74
+ 예를 들어 마지막 공식 릴리즈 이후 버그가 수정되었지만, 새 릴리즈가 아직 출시되지 않은 경우입니다.
75
+ 그러나 이는 `main` 버전이 항상 안정적이지 않을 수 있음을 의미합니다.
76
+ 우리는 `main` 버전이 지속적으로 작동하도록 노력하고 있으며, 대부분의 문제는 보통 몇 시간 또는 하루 안에 해결됩니다.
77
+ 문제가 발생하면 더 빨리 해결할 수 있도록 [Issue](https://github.com/huggingface/transformers/issues)를 열어주세요!
78
+
79
+
80
+ ## 편집가능한 설치
81
+
82
+ 다음을 수행하려면 편집가능한 설치가 필요합니다:
83
+
84
+ * 소스 코드의 `main` 버전을 사용
85
+ * 🤗 Diffusers에 기여 (코드의 변경 사항을 테스트하기 위해 필요)
86
+
87
+ 저장소를 복제하고 다음 명령어를 사용하여 🤗 Diffusers를 설치합니다:
88
+
89
+ ```bash
90
+ git clone https://github.com/huggingface/diffusers.git
91
+ cd diffusers
92
+ ```
93
+
94
+ **PyTorch의 경우**
95
+
96
+ ```sh
97
+ pip install -e ".[torch]"
98
+ ```
99
+
100
+ **Flax의 경우**
101
+
102
+ ```sh
103
+ pip install -e ".[flax]"
104
+ ```
105
+
106
+ 이러한 명령어들은 저장소를 복제한 폴더와 Python 라이브러리 경로를 연결합니다.
107
+ Python은 이제 일반 라이브러리 경로에 더하여 복제한 폴더 내부를 살펴봅니다.
108
+ 예를들어 Python 패키지가 `~/anaconda3/envs/main/lib/python3.10/site-packages/`에 설치되어 있는 경우 Python은 복제한 폴더인 `~/diffusers/`도 검색합니다.
109
+
110
+ > [!WARNING]
111
+ > 라이브러리를 계속 사용하려면 `diffusers` 폴더를 유지해야 합니다.
112
+
113
+ 이제 다음 명령어를 사용하여 최신 버전의 🤗 Diffusers로 쉽게 업데이트할 수 있습니다:
114
+
115
+ ```bash
116
+ cd ~/diffusers/
117
+ git pull
118
+ ```
119
+
120
+ 이렇게 하면, 다음에 실행할 때 Python 환경이 🤗 Diffusers의 `main` 버전을 찾게 됩니다.
121
+
122
+ ## 텔레메트리 로깅에 대한 알림
123
+
124
+ 우리 라이브러리는 `from_pretrained()` 요청 중에 텔레메트리 정보를 원격으로 수집합니다.
125
+ 이 데이터에는 Diffusers 및 PyTorch/Flax의 버전, 요청된 모델 또는 파이프라인 클래스, 그리고 허브에서 호스팅되는 경우 사전학습된 체크포인트에 대한 경로를 포함합니다.
126
+ 이 사용 데이터는 문제를 디버깅하고 새로운 기능의 우선순위를 지정하는데 도움이 됩니다.
127
+ 텔레메트리는 HuggingFace 허브에서 모델과 파이프라인을 ���러올 때만 전송되며, 로컬 사용 중에는 수집되지 않습니다.
128
+
129
+ 우리는 추가 정보를 공유하지 않기를 원하는 사람이 있다는 것을 이해하고 개인 정보를 존중하므로, 터미널에서 `DISABLE_TELEMETRY` 환경 변수를 설정하여 텔레메트리 수집을 비활성화할 수 있습니다.
130
+
131
+ Linux/MacOS에서:
132
+ ```bash
133
+ export DISABLE_TELEMETRY=YES
134
+ ```
135
+
136
+ Windows에서:
137
+ ```bash
138
+ set DISABLE_TELEMETRY=YES
139
+ ```