OzzyGT HF Staff commited on
Commit
c9aa484
·
verified ·
1 Parent(s): 932418f

Upload pipeline.py

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