dvir-bria commited on
Commit
a3fc925
·
verified ·
1 Parent(s): 2c17097

Upload pipeline_controlnet_sd_xl.py

Browse files
Files changed (1) hide show
  1. pipeline_controlnet_sd_xl.py +1465 -0
pipeline_controlnet_sd_xl.py ADDED
@@ -0,0 +1,1465 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ import inspect
17
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
18
+
19
+ import numpy as np
20
+ import PIL.Image
21
+ import torch
22
+ import torch.nn.functional as F
23
+ from transformers import (
24
+ CLIPImageProcessor,
25
+ CLIPTextModel,
26
+ CLIPTextModelWithProjection,
27
+ CLIPTokenizer,
28
+ CLIPVisionModelWithProjection,
29
+ )
30
+
31
+ from diffusers.utils.import_utils import is_invisible_watermark_available
32
+
33
+ from image_processor import PipelineImageInput, VaeImageProcessor
34
+ from diffusers.loaders import (
35
+ FromSingleFileMixin,
36
+ IPAdapterMixin,
37
+ StableDiffusionXLLoraLoaderMixin,
38
+ TextualInversionLoaderMixin,
39
+ )
40
+ from controlnet import ControlNetModel
41
+ # from diffusers.models import AutoencoderKL, ControlNetModel, ImageProjection, UNet2DConditionModel
42
+ from diffusers.models import AutoencoderKL, ImageProjection, UNet2DConditionModel
43
+ from diffusers.models.attention_processor import (
44
+ AttnProcessor2_0,
45
+ LoRAAttnProcessor2_0,
46
+ LoRAXFormersAttnProcessor,
47
+ XFormersAttnProcessor,
48
+ )
49
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
50
+ from diffusers.schedulers import KarrasDiffusionSchedulers
51
+ from diffusers.utils import (
52
+ USE_PEFT_BACKEND,
53
+ deprecate,
54
+ logging,
55
+ replace_example_docstring,
56
+ scale_lora_layers,
57
+ unscale_lora_layers,
58
+ )
59
+ from diffusers.utils.torch_utils import is_compiled_module, is_torch_version, randn_tensor
60
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
61
+ from diffusers.pipelines.stable_diffusion_xl.pipeline_output import StableDiffusionXLPipelineOutput
62
+
63
+
64
+ if is_invisible_watermark_available():
65
+ from diffusers.pipelines.stable_diffusion_xl.watermark import StableDiffusionXLWatermarker
66
+
67
+ from diffusers.pipelines.controlnet.multicontrolnet import MultiControlNetModel
68
+
69
+
70
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
71
+
72
+
73
+ EXAMPLE_DOC_STRING = """
74
+ Examples:
75
+ ```py
76
+ >>> # !pip install opencv-python transformers accelerate
77
+ >>> from diffusers import StableDiffusionXLControlNetPipeline, ControlNetModel, AutoencoderKL
78
+ >>> from diffusers.utils import load_image
79
+ >>> import numpy as np
80
+ >>> import torch
81
+
82
+ >>> import cv2
83
+ >>> from PIL import Image
84
+
85
+ >>> prompt = "aerial view, a futuristic research complex in a bright foggy jungle, hard lighting"
86
+ >>> negative_prompt = "low quality, bad quality, sketches"
87
+
88
+ >>> # download an image
89
+ >>> image = load_image(
90
+ ... "https://hf.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/hf-logo.png"
91
+ ... )
92
+
93
+ >>> # initialize the models and pipeline
94
+ >>> controlnet_conditioning_scale = 0.5 # recommended for good generalization
95
+ >>> controlnet = ControlNetModel.from_pretrained(
96
+ ... "diffusers/controlnet-canny-sdxl-1.0", torch_dtype=torch.float16
97
+ ... )
98
+ >>> vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
99
+ >>> pipe = StableDiffusionXLControlNetPipeline.from_pretrained(
100
+ ... "stabilityai/stable-diffusion-xl-base-1.0", controlnet=controlnet, vae=vae, torch_dtype=torch.float16
101
+ ... )
102
+ >>> pipe.enable_model_cpu_offload()
103
+
104
+ >>> # get canny image
105
+ >>> image = np.array(image)
106
+ >>> image = cv2.Canny(image, 100, 200)
107
+ >>> image = image[:, :, None]
108
+ >>> image = np.concatenate([image, image, image], axis=2)
109
+ >>> canny_image = Image.fromarray(image)
110
+
111
+ >>> # generate image
112
+ >>> image = pipe(
113
+ ... prompt, controlnet_conditioning_scale=controlnet_conditioning_scale, image=canny_image
114
+ ... ).images[0]
115
+ ```
116
+ """
117
+
118
+
119
+ class StableDiffusionXLControlNetPipeline(
120
+ DiffusionPipeline,
121
+ TextualInversionLoaderMixin,
122
+ StableDiffusionXLLoraLoaderMixin,
123
+ IPAdapterMixin,
124
+ FromSingleFileMixin,
125
+ ):
126
+ r"""
127
+ Pipeline for text-to-image generation using Stable Diffusion XL with ControlNet guidance.
128
+
129
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
130
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
131
+
132
+ The pipeline also inherits the following loading methods:
133
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
134
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
135
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
136
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
137
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
138
+
139
+ Args:
140
+ vae ([`AutoencoderKL`]):
141
+ Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
142
+ text_encoder ([`~transformers.CLIPTextModel`]):
143
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
144
+ text_encoder_2 ([`~transformers.CLIPTextModelWithProjection`]):
145
+ Second frozen text-encoder
146
+ ([laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)).
147
+ tokenizer ([`~transformers.CLIPTokenizer`]):
148
+ A `CLIPTokenizer` to tokenize text.
149
+ tokenizer_2 ([`~transformers.CLIPTokenizer`]):
150
+ A `CLIPTokenizer` to tokenize text.
151
+ unet ([`UNet2DConditionModel`]):
152
+ A `UNet2DConditionModel` to denoise the encoded image latents.
153
+ controlnet ([`ControlNetModel`] or `List[ControlNetModel]`):
154
+ Provides additional conditioning to the `unet` during the denoising process. If you set multiple
155
+ ControlNets as a list, the outputs from each ControlNet are added together to create one combined
156
+ additional conditioning.
157
+ scheduler ([`SchedulerMixin`]):
158
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
159
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
160
+ force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"True"`):
161
+ Whether the negative prompt embeddings should always be set to 0. Also see the config of
162
+ `stabilityai/stable-diffusion-xl-base-1-0`.
163
+ add_watermarker (`bool`, *optional*):
164
+ Whether to use the [invisible_watermark](https://github.com/ShieldMnt/invisible-watermark/) library to
165
+ watermark output images. If not defined, it defaults to `True` if the package is installed; otherwise no
166
+ watermarker is used.
167
+ """
168
+
169
+ # leave controlnet out on purpose because it iterates with unet
170
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->image_encoder->unet->vae"
171
+ _optional_components = [
172
+ "tokenizer",
173
+ "tokenizer_2",
174
+ "text_encoder",
175
+ "text_encoder_2",
176
+ "feature_extractor",
177
+ "image_encoder",
178
+ ]
179
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
180
+
181
+ def __init__(
182
+ self,
183
+ vae: AutoencoderKL,
184
+ text_encoder: CLIPTextModel,
185
+ text_encoder_2: CLIPTextModelWithProjection,
186
+ tokenizer: CLIPTokenizer,
187
+ tokenizer_2: CLIPTokenizer,
188
+ unet: UNet2DConditionModel,
189
+ controlnet: Union[ControlNetModel, List[ControlNetModel], Tuple[ControlNetModel], MultiControlNetModel],
190
+ scheduler: KarrasDiffusionSchedulers,
191
+ force_zeros_for_empty_prompt: bool = True,
192
+ add_watermarker: Optional[bool] = None,
193
+ feature_extractor: CLIPImageProcessor = None,
194
+ image_encoder: CLIPVisionModelWithProjection = None,
195
+ ):
196
+ super().__init__()
197
+
198
+ if isinstance(controlnet, (list, tuple)):
199
+ controlnet = MultiControlNetModel(controlnet)
200
+
201
+ self.register_modules(
202
+ vae=vae,
203
+ text_encoder=text_encoder,
204
+ text_encoder_2=text_encoder_2,
205
+ tokenizer=tokenizer,
206
+ tokenizer_2=tokenizer_2,
207
+ unet=unet,
208
+ controlnet=controlnet,
209
+ scheduler=scheduler,
210
+ feature_extractor=feature_extractor,
211
+ image_encoder=image_encoder,
212
+ )
213
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
214
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True)
215
+ self.control_image_processor = VaeImageProcessor(
216
+ vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True, do_normalize=False
217
+ )
218
+ add_watermarker = add_watermarker if add_watermarker is not None else is_invisible_watermark_available()
219
+
220
+ if add_watermarker:
221
+ self.watermark = StableDiffusionXLWatermarker()
222
+ else:
223
+ self.watermark = None
224
+
225
+ self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
226
+
227
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_slicing
228
+ def enable_vae_slicing(self):
229
+ r"""
230
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
231
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
232
+ """
233
+ self.vae.enable_slicing()
234
+
235
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_slicing
236
+ def disable_vae_slicing(self):
237
+ r"""
238
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
239
+ computing decoding in one step.
240
+ """
241
+ self.vae.disable_slicing()
242
+
243
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_tiling
244
+ def enable_vae_tiling(self):
245
+ r"""
246
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
247
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
248
+ processing larger images.
249
+ """
250
+ self.vae.enable_tiling()
251
+
252
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_tiling
253
+ def disable_vae_tiling(self):
254
+ r"""
255
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
256
+ computing decoding in one step.
257
+ """
258
+ self.vae.disable_tiling()
259
+
260
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.encode_prompt
261
+ def encode_prompt(
262
+ self,
263
+ prompt: str,
264
+ prompt_2: Optional[str] = None,
265
+ device: Optional[torch.device] = None,
266
+ num_images_per_prompt: int = 1,
267
+ do_classifier_free_guidance: bool = True,
268
+ negative_prompt: Optional[str] = None,
269
+ negative_prompt_2: Optional[str] = None,
270
+ prompt_embeds: Optional[torch.FloatTensor] = None,
271
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
272
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
273
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
274
+ lora_scale: Optional[float] = None,
275
+ clip_skip: Optional[int] = None,
276
+ ):
277
+ r"""
278
+ Encodes the prompt into text encoder hidden states.
279
+
280
+ Args:
281
+ prompt (`str` or `List[str]`, *optional*):
282
+ prompt to be encoded
283
+ prompt_2 (`str` or `List[str]`, *optional*):
284
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
285
+ used in both text-encoders
286
+ device: (`torch.device`):
287
+ torch device
288
+ num_images_per_prompt (`int`):
289
+ number of images that should be generated per prompt
290
+ do_classifier_free_guidance (`bool`):
291
+ whether to use classifier free guidance or not
292
+ negative_prompt (`str` or `List[str]`, *optional*):
293
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
294
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
295
+ less than `1`).
296
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
297
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
298
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
299
+ prompt_embeds (`torch.FloatTensor`, *optional*):
300
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
301
+ provided, text embeddings will be generated from `prompt` input argument.
302
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
303
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
304
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
305
+ argument.
306
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
307
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
308
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
309
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
310
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
311
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
312
+ input argument.
313
+ lora_scale (`float`, *optional*):
314
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
315
+ clip_skip (`int`, *optional*):
316
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
317
+ the output of the pre-final layer will be used for computing the prompt embeddings.
318
+ """
319
+ device = device or self._execution_device
320
+
321
+ # set lora scale so that monkey patched LoRA
322
+ # function of text encoder can correctly access it
323
+ if lora_scale is not None and isinstance(self, StableDiffusionXLLoraLoaderMixin):
324
+ self._lora_scale = lora_scale
325
+
326
+ # dynamically adjust the LoRA scale
327
+ if self.text_encoder is not None:
328
+ if not USE_PEFT_BACKEND:
329
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
330
+ else:
331
+ scale_lora_layers(self.text_encoder, lora_scale)
332
+
333
+ if self.text_encoder_2 is not None:
334
+ if not USE_PEFT_BACKEND:
335
+ adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
336
+ else:
337
+ scale_lora_layers(self.text_encoder_2, lora_scale)
338
+
339
+ prompt = [prompt] if isinstance(prompt, str) else prompt
340
+
341
+ if prompt is not None:
342
+ batch_size = len(prompt)
343
+ else:
344
+ batch_size = prompt_embeds.shape[0]
345
+
346
+ # Define tokenizers and text encoders
347
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
348
+ text_encoders = (
349
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
350
+ )
351
+
352
+ if prompt_embeds is None:
353
+ prompt_2 = prompt_2 or prompt
354
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
355
+
356
+ # textual inversion: procecss multi-vector tokens if necessary
357
+ prompt_embeds_list = []
358
+ prompts = [prompt, prompt_2]
359
+ for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
360
+ if isinstance(self, TextualInversionLoaderMixin):
361
+ prompt = self.maybe_convert_prompt(prompt, tokenizer)
362
+
363
+ text_inputs = tokenizer(
364
+ prompt,
365
+ padding="max_length",
366
+ max_length=tokenizer.model_max_length,
367
+ truncation=True,
368
+ return_tensors="pt",
369
+ )
370
+
371
+ text_input_ids = text_inputs.input_ids
372
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
373
+
374
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
375
+ text_input_ids, untruncated_ids
376
+ ):
377
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
378
+ logger.warning(
379
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
380
+ f" {tokenizer.model_max_length} tokens: {removed_text}"
381
+ )
382
+
383
+ prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=True)
384
+
385
+ # We are only ALWAYS interested in the pooled output of the final text encoder
386
+ pooled_prompt_embeds = prompt_embeds[0]
387
+ if clip_skip is None:
388
+ prompt_embeds = prompt_embeds.hidden_states[-2]
389
+ else:
390
+ # "2" because SDXL always indexes from the penultimate layer.
391
+ prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
392
+
393
+ prompt_embeds_list.append(prompt_embeds)
394
+
395
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
396
+
397
+ # get unconditional embeddings for classifier free guidance
398
+ zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
399
+ if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
400
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
401
+ negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
402
+ elif do_classifier_free_guidance and negative_prompt_embeds is None:
403
+ negative_prompt = negative_prompt or ""
404
+ negative_prompt_2 = negative_prompt_2 or negative_prompt
405
+
406
+ # normalize str to list
407
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
408
+ negative_prompt_2 = (
409
+ batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
410
+ )
411
+
412
+ uncond_tokens: List[str]
413
+ if prompt is not None and type(prompt) is not type(negative_prompt):
414
+ raise TypeError(
415
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
416
+ f" {type(prompt)}."
417
+ )
418
+ elif batch_size != len(negative_prompt):
419
+ raise ValueError(
420
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
421
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
422
+ " the batch size of `prompt`."
423
+ )
424
+ else:
425
+ uncond_tokens = [negative_prompt, negative_prompt_2]
426
+
427
+ negative_prompt_embeds_list = []
428
+ for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
429
+ if isinstance(self, TextualInversionLoaderMixin):
430
+ negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
431
+
432
+ max_length = prompt_embeds.shape[1]
433
+ uncond_input = tokenizer(
434
+ negative_prompt,
435
+ padding="max_length",
436
+ max_length=max_length,
437
+ truncation=True,
438
+ return_tensors="pt",
439
+ )
440
+
441
+ negative_prompt_embeds = text_encoder(
442
+ uncond_input.input_ids.to(device),
443
+ output_hidden_states=True,
444
+ )
445
+ # We are only ALWAYS interested in the pooled output of the final text encoder
446
+ negative_pooled_prompt_embeds = negative_prompt_embeds[0]
447
+ negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
448
+
449
+ negative_prompt_embeds_list.append(negative_prompt_embeds)
450
+
451
+ negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
452
+
453
+ if self.text_encoder_2 is not None:
454
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
455
+ else:
456
+ prompt_embeds = prompt_embeds.to(dtype=self.unet.dtype, device=device)
457
+
458
+ bs_embed, seq_len, _ = prompt_embeds.shape
459
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
460
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
461
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
462
+
463
+ if do_classifier_free_guidance:
464
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
465
+ seq_len = negative_prompt_embeds.shape[1]
466
+
467
+ if self.text_encoder_2 is not None:
468
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
469
+ else:
470
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.unet.dtype, device=device)
471
+
472
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
473
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
474
+
475
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
476
+ bs_embed * num_images_per_prompt, -1
477
+ )
478
+ if do_classifier_free_guidance:
479
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
480
+ bs_embed * num_images_per_prompt, -1
481
+ )
482
+
483
+ if self.text_encoder is not None:
484
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
485
+ # Retrieve the original scale by scaling back the LoRA layers
486
+ unscale_lora_layers(self.text_encoder, lora_scale)
487
+
488
+ if self.text_encoder_2 is not None:
489
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
490
+ # Retrieve the original scale by scaling back the LoRA layers
491
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
492
+
493
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
494
+
495
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
496
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
497
+ dtype = next(self.image_encoder.parameters()).dtype
498
+
499
+ if not isinstance(image, torch.Tensor):
500
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
501
+
502
+ image = image.to(device=device, dtype=dtype)
503
+ if output_hidden_states:
504
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
505
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
506
+ uncond_image_enc_hidden_states = self.image_encoder(
507
+ torch.zeros_like(image), output_hidden_states=True
508
+ ).hidden_states[-2]
509
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
510
+ num_images_per_prompt, dim=0
511
+ )
512
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
513
+ else:
514
+ image_embeds = self.image_encoder(image).image_embeds
515
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
516
+ uncond_image_embeds = torch.zeros_like(image_embeds)
517
+
518
+ return image_embeds, uncond_image_embeds
519
+
520
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
521
+ def prepare_ip_adapter_image_embeds(self, ip_adapter_image, device, num_images_per_prompt):
522
+ if not isinstance(ip_adapter_image, list):
523
+ ip_adapter_image = [ip_adapter_image]
524
+
525
+ if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
526
+ raise ValueError(
527
+ f"`ip_adapter_image` must have same length as the number of IP Adapters. Got {len(ip_adapter_image)} images and {len(self.unet.encoder_hid_proj.image_projection_layers)} IP Adapters."
528
+ )
529
+
530
+ image_embeds = []
531
+ for single_ip_adapter_image, image_proj_layer in zip(
532
+ ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
533
+ ):
534
+ output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
535
+ single_image_embeds, single_negative_image_embeds = self.encode_image(
536
+ single_ip_adapter_image, device, 1, output_hidden_state
537
+ )
538
+ single_image_embeds = torch.stack([single_image_embeds] * num_images_per_prompt, dim=0)
539
+ single_negative_image_embeds = torch.stack([single_negative_image_embeds] * num_images_per_prompt, dim=0)
540
+
541
+ if self.do_classifier_free_guidance:
542
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds])
543
+ single_image_embeds = single_image_embeds.to(device)
544
+
545
+ image_embeds.append(single_image_embeds)
546
+
547
+ return image_embeds
548
+
549
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
550
+ def prepare_extra_step_kwargs(self, generator, eta):
551
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
552
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
553
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
554
+ # and should be between [0, 1]
555
+
556
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
557
+ extra_step_kwargs = {}
558
+ if accepts_eta:
559
+ extra_step_kwargs["eta"] = eta
560
+
561
+ # check if the scheduler accepts generator
562
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
563
+ if accepts_generator:
564
+ extra_step_kwargs["generator"] = generator
565
+ return extra_step_kwargs
566
+
567
+ def check_inputs(
568
+ self,
569
+ prompt,
570
+ prompt_2,
571
+ image,
572
+ callback_steps,
573
+ negative_prompt=None,
574
+ negative_prompt_2=None,
575
+ prompt_embeds=None,
576
+ negative_prompt_embeds=None,
577
+ pooled_prompt_embeds=None,
578
+ negative_pooled_prompt_embeds=None,
579
+ controlnet_conditioning_scale=1.0,
580
+ control_guidance_start=0.0,
581
+ control_guidance_end=1.0,
582
+ callback_on_step_end_tensor_inputs=None,
583
+ ):
584
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
585
+ raise ValueError(
586
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
587
+ f" {type(callback_steps)}."
588
+ )
589
+
590
+ if callback_on_step_end_tensor_inputs is not None and not all(
591
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
592
+ ):
593
+ raise ValueError(
594
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
595
+ )
596
+
597
+ if prompt is not None and prompt_embeds is not None:
598
+ raise ValueError(
599
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
600
+ " only forward one of the two."
601
+ )
602
+ elif prompt_2 is not None and prompt_embeds is not None:
603
+ raise ValueError(
604
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
605
+ " only forward one of the two."
606
+ )
607
+ elif prompt is None and prompt_embeds is None:
608
+ raise ValueError(
609
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
610
+ )
611
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
612
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
613
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
614
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
615
+
616
+ if negative_prompt is not None and negative_prompt_embeds is not None:
617
+ raise ValueError(
618
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
619
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
620
+ )
621
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
622
+ raise ValueError(
623
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
624
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
625
+ )
626
+
627
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
628
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
629
+ raise ValueError(
630
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
631
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
632
+ f" {negative_prompt_embeds.shape}."
633
+ )
634
+
635
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
636
+ raise ValueError(
637
+ "If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`."
638
+ )
639
+
640
+ if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
641
+ raise ValueError(
642
+ "If `negative_prompt_embeds` are provided, `negative_pooled_prompt_embeds` also have to be passed. Make sure to generate `negative_pooled_prompt_embeds` from the same text encoder that was used to generate `negative_prompt_embeds`."
643
+ )
644
+
645
+ # `prompt` needs more sophisticated handling when there are multiple
646
+ # conditionings.
647
+ if isinstance(self.controlnet, MultiControlNetModel):
648
+ if isinstance(prompt, list):
649
+ logger.warning(
650
+ f"You have {len(self.controlnet.nets)} ControlNets and you have passed {len(prompt)}"
651
+ " prompts. The conditionings will be fixed across the prompts."
652
+ )
653
+
654
+ # Check `image`
655
+ is_compiled = hasattr(F, "scaled_dot_product_attention") and isinstance(
656
+ self.controlnet, torch._dynamo.eval_frame.OptimizedModule
657
+ )
658
+ if (
659
+ isinstance(self.controlnet, ControlNetModel)
660
+ or is_compiled
661
+ and isinstance(self.controlnet._orig_mod, ControlNetModel)
662
+ ):
663
+ self.check_image(image, prompt, prompt_embeds)
664
+ elif (
665
+ isinstance(self.controlnet, MultiControlNetModel)
666
+ or is_compiled
667
+ and isinstance(self.controlnet._orig_mod, MultiControlNetModel)
668
+ ):
669
+ if not isinstance(image, list):
670
+ raise TypeError("For multiple controlnets: `image` must be type `list`")
671
+
672
+ # When `image` is a nested list:
673
+ # (e.g. [[canny_image_1, pose_image_1], [canny_image_2, pose_image_2]])
674
+ elif any(isinstance(i, list) for i in image):
675
+ raise ValueError("A single batch of multiple conditionings are supported at the moment.")
676
+ elif len(image) != len(self.controlnet.nets):
677
+ raise ValueError(
678
+ f"For multiple controlnets: `image` must have the same length as the number of controlnets, but got {len(image)} images and {len(self.controlnet.nets)} ControlNets."
679
+ )
680
+
681
+ for image_ in image:
682
+ self.check_image(image_, prompt, prompt_embeds)
683
+ else:
684
+ assert False
685
+
686
+ # Check `controlnet_conditioning_scale`
687
+ if (
688
+ isinstance(self.controlnet, ControlNetModel)
689
+ or is_compiled
690
+ and isinstance(self.controlnet._orig_mod, ControlNetModel)
691
+ ):
692
+ if not isinstance(controlnet_conditioning_scale, float):
693
+ raise TypeError("For single controlnet: `controlnet_conditioning_scale` must be type `float`.")
694
+ elif (
695
+ isinstance(self.controlnet, MultiControlNetModel)
696
+ or is_compiled
697
+ and isinstance(self.controlnet._orig_mod, MultiControlNetModel)
698
+ ):
699
+ if isinstance(controlnet_conditioning_scale, list):
700
+ if any(isinstance(i, list) for i in controlnet_conditioning_scale):
701
+ raise ValueError("A single batch of multiple conditionings are supported at the moment.")
702
+ elif isinstance(controlnet_conditioning_scale, list) and len(controlnet_conditioning_scale) != len(
703
+ self.controlnet.nets
704
+ ):
705
+ raise ValueError(
706
+ "For multiple controlnets: When `controlnet_conditioning_scale` is specified as `list`, it must have"
707
+ " the same length as the number of controlnets"
708
+ )
709
+ else:
710
+ assert False
711
+
712
+ if not isinstance(control_guidance_start, (tuple, list)):
713
+ control_guidance_start = [control_guidance_start]
714
+
715
+ if not isinstance(control_guidance_end, (tuple, list)):
716
+ control_guidance_end = [control_guidance_end]
717
+
718
+ if len(control_guidance_start) != len(control_guidance_end):
719
+ raise ValueError(
720
+ f"`control_guidance_start` has {len(control_guidance_start)} elements, but `control_guidance_end` has {len(control_guidance_end)} elements. Make sure to provide the same number of elements to each list."
721
+ )
722
+
723
+ if isinstance(self.controlnet, MultiControlNetModel):
724
+ if len(control_guidance_start) != len(self.controlnet.nets):
725
+ raise ValueError(
726
+ f"`control_guidance_start`: {control_guidance_start} has {len(control_guidance_start)} elements but there are {len(self.controlnet.nets)} controlnets available. Make sure to provide {len(self.controlnet.nets)}."
727
+ )
728
+
729
+ for start, end in zip(control_guidance_start, control_guidance_end):
730
+ if start >= end:
731
+ raise ValueError(
732
+ f"control guidance start: {start} cannot be larger or equal to control guidance end: {end}."
733
+ )
734
+ if start < 0.0:
735
+ raise ValueError(f"control guidance start: {start} can't be smaller than 0.")
736
+ if end > 1.0:
737
+ raise ValueError(f"control guidance end: {end} can't be larger than 1.0.")
738
+
739
+ # Copied from diffusers.pipelines.controlnet.pipeline_controlnet.StableDiffusionControlNetPipeline.check_image
740
+ def check_image(self, image, prompt, prompt_embeds):
741
+ image_is_pil = isinstance(image, PIL.Image.Image)
742
+ image_is_tensor = isinstance(image, torch.Tensor)
743
+ image_is_np = isinstance(image, np.ndarray)
744
+ image_is_pil_list = isinstance(image, list) and isinstance(image[0], PIL.Image.Image)
745
+ image_is_tensor_list = isinstance(image, list) and isinstance(image[0], torch.Tensor)
746
+ image_is_np_list = isinstance(image, list) and isinstance(image[0], np.ndarray)
747
+
748
+ if (
749
+ not image_is_pil
750
+ and not image_is_tensor
751
+ and not image_is_np
752
+ and not image_is_pil_list
753
+ and not image_is_tensor_list
754
+ and not image_is_np_list
755
+ ):
756
+ raise TypeError(
757
+ f"image must be passed and be one of PIL image, numpy array, torch tensor, list of PIL images, list of numpy arrays or list of torch tensors, but is {type(image)}"
758
+ )
759
+
760
+ if image_is_pil:
761
+ image_batch_size = 1
762
+ else:
763
+ image_batch_size = len(image)
764
+
765
+ if prompt is not None and isinstance(prompt, str):
766
+ prompt_batch_size = 1
767
+ elif prompt is not None and isinstance(prompt, list):
768
+ prompt_batch_size = len(prompt)
769
+ elif prompt_embeds is not None:
770
+ prompt_batch_size = prompt_embeds.shape[0]
771
+
772
+ if image_batch_size != 1 and image_batch_size != prompt_batch_size:
773
+ raise ValueError(
774
+ f"If image batch size is not 1, image batch size must be same as prompt batch size. image batch size: {image_batch_size}, prompt batch size: {prompt_batch_size}"
775
+ )
776
+
777
+ # Copied from diffusers.pipelines.controlnet.pipeline_controlnet.StableDiffusionControlNetPipeline.prepare_image
778
+ def prepare_image(
779
+ self,
780
+ image,
781
+ width,
782
+ height,
783
+ batch_size,
784
+ num_images_per_prompt,
785
+ device,
786
+ dtype,
787
+ do_classifier_free_guidance=False,
788
+ guess_mode=False,
789
+ ):
790
+ image = self.control_image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32)
791
+ image_batch_size = image.shape[0]
792
+
793
+ if image_batch_size == 1:
794
+ repeat_by = batch_size
795
+ else:
796
+ # image batch size is the same as prompt batch size
797
+ repeat_by = num_images_per_prompt
798
+
799
+ image = image.repeat_interleave(repeat_by, dim=0)
800
+
801
+ image = image.to(device=device, dtype=dtype)
802
+
803
+ if do_classifier_free_guidance and not guess_mode:
804
+ image = torch.cat([image] * 2)
805
+
806
+ return image
807
+
808
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
809
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
810
+ shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
811
+ if isinstance(generator, list) and len(generator) != batch_size:
812
+ raise ValueError(
813
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
814
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
815
+ )
816
+
817
+ if latents is None:
818
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
819
+ else:
820
+ latents = latents.to(device)
821
+
822
+ # scale the initial noise by the standard deviation required by the scheduler
823
+ latents = latents * self.scheduler.init_noise_sigma
824
+ return latents
825
+
826
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline._get_add_time_ids
827
+ def _get_add_time_ids(
828
+ self, original_size, crops_coords_top_left, target_size, dtype, text_encoder_projection_dim=None
829
+ ):
830
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
831
+
832
+ passed_add_embed_dim = (
833
+ self.unet.config.addition_time_embed_dim * len(add_time_ids) + text_encoder_projection_dim
834
+ )
835
+ expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
836
+
837
+ if expected_add_embed_dim != passed_add_embed_dim:
838
+ raise ValueError(
839
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. The model has an incorrect config. Please check `unet.config.time_embedding_type` and `text_encoder_2.config.projection_dim`."
840
+ )
841
+
842
+ add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
843
+ return add_time_ids
844
+
845
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.StableDiffusionUpscalePipeline.upcast_vae
846
+ def upcast_vae(self):
847
+ dtype = self.vae.dtype
848
+ self.vae.to(dtype=torch.float32)
849
+ use_torch_2_0_or_xformers = isinstance(
850
+ self.vae.decoder.mid_block.attentions[0].processor,
851
+ (
852
+ AttnProcessor2_0,
853
+ XFormersAttnProcessor,
854
+ LoRAXFormersAttnProcessor,
855
+ LoRAAttnProcessor2_0,
856
+ ),
857
+ )
858
+ # if xformers or torch_2_0 is used attention block does not need
859
+ # to be in float32 which can save lots of memory
860
+ if use_torch_2_0_or_xformers:
861
+ self.vae.post_quant_conv.to(dtype)
862
+ self.vae.decoder.conv_in.to(dtype)
863
+ self.vae.decoder.mid_block.to(dtype)
864
+
865
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_freeu
866
+ def enable_freeu(self, s1: float, s2: float, b1: float, b2: float):
867
+ r"""Enables the FreeU mechanism as in https://arxiv.org/abs/2309.11497.
868
+
869
+ The suffixes after the scaling factors represent the stages where they are being applied.
870
+
871
+ Please refer to the [official repository](https://github.com/ChenyangSi/FreeU) for combinations of the values
872
+ that are known to work well for different pipelines such as Stable Diffusion v1, v2, and Stable Diffusion XL.
873
+
874
+ Args:
875
+ s1 (`float`):
876
+ Scaling factor for stage 1 to attenuate the contributions of the skip features. This is done to
877
+ mitigate "oversmoothing effect" in the enhanced denoising process.
878
+ s2 (`float`):
879
+ Scaling factor for stage 2 to attenuate the contributions of the skip features. This is done to
880
+ mitigate "oversmoothing effect" in the enhanced denoising process.
881
+ b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features.
882
+ b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features.
883
+ """
884
+ if not hasattr(self, "unet"):
885
+ raise ValueError("The pipeline must have `unet` for using FreeU.")
886
+ self.unet.enable_freeu(s1=s1, s2=s2, b1=b1, b2=b2)
887
+
888
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_freeu
889
+ def disable_freeu(self):
890
+ """Disables the FreeU mechanism if enabled."""
891
+ self.unet.disable_freeu()
892
+
893
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
894
+ def get_guidance_scale_embedding(self, w, embedding_dim=512, dtype=torch.float32):
895
+ """
896
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
897
+
898
+ Args:
899
+ timesteps (`torch.Tensor`):
900
+ generate embedding vectors at these timesteps
901
+ embedding_dim (`int`, *optional*, defaults to 512):
902
+ dimension of the embeddings to generate
903
+ dtype:
904
+ data type of the generated embeddings
905
+
906
+ Returns:
907
+ `torch.FloatTensor`: Embedding vectors with shape `(len(timesteps), embedding_dim)`
908
+ """
909
+ assert len(w.shape) == 1
910
+ w = w * 1000.0
911
+
912
+ half_dim = embedding_dim // 2
913
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
914
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
915
+ emb = w.to(dtype)[:, None] * emb[None, :]
916
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
917
+ if embedding_dim % 2 == 1: # zero pad
918
+ emb = torch.nn.functional.pad(emb, (0, 1))
919
+ assert emb.shape == (w.shape[0], embedding_dim)
920
+ return emb
921
+
922
+ @property
923
+ def guidance_scale(self):
924
+ return self._guidance_scale
925
+
926
+ @property
927
+ def clip_skip(self):
928
+ return self._clip_skip
929
+
930
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
931
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
932
+ # corresponds to doing no classifier free guidance.
933
+ @property
934
+ def do_classifier_free_guidance(self):
935
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
936
+
937
+ @property
938
+ def cross_attention_kwargs(self):
939
+ return self._cross_attention_kwargs
940
+
941
+ @property
942
+ def num_timesteps(self):
943
+ return self._num_timesteps
944
+
945
+ @torch.no_grad()
946
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
947
+ def __call__(
948
+ self,
949
+ prompt: Union[str, List[str]] = None,
950
+ prompt_2: Optional[Union[str, List[str]]] = None,
951
+ image: PipelineImageInput = None,
952
+ height: Optional[int] = None,
953
+ width: Optional[int] = None,
954
+ num_inference_steps: int = 50,
955
+ guidance_scale: float = 5.0,
956
+ negative_prompt: Optional[Union[str, List[str]]] = None,
957
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
958
+ num_images_per_prompt: Optional[int] = 1,
959
+ eta: float = 0.0,
960
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
961
+ latents: Optional[torch.FloatTensor] = None,
962
+ prompt_embeds: Optional[torch.FloatTensor] = None,
963
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
964
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
965
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
966
+ ip_adapter_image: Optional[PipelineImageInput] = None,
967
+ output_type: Optional[str] = "pil",
968
+ return_dict: bool = True,
969
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
970
+ controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
971
+ guess_mode: bool = False,
972
+ control_guidance_start: Union[float, List[float]] = 0.0,
973
+ control_guidance_end: Union[float, List[float]] = 1.0,
974
+ original_size: Tuple[int, int] = None,
975
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
976
+ target_size: Tuple[int, int] = None,
977
+ negative_original_size: Optional[Tuple[int, int]] = None,
978
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
979
+ negative_target_size: Optional[Tuple[int, int]] = None,
980
+ clip_skip: Optional[int] = None,
981
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
982
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
983
+ **kwargs,
984
+ ):
985
+ r"""
986
+ The call function to the pipeline for generation.
987
+
988
+ Args:
989
+ prompt (`str` or `List[str]`, *optional*):
990
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
991
+ prompt_2 (`str` or `List[str]`, *optional*):
992
+ The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
993
+ used in both text-encoders.
994
+ image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
995
+ `List[List[torch.FloatTensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
996
+ The ControlNet input condition to provide guidance to the `unet` for generation. If the type is
997
+ specified as `torch.FloatTensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also be
998
+ accepted as an image. The dimensions of the output image defaults to `image`'s dimensions. If height
999
+ and/or width are passed, `image` is resized accordingly. If multiple ControlNets are specified in
1000
+ `init`, images must be passed as a list such that each element of the list can be correctly batched for
1001
+ input to a single ControlNet.
1002
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
1003
+ The height in pixels of the generated image. Anything below 512 pixels won't work well for
1004
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
1005
+ and checkpoints that are not specifically fine-tuned on low resolutions.
1006
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
1007
+ The width in pixels of the generated image. Anything below 512 pixels won't work well for
1008
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
1009
+ and checkpoints that are not specifically fine-tuned on low resolutions.
1010
+ num_inference_steps (`int`, *optional*, defaults to 50):
1011
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
1012
+ expense of slower inference.
1013
+ guidance_scale (`float`, *optional*, defaults to 5.0):
1014
+ A higher guidance scale value encourages the model to generate images closely linked to the text
1015
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
1016
+ negative_prompt (`str` or `List[str]`, *optional*):
1017
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
1018
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
1019
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
1020
+ The prompt or prompts to guide what to not include in image generation. This is sent to `tokenizer_2`
1021
+ and `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders.
1022
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1023
+ The number of images to generate per prompt.
1024
+ eta (`float`, *optional*, defaults to 0.0):
1025
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
1026
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
1027
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
1028
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
1029
+ generation deterministic.
1030
+ latents (`torch.FloatTensor`, *optional*):
1031
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
1032
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
1033
+ tensor is generated by sampling using the supplied random `generator`.
1034
+ prompt_embeds (`torch.FloatTensor`, *optional*):
1035
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
1036
+ provided, text embeddings are generated from the `prompt` input argument.
1037
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
1038
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
1039
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
1040
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
1041
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
1042
+ not provided, pooled text embeddings are generated from `prompt` input argument.
1043
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
1044
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs (prompt
1045
+ weighting). If not provided, pooled `negative_prompt_embeds` are generated from `negative_prompt` input
1046
+ argument.
1047
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
1048
+ output_type (`str`, *optional*, defaults to `"pil"`):
1049
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
1050
+ return_dict (`bool`, *optional*, defaults to `True`):
1051
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
1052
+ plain tuple.
1053
+ cross_attention_kwargs (`dict`, *optional*):
1054
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
1055
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1056
+ controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
1057
+ The outputs of the ControlNet are multiplied by `controlnet_conditioning_scale` before they are added
1058
+ to the residual in the original `unet`. If multiple ControlNets are specified in `init`, you can set
1059
+ the corresponding scale as a list.
1060
+ guess_mode (`bool`, *optional*, defaults to `False`):
1061
+ The ControlNet encoder tries to recognize the content of the input image even if you remove all
1062
+ prompts. A `guidance_scale` value between 3.0 and 5.0 is recommended.
1063
+ control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0):
1064
+ The percentage of total steps at which the ControlNet starts applying.
1065
+ control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0):
1066
+ The percentage of total steps at which the ControlNet stops applying.
1067
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1068
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
1069
+ `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
1070
+ explained in section 2.2 of
1071
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1072
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
1073
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
1074
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
1075
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
1076
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1077
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1078
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
1079
+ not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
1080
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1081
+ negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1082
+ To negatively condition the generation process based on a specific image resolution. Part of SDXL's
1083
+ micro-conditioning as explained in section 2.2 of
1084
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1085
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1086
+ negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
1087
+ To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
1088
+ micro-conditioning as explained in section 2.2 of
1089
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1090
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1091
+ negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1092
+ To negatively condition the generation process based on a target image resolution. It should be as same
1093
+ as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
1094
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1095
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1096
+ clip_skip (`int`, *optional*):
1097
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
1098
+ the output of the pre-final layer will be used for computing the prompt embeddings.
1099
+ callback_on_step_end (`Callable`, *optional*):
1100
+ A function that calls at the end of each denoising steps during the inference. The function is called
1101
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
1102
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
1103
+ `callback_on_step_end_tensor_inputs`.
1104
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
1105
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
1106
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
1107
+ `._callback_tensor_inputs` attribute of your pipeine class.
1108
+
1109
+ Examples:
1110
+
1111
+ Returns:
1112
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
1113
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
1114
+ otherwise a `tuple` is returned containing the output images.
1115
+ """
1116
+
1117
+ callback = kwargs.pop("callback", None)
1118
+ callback_steps = kwargs.pop("callback_steps", None)
1119
+
1120
+ if callback is not None:
1121
+ deprecate(
1122
+ "callback",
1123
+ "1.0.0",
1124
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
1125
+ )
1126
+ if callback_steps is not None:
1127
+ deprecate(
1128
+ "callback_steps",
1129
+ "1.0.0",
1130
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
1131
+ )
1132
+
1133
+ controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet
1134
+
1135
+ # align format for control guidance
1136
+ if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):
1137
+ control_guidance_start = len(control_guidance_end) * [control_guidance_start]
1138
+ elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):
1139
+ control_guidance_end = len(control_guidance_start) * [control_guidance_end]
1140
+ elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):
1141
+ mult = len(controlnet.nets) if isinstance(controlnet, MultiControlNetModel) else 1
1142
+ control_guidance_start, control_guidance_end = (
1143
+ mult * [control_guidance_start],
1144
+ mult * [control_guidance_end],
1145
+ )
1146
+
1147
+ # 1. Check inputs. Raise error if not correct
1148
+ self.check_inputs(
1149
+ prompt,
1150
+ prompt_2,
1151
+ image,
1152
+ callback_steps,
1153
+ negative_prompt,
1154
+ negative_prompt_2,
1155
+ prompt_embeds,
1156
+ negative_prompt_embeds,
1157
+ pooled_prompt_embeds,
1158
+ negative_pooled_prompt_embeds,
1159
+ controlnet_conditioning_scale,
1160
+ control_guidance_start,
1161
+ control_guidance_end,
1162
+ callback_on_step_end_tensor_inputs,
1163
+ )
1164
+
1165
+ self._guidance_scale = guidance_scale
1166
+ self._clip_skip = clip_skip
1167
+ self._cross_attention_kwargs = cross_attention_kwargs
1168
+
1169
+ # 2. Define call parameters
1170
+ if prompt is not None and isinstance(prompt, str):
1171
+ batch_size = 1
1172
+ elif prompt is not None and isinstance(prompt, list):
1173
+ batch_size = len(prompt)
1174
+ else:
1175
+ batch_size = prompt_embeds.shape[0]
1176
+
1177
+ device = self._execution_device
1178
+
1179
+ if isinstance(controlnet, MultiControlNetModel) and isinstance(controlnet_conditioning_scale, float):
1180
+ controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet.nets)
1181
+
1182
+ global_pool_conditions = (
1183
+ controlnet.config.global_pool_conditions
1184
+ if isinstance(controlnet, ControlNetModel)
1185
+ else controlnet.nets[0].config.global_pool_conditions
1186
+ )
1187
+ guess_mode = guess_mode or global_pool_conditions
1188
+
1189
+ # 3.1 Encode input prompt
1190
+ text_encoder_lora_scale = (
1191
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
1192
+ )
1193
+ (
1194
+ prompt_embeds,
1195
+ negative_prompt_embeds,
1196
+ pooled_prompt_embeds,
1197
+ negative_pooled_prompt_embeds,
1198
+ ) = self.encode_prompt(
1199
+ prompt,
1200
+ prompt_2,
1201
+ device,
1202
+ num_images_per_prompt,
1203
+ self.do_classifier_free_guidance,
1204
+ negative_prompt,
1205
+ negative_prompt_2,
1206
+ prompt_embeds=prompt_embeds,
1207
+ negative_prompt_embeds=negative_prompt_embeds,
1208
+ pooled_prompt_embeds=pooled_prompt_embeds,
1209
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
1210
+ lora_scale=text_encoder_lora_scale,
1211
+ clip_skip=self.clip_skip,
1212
+ )
1213
+
1214
+ # 3.2 Encode ip_adapter_image
1215
+ if ip_adapter_image is not None:
1216
+ image_embeds = self.prepare_ip_adapter_image_embeds(
1217
+ ip_adapter_image, device, batch_size * num_images_per_prompt
1218
+ )
1219
+
1220
+ # 4. Prepare image
1221
+ if isinstance(controlnet, ControlNetModel):
1222
+ image = self.prepare_image(
1223
+ image=image,
1224
+ width=width,
1225
+ height=height,
1226
+ batch_size=batch_size * num_images_per_prompt,
1227
+ num_images_per_prompt=num_images_per_prompt,
1228
+ device=device,
1229
+ dtype=controlnet.dtype,
1230
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1231
+ guess_mode=guess_mode,
1232
+ )
1233
+ height, width = image.shape[-2:]
1234
+ height, width = height*self.vae_scale_factor, width*self.vae_scale_factor # for vae controlnet
1235
+ elif isinstance(controlnet, MultiControlNetModel):
1236
+ images = []
1237
+
1238
+ for image_ in image:
1239
+ image_ = self.prepare_image(
1240
+ image=image_,
1241
+ width=width,
1242
+ height=height,
1243
+ batch_size=batch_size * num_images_per_prompt,
1244
+ num_images_per_prompt=num_images_per_prompt,
1245
+ device=device,
1246
+ dtype=controlnet.dtype,
1247
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1248
+ guess_mode=guess_mode,
1249
+ )
1250
+
1251
+ images.append(image_)
1252
+
1253
+ image = images
1254
+ height, width = image[0].shape[-2:]
1255
+ else:
1256
+ assert False
1257
+
1258
+ # 5. Prepare timesteps
1259
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
1260
+ timesteps = self.scheduler.timesteps
1261
+ self._num_timesteps = len(timesteps)
1262
+
1263
+ # 6. Prepare latent variables
1264
+ num_channels_latents = self.unet.config.in_channels
1265
+ latents = self.prepare_latents(
1266
+ batch_size * num_images_per_prompt,
1267
+ num_channels_latents,
1268
+ height,
1269
+ width,
1270
+ prompt_embeds.dtype,
1271
+ device,
1272
+ generator,
1273
+ latents,
1274
+ )
1275
+
1276
+ # 6.5 Optionally get Guidance Scale Embedding
1277
+ timestep_cond = None
1278
+ if self.unet.config.time_cond_proj_dim is not None:
1279
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
1280
+ timestep_cond = self.get_guidance_scale_embedding(
1281
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
1282
+ ).to(device=device, dtype=latents.dtype)
1283
+
1284
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1285
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1286
+
1287
+ # 7.1 Create tensor stating which controlnets to keep
1288
+ controlnet_keep = []
1289
+ for i in range(len(timesteps)):
1290
+ keeps = [
1291
+ 1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e)
1292
+ for s, e in zip(control_guidance_start, control_guidance_end)
1293
+ ]
1294
+ controlnet_keep.append(keeps[0] if isinstance(controlnet, ControlNetModel) else keeps)
1295
+
1296
+ # 7.2 Prepare added time ids & embeddings
1297
+ if isinstance(image, list):
1298
+ original_size = original_size or image[0].shape[-2:]
1299
+ else:
1300
+ original_size = original_size or image.shape[-2:]
1301
+ target_size = target_size or (height, width)
1302
+
1303
+ add_text_embeds = pooled_prompt_embeds
1304
+ if self.text_encoder_2 is None:
1305
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
1306
+ else:
1307
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
1308
+
1309
+ add_time_ids = self._get_add_time_ids(
1310
+ original_size,
1311
+ crops_coords_top_left,
1312
+ target_size,
1313
+ dtype=prompt_embeds.dtype,
1314
+ text_encoder_projection_dim=text_encoder_projection_dim,
1315
+ )
1316
+
1317
+ if negative_original_size is not None and negative_target_size is not None:
1318
+ negative_add_time_ids = self._get_add_time_ids(
1319
+ negative_original_size,
1320
+ negative_crops_coords_top_left,
1321
+ negative_target_size,
1322
+ dtype=prompt_embeds.dtype,
1323
+ text_encoder_projection_dim=text_encoder_projection_dim,
1324
+ )
1325
+ else:
1326
+ negative_add_time_ids = add_time_ids
1327
+
1328
+ if self.do_classifier_free_guidance:
1329
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
1330
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
1331
+ add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
1332
+
1333
+ prompt_embeds = prompt_embeds.to(device)
1334
+ add_text_embeds = add_text_embeds.to(device)
1335
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
1336
+
1337
+ # 8. Denoising loop
1338
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
1339
+ is_unet_compiled = is_compiled_module(self.unet)
1340
+ is_controlnet_compiled = is_compiled_module(self.controlnet)
1341
+ is_torch_higher_equal_2_1 = is_torch_version(">=", "2.1")
1342
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1343
+ for i, t in enumerate(timesteps):
1344
+ # Relevant thread:
1345
+ # https://dev-discuss.pytorch.org/t/cudagraphs-in-pytorch-2-0/1428
1346
+ if (is_unet_compiled and is_controlnet_compiled) and is_torch_higher_equal_2_1:
1347
+ torch._inductor.cudagraph_mark_step_begin()
1348
+ # expand the latents if we are doing classifier free guidance
1349
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1350
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1351
+
1352
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
1353
+
1354
+ # controlnet(s) inference
1355
+ if guess_mode and self.do_classifier_free_guidance:
1356
+ # Infer ControlNet only for the conditional batch.
1357
+ control_model_input = latents
1358
+ control_model_input = self.scheduler.scale_model_input(control_model_input, t)
1359
+ controlnet_prompt_embeds = prompt_embeds.chunk(2)[1]
1360
+ controlnet_added_cond_kwargs = {
1361
+ "text_embeds": add_text_embeds.chunk(2)[1],
1362
+ "time_ids": add_time_ids.chunk(2)[1],
1363
+ }
1364
+ else:
1365
+ control_model_input = latent_model_input
1366
+ controlnet_prompt_embeds = prompt_embeds
1367
+ controlnet_added_cond_kwargs = added_cond_kwargs
1368
+
1369
+ if isinstance(controlnet_keep[i], list):
1370
+ cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]
1371
+ else:
1372
+ controlnet_cond_scale = controlnet_conditioning_scale
1373
+ if isinstance(controlnet_cond_scale, list):
1374
+ controlnet_cond_scale = controlnet_cond_scale[0]
1375
+ cond_scale = controlnet_cond_scale * controlnet_keep[i]
1376
+
1377
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
1378
+ control_model_input,
1379
+ t,
1380
+ encoder_hidden_states=controlnet_prompt_embeds,
1381
+ controlnet_cond=image,
1382
+ conditioning_scale=cond_scale,
1383
+ guess_mode=guess_mode,
1384
+ added_cond_kwargs=controlnet_added_cond_kwargs,
1385
+ return_dict=False,
1386
+ )
1387
+
1388
+ if guess_mode and self.do_classifier_free_guidance:
1389
+ # Infered ControlNet only for the conditional batch.
1390
+ # To apply the output of ControlNet to both the unconditional and conditional batches,
1391
+ # add 0 to the unconditional batch to keep it unchanged.
1392
+ down_block_res_samples = [torch.cat([torch.zeros_like(d), d]) for d in down_block_res_samples]
1393
+ mid_block_res_sample = torch.cat([torch.zeros_like(mid_block_res_sample), mid_block_res_sample])
1394
+
1395
+ if ip_adapter_image is not None:
1396
+ added_cond_kwargs["image_embeds"] = image_embeds
1397
+
1398
+ # predict the noise residual
1399
+ noise_pred = self.unet(
1400
+ latent_model_input,
1401
+ t,
1402
+ encoder_hidden_states=prompt_embeds,
1403
+ timestep_cond=timestep_cond,
1404
+ cross_attention_kwargs=self.cross_attention_kwargs,
1405
+ down_block_additional_residuals=down_block_res_samples,
1406
+ mid_block_additional_residual=mid_block_res_sample,
1407
+ added_cond_kwargs=added_cond_kwargs,
1408
+ return_dict=False,
1409
+ )[0]
1410
+
1411
+ # perform guidance
1412
+ if self.do_classifier_free_guidance:
1413
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1414
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1415
+
1416
+ # compute the previous noisy sample x_t -> x_t-1
1417
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1418
+
1419
+ if callback_on_step_end is not None:
1420
+ callback_kwargs = {}
1421
+ for k in callback_on_step_end_tensor_inputs:
1422
+ callback_kwargs[k] = locals()[k]
1423
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1424
+
1425
+ latents = callback_outputs.pop("latents", latents)
1426
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1427
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1428
+
1429
+ # call the callback, if provided
1430
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1431
+ progress_bar.update()
1432
+ if callback is not None and i % callback_steps == 0:
1433
+ step_idx = i // getattr(self.scheduler, "order", 1)
1434
+ callback(step_idx, t, latents)
1435
+
1436
+ if not output_type == "latent":
1437
+ # make sure the VAE is in float32 mode, as it overflows in float16
1438
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
1439
+
1440
+ if needs_upcasting:
1441
+ self.upcast_vae()
1442
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1443
+
1444
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
1445
+
1446
+ # cast back to fp16 if needed
1447
+ if needs_upcasting:
1448
+ self.vae.to(dtype=torch.float16)
1449
+ else:
1450
+ image = latents
1451
+
1452
+ if not output_type == "latent":
1453
+ # apply watermark if available
1454
+ if self.watermark is not None:
1455
+ image = self.watermark.apply_watermark(image)
1456
+
1457
+ image = self.image_processor.postprocess(image, output_type=output_type)
1458
+
1459
+ # Offload all models
1460
+ self.maybe_free_model_hooks()
1461
+
1462
+ if not return_dict:
1463
+ return (image,)
1464
+
1465
+ return StableDiffusionXLPipelineOutput(images=image)