multimodalart HF staff commited on
Commit
517af83
1 Parent(s): 79d2de9

Upload custom_pipeline.py

Browse files
Files changed (1) hide show
  1. custom_pipeline.py +987 -0
custom_pipeline.py ADDED
@@ -0,0 +1,987 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Harutatsu Akiyama and 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
+ import inspect
16
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
17
+
18
+ import PIL.Image
19
+ import torch
20
+ from transformers import CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer
21
+
22
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
23
+ from diffusers.loaders import FromSingleFileMixin, StableDiffusionXLLoraLoaderMixin, TextualInversionLoaderMixin
24
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
25
+ from diffusers.models.attention_processor import (
26
+ AttnProcessor2_0,
27
+ FusedAttnProcessor2_0,
28
+ LoRAAttnProcessor2_0,
29
+ LoRAXFormersAttnProcessor,
30
+ XFormersAttnProcessor,
31
+ )
32
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
33
+ from diffusers.schedulers import KarrasDiffusionSchedulers
34
+ from diffusers.utils import (
35
+ USE_PEFT_BACKEND,
36
+ deprecate,
37
+ is_invisible_watermark_available,
38
+ is_torch_xla_available,
39
+ logging,
40
+ replace_example_docstring,
41
+ scale_lora_layers,
42
+ )
43
+ from diffusers.utils.torch_utils import randn_tensor
44
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
45
+ from diffusers.pipelines.stable_diffusion_xl.pipeline_output import StableDiffusionXLPipelineOutput
46
+
47
+
48
+ if is_invisible_watermark_available():
49
+ from diffusers.pipelines.stable_diffusion_xl.watermark import StableDiffusionXLWatermarker
50
+
51
+ if is_torch_xla_available():
52
+ import torch_xla.core.xla_model as xm
53
+
54
+ XLA_AVAILABLE = True
55
+ else:
56
+ XLA_AVAILABLE = False
57
+
58
+
59
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
60
+
61
+ EXAMPLE_DOC_STRING = """
62
+ Examples:
63
+ ```py
64
+ >>> import torch
65
+ >>> from diffusers import StableDiffusionXLInstructPix2PixPipeline
66
+ >>> from diffusers.utils import load_image
67
+
68
+ >>> resolution = 768
69
+ >>> image = load_image(
70
+ ... "https://hf.co/datasets/diffusers/diffusers-images-docs/resolve/main/mountain.png"
71
+ ... ).resize((resolution, resolution))
72
+ >>> edit_instruction = "Turn sky into a cloudy one"
73
+
74
+ >>> pipe = StableDiffusionXLInstructPix2PixPipeline.from_pretrained(
75
+ ... "diffusers/sdxl-instructpix2pix-768", torch_dtype=torch.float16
76
+ ... ).to("cuda")
77
+
78
+ >>> edited_image = pipe(
79
+ ... prompt=edit_instruction,
80
+ ... image=image,
81
+ ... height=resolution,
82
+ ... width=resolution,
83
+ ... guidance_scale=3.0,
84
+ ... image_guidance_scale=1.5,
85
+ ... num_inference_steps=30,
86
+ ... ).images[0]
87
+ >>> edited_image
88
+ ```
89
+ """
90
+
91
+
92
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
93
+ def retrieve_latents(
94
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
95
+ ):
96
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
97
+ return encoder_output.latent_dist.sample(generator)
98
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
99
+ return encoder_output.latent_dist.mode()
100
+ elif hasattr(encoder_output, "latents"):
101
+ return encoder_output.latents
102
+ else:
103
+ raise AttributeError("Could not access latents of provided encoder_output")
104
+
105
+
106
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
107
+ """
108
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
109
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
110
+ """
111
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
112
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
113
+ # rescale the results from guidance (fixes overexposure)
114
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
115
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
116
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
117
+ return noise_cfg
118
+
119
+
120
+ class CosStableDiffusionXLInstructPix2PixPipeline(
121
+ DiffusionPipeline,
122
+ StableDiffusionMixin,
123
+ TextualInversionLoaderMixin,
124
+ FromSingleFileMixin,
125
+ StableDiffusionXLLoraLoaderMixin,
126
+ ):
127
+ r"""
128
+ Pipeline for pixel-level image editing by following text instructions. Based on Stable Diffusion XL.
129
+
130
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
131
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
132
+
133
+ The pipeline also inherits the following loading methods:
134
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
135
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
136
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
137
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
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 ([`CLIPTextModel`]):
143
+ Frozen text-encoder. Stable Diffusion XL uses the text portion of
144
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
145
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
146
+ text_encoder_2 ([` CLIPTextModelWithProjection`]):
147
+ Second frozen text-encoder. Stable Diffusion XL uses the text and pool portion of
148
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
149
+ specifically the
150
+ [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)
151
+ variant.
152
+ tokenizer (`CLIPTokenizer`):
153
+ Tokenizer of class
154
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
155
+ tokenizer_2 (`CLIPTokenizer`):
156
+ Second Tokenizer of class
157
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
158
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
159
+ scheduler ([`SchedulerMixin`]):
160
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
161
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
162
+ requires_aesthetics_score (`bool`, *optional*, defaults to `"False"`):
163
+ Whether the `unet` requires a aesthetic_score condition to be passed during inference. Also see the config
164
+ of `stabilityai/stable-diffusion-xl-refiner-1-0`.
165
+ force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"True"`):
166
+ Whether the negative prompt embeddings shall be forced to always be set to 0. Also see the config of
167
+ `stabilityai/stable-diffusion-xl-base-1-0`.
168
+ add_watermarker (`bool`, *optional*):
169
+ Whether to use the [invisible_watermark library](https://github.com/ShieldMnt/invisible-watermark/) to
170
+ watermark output images. If not defined, it will default to True if the package is installed, otherwise no
171
+ watermarker will be used.
172
+ """
173
+
174
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->unet->vae"
175
+ _optional_components = ["tokenizer", "tokenizer_2", "text_encoder", "text_encoder_2"]
176
+
177
+ def __init__(
178
+ self,
179
+ vae: AutoencoderKL,
180
+ text_encoder: CLIPTextModel,
181
+ text_encoder_2: CLIPTextModelWithProjection,
182
+ tokenizer: CLIPTokenizer,
183
+ tokenizer_2: CLIPTokenizer,
184
+ unet: UNet2DConditionModel,
185
+ scheduler: KarrasDiffusionSchedulers,
186
+ force_zeros_for_empty_prompt: bool = True,
187
+ add_watermarker: Optional[bool] = None,
188
+ ):
189
+ super().__init__()
190
+
191
+ self.register_modules(
192
+ vae=vae,
193
+ text_encoder=text_encoder,
194
+ text_encoder_2=text_encoder_2,
195
+ tokenizer=tokenizer,
196
+ tokenizer_2=tokenizer_2,
197
+ unet=unet,
198
+ scheduler=scheduler,
199
+ )
200
+ self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
201
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
202
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
203
+ self.default_sample_size = self.unet.config.sample_size
204
+
205
+ add_watermarker = add_watermarker if add_watermarker is not None else is_invisible_watermark_available()
206
+
207
+ if add_watermarker:
208
+ self.watermark = StableDiffusionXLWatermarker()
209
+ else:
210
+ self.watermark = None
211
+
212
+ def encode_prompt(
213
+ self,
214
+ prompt: str,
215
+ prompt_2: Optional[str] = None,
216
+ device: Optional[torch.device] = None,
217
+ num_images_per_prompt: int = 1,
218
+ do_classifier_free_guidance: bool = True,
219
+ negative_prompt: Optional[str] = None,
220
+ negative_prompt_2: Optional[str] = None,
221
+ prompt_embeds: Optional[torch.FloatTensor] = None,
222
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
223
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
224
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
225
+ lora_scale: Optional[float] = None,
226
+ ):
227
+ r"""
228
+ Encodes the prompt into text encoder hidden states.
229
+
230
+ Args:
231
+ prompt (`str` or `List[str]`, *optional*):
232
+ prompt to be encoded
233
+ prompt_2 (`str` or `List[str]`, *optional*):
234
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
235
+ used in both text-encoders
236
+ device: (`torch.device`):
237
+ torch device
238
+ num_images_per_prompt (`int`):
239
+ number of images that should be generated per prompt
240
+ do_classifier_free_guidance (`bool`):
241
+ whether to use classifier free guidance or not
242
+ negative_prompt (`str` or `List[str]`, *optional*):
243
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
244
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
245
+ less than `1`).
246
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
247
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
248
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
249
+ prompt_embeds (`torch.FloatTensor`, *optional*):
250
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
251
+ provided, text embeddings will be generated from `prompt` input argument.
252
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
253
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
254
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
255
+ argument.
256
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
257
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
258
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
259
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
260
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
261
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
262
+ input argument.
263
+ lora_scale (`float`, *optional*):
264
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
265
+ """
266
+ device = device or self._execution_device
267
+
268
+ # set lora scale so that monkey patched LoRA
269
+ # function of text encoder can correctly access it
270
+ if lora_scale is not None and isinstance(self, StableDiffusionXLLoraLoaderMixin):
271
+ self._lora_scale = lora_scale
272
+
273
+ # dynamically adjust the LoRA scale
274
+ if self.text_encoder is not None:
275
+ if not USE_PEFT_BACKEND:
276
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
277
+ else:
278
+ scale_lora_layers(self.text_encoder, lora_scale)
279
+
280
+ if self.text_encoder_2 is not None:
281
+ if not USE_PEFT_BACKEND:
282
+ adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
283
+ else:
284
+ scale_lora_layers(self.text_encoder_2, lora_scale)
285
+
286
+ if prompt is not None and isinstance(prompt, str):
287
+ batch_size = 1
288
+ elif prompt is not None and isinstance(prompt, list):
289
+ batch_size = len(prompt)
290
+ else:
291
+ batch_size = prompt_embeds.shape[0]
292
+
293
+ # Define tokenizers and text encoders
294
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
295
+ text_encoders = (
296
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
297
+ )
298
+
299
+ if prompt_embeds is None:
300
+ prompt_2 = prompt_2 or prompt
301
+ # textual inversion: process multi-vector tokens if necessary
302
+ prompt_embeds_list = []
303
+ prompts = [prompt, prompt_2]
304
+ for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
305
+ if isinstance(self, TextualInversionLoaderMixin):
306
+ prompt = self.maybe_convert_prompt(prompt, tokenizer)
307
+
308
+ text_inputs = tokenizer(
309
+ prompt,
310
+ padding="max_length",
311
+ max_length=tokenizer.model_max_length,
312
+ truncation=True,
313
+ return_tensors="pt",
314
+ )
315
+
316
+ text_input_ids = text_inputs.input_ids
317
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
318
+
319
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
320
+ text_input_ids, untruncated_ids
321
+ ):
322
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
323
+ logger.warning(
324
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
325
+ f" {tokenizer.model_max_length} tokens: {removed_text}"
326
+ )
327
+
328
+ prompt_embeds = text_encoder(
329
+ text_input_ids.to(device),
330
+ output_hidden_states=True,
331
+ )
332
+
333
+ # We are only ALWAYS interested in the pooled output of the final text encoder
334
+ pooled_prompt_embeds = prompt_embeds[0]
335
+ prompt_embeds = prompt_embeds.hidden_states[-2]
336
+
337
+ prompt_embeds_list.append(prompt_embeds)
338
+
339
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
340
+
341
+ # get unconditional embeddings for classifier free guidance
342
+ zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
343
+ if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
344
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
345
+ negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
346
+ elif do_classifier_free_guidance and negative_prompt_embeds is None:
347
+ negative_prompt = negative_prompt or ""
348
+ negative_prompt_2 = negative_prompt_2 or negative_prompt
349
+
350
+ uncond_tokens: List[str]
351
+ if prompt is not None and type(prompt) is not type(negative_prompt):
352
+ raise TypeError(
353
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
354
+ f" {type(prompt)}."
355
+ )
356
+ elif isinstance(negative_prompt, str):
357
+ uncond_tokens = [negative_prompt, negative_prompt_2]
358
+ elif batch_size != len(negative_prompt):
359
+ raise ValueError(
360
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
361
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
362
+ " the batch size of `prompt`."
363
+ )
364
+ else:
365
+ uncond_tokens = [negative_prompt, negative_prompt_2]
366
+
367
+ negative_prompt_embeds_list = []
368
+ for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
369
+ if isinstance(self, TextualInversionLoaderMixin):
370
+ negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
371
+
372
+ max_length = prompt_embeds.shape[1]
373
+ uncond_input = tokenizer(
374
+ negative_prompt,
375
+ padding="max_length",
376
+ max_length=max_length,
377
+ truncation=True,
378
+ return_tensors="pt",
379
+ )
380
+
381
+ negative_prompt_embeds = text_encoder(
382
+ uncond_input.input_ids.to(device),
383
+ output_hidden_states=True,
384
+ )
385
+ # We are only ALWAYS interested in the pooled output of the final text encoder
386
+ negative_pooled_prompt_embeds = negative_prompt_embeds[0]
387
+ negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
388
+
389
+ negative_prompt_embeds_list.append(negative_prompt_embeds)
390
+
391
+ negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
392
+
393
+ prompt_embeds_dtype = self.text_encoder_2.dtype if self.text_encoder_2 is not None else self.unet.dtype
394
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
395
+ bs_embed, seq_len, _ = prompt_embeds.shape
396
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
397
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
398
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
399
+
400
+ if do_classifier_free_guidance:
401
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
402
+ seq_len = negative_prompt_embeds.shape[1]
403
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
404
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
405
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
406
+
407
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
408
+ bs_embed * num_images_per_prompt, -1
409
+ )
410
+ if do_classifier_free_guidance:
411
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
412
+ bs_embed * num_images_per_prompt, -1
413
+ )
414
+
415
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
416
+
417
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
418
+ def prepare_extra_step_kwargs(self, generator, eta):
419
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
420
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
421
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
422
+ # and should be between [0, 1]
423
+
424
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
425
+ extra_step_kwargs = {}
426
+ if accepts_eta:
427
+ extra_step_kwargs["eta"] = eta
428
+
429
+ # check if the scheduler accepts generator
430
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
431
+ if accepts_generator:
432
+ extra_step_kwargs["generator"] = generator
433
+ return extra_step_kwargs
434
+
435
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_instruct_pix2pix.StableDiffusionInstructPix2PixPipeline.check_inputs
436
+ def check_inputs(
437
+ self,
438
+ prompt,
439
+ callback_steps,
440
+ negative_prompt=None,
441
+ prompt_embeds=None,
442
+ negative_prompt_embeds=None,
443
+ callback_on_step_end_tensor_inputs=None,
444
+ ):
445
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
446
+ raise ValueError(
447
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
448
+ f" {type(callback_steps)}."
449
+ )
450
+
451
+ if callback_on_step_end_tensor_inputs is not None and not all(
452
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
453
+ ):
454
+ raise ValueError(
455
+ 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]}"
456
+ )
457
+
458
+ if prompt is not None and prompt_embeds is not None:
459
+ raise ValueError(
460
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
461
+ " only forward one of the two."
462
+ )
463
+ elif prompt is None and prompt_embeds is None:
464
+ raise ValueError(
465
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
466
+ )
467
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
468
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
469
+
470
+ if negative_prompt is not None and negative_prompt_embeds is not None:
471
+ raise ValueError(
472
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
473
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
474
+ )
475
+
476
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
477
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
478
+ raise ValueError(
479
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
480
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
481
+ f" {negative_prompt_embeds.shape}."
482
+ )
483
+
484
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
485
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
486
+ shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
487
+ if isinstance(generator, list) and len(generator) != batch_size:
488
+ raise ValueError(
489
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
490
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
491
+ )
492
+
493
+ if latents is None:
494
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
495
+ else:
496
+ latents = latents.to(device)
497
+
498
+ # scale the initial noise by the standard deviation required by the scheduler
499
+ latents = latents * self.scheduler.init_noise_sigma
500
+ return latents
501
+
502
+ def prepare_image_latents(
503
+ self, image, batch_size, num_images_per_prompt, dtype, device, do_classifier_free_guidance, generator=None
504
+ ):
505
+ if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
506
+ raise ValueError(
507
+ f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
508
+ )
509
+
510
+ image = image.to(device=device, dtype=dtype)
511
+
512
+ batch_size = batch_size * num_images_per_prompt
513
+
514
+ if image.shape[1] == 4:
515
+ image_latents = image
516
+ else:
517
+ # make sure the VAE is in float32 mode, as it overflows in float16
518
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
519
+ if needs_upcasting:
520
+ self.upcast_vae()
521
+ image = image.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
522
+
523
+ image_latents = retrieve_latents(self.vae.encode(image), sample_mode="argmax")
524
+
525
+ # cast back to fp16 if needed
526
+ if needs_upcasting:
527
+ self.vae.to(dtype=torch.float16)
528
+
529
+ if batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] == 0:
530
+ # expand image_latents for batch_size
531
+ deprecation_message = (
532
+ f"You have passed {batch_size} text prompts (`prompt`), but only {image_latents.shape[0]} initial"
533
+ " images (`image`). Initial images are now duplicating to match the number of text prompts. Note"
534
+ " that this behavior is deprecated and will be removed in a version 1.0.0. Please make sure to update"
535
+ " your script to pass as many initial images as text prompts to suppress this warning."
536
+ )
537
+ deprecate("len(prompt) != len(image)", "1.0.0", deprecation_message, standard_warn=False)
538
+ additional_image_per_prompt = batch_size // image_latents.shape[0]
539
+ image_latents = torch.cat([image_latents] * additional_image_per_prompt, dim=0)
540
+ elif batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] != 0:
541
+ raise ValueError(
542
+ f"Cannot duplicate `image` of batch size {image_latents.shape[0]} to {batch_size} text prompts."
543
+ )
544
+ else:
545
+ image_latents = torch.cat([image_latents], dim=0)
546
+
547
+ if do_classifier_free_guidance:
548
+ uncond_image_latents = torch.zeros_like(image_latents)
549
+ image_latents = torch.cat([image_latents, image_latents, uncond_image_latents], dim=0)
550
+
551
+ if image_latents.dtype != self.vae.dtype:
552
+ image_latents = image_latents.to(dtype=self.vae.dtype)
553
+
554
+ return image_latents
555
+
556
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline._get_add_time_ids
557
+ def _get_add_time_ids(
558
+ self, original_size, crops_coords_top_left, target_size, dtype, text_encoder_projection_dim=None
559
+ ):
560
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
561
+
562
+ passed_add_embed_dim = (
563
+ self.unet.config.addition_time_embed_dim * len(add_time_ids) + text_encoder_projection_dim
564
+ )
565
+ expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
566
+
567
+ if expected_add_embed_dim != passed_add_embed_dim:
568
+ raise ValueError(
569
+ 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`."
570
+ )
571
+
572
+ add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
573
+ return add_time_ids
574
+
575
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.upcast_vae
576
+ def upcast_vae(self):
577
+ dtype = self.vae.dtype
578
+ self.vae.to(dtype=torch.float32)
579
+ use_torch_2_0_or_xformers = isinstance(
580
+ self.vae.decoder.mid_block.attentions[0].processor,
581
+ (
582
+ AttnProcessor2_0,
583
+ XFormersAttnProcessor,
584
+ LoRAXFormersAttnProcessor,
585
+ LoRAAttnProcessor2_0,
586
+ FusedAttnProcessor2_0,
587
+ ),
588
+ )
589
+ # if xformers or torch_2_0 is used attention block does not need
590
+ # to be in float32 which can save lots of memory
591
+ if use_torch_2_0_or_xformers:
592
+ self.vae.post_quant_conv.to(dtype)
593
+ self.vae.decoder.conv_in.to(dtype)
594
+ self.vae.decoder.mid_block.to(dtype)
595
+
596
+ @torch.no_grad()
597
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
598
+ def __call__(
599
+ self,
600
+ prompt: Union[str, List[str]] = None,
601
+ prompt_2: Optional[Union[str, List[str]]] = None,
602
+ image: PipelineImageInput = None,
603
+ height: Optional[int] = None,
604
+ width: Optional[int] = None,
605
+ num_inference_steps: int = 100,
606
+ denoising_end: Optional[float] = None,
607
+ guidance_scale: float = 5.0,
608
+ image_guidance_scale: float = 1.5,
609
+ negative_prompt: Optional[Union[str, List[str]]] = None,
610
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
611
+ num_images_per_prompt: Optional[int] = 1,
612
+ eta: float = 0.0,
613
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
614
+ latents: Optional[torch.FloatTensor] = None,
615
+ prompt_embeds: Optional[torch.FloatTensor] = None,
616
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
617
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
618
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
619
+ output_type: Optional[str] = "pil",
620
+ return_dict: bool = True,
621
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
622
+ callback_steps: int = 1,
623
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
624
+ guidance_rescale: float = 0.0,
625
+ original_size: Tuple[int, int] = None,
626
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
627
+ target_size: Tuple[int, int] = None,
628
+ ):
629
+ r"""
630
+ Function invoked when calling the pipeline for generation.
631
+
632
+ Args:
633
+ prompt (`str` or `List[str]`, *optional*):
634
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
635
+ instead.
636
+ prompt_2 (`str` or `List[str]`, *optional*):
637
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
638
+ used in both text-encoders
639
+ image (`torch.FloatTensor` or `PIL.Image.Image` or `np.ndarray` or `List[torch.FloatTensor]` or `List[PIL.Image.Image]` or `List[np.ndarray]`):
640
+ The image(s) to modify with the pipeline.
641
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
642
+ The height in pixels of the generated image.
643
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
644
+ The width in pixels of the generated image.
645
+ num_inference_steps (`int`, *optional*, defaults to 50):
646
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
647
+ expense of slower inference.
648
+ denoising_end (`float`, *optional*):
649
+ When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
650
+ completed before it is intentionally prematurely terminated. As a result, the returned sample will
651
+ still retain a substantial amount of noise as determined by the discrete timesteps selected by the
652
+ scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
653
+ "Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
654
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)
655
+ guidance_scale (`float`, *optional*, defaults to 5.0):
656
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
657
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
658
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
659
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
660
+ usually at the expense of lower image quality.
661
+ image_guidance_scale (`float`, *optional*, defaults to 1.5):
662
+ Image guidance scale is to push the generated image towards the initial image `image`. Image guidance
663
+ scale is enabled by setting `image_guidance_scale > 1`. Higher image guidance scale encourages to
664
+ generate images that are closely linked to the source image `image`, usually at the expense of lower
665
+ image quality. This pipeline requires a value of at least `1`.
666
+ negative_prompt (`str` or `List[str]`, *optional*):
667
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
668
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
669
+ less than `1`).
670
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
671
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
672
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders.
673
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
674
+ The number of images to generate per prompt.
675
+ eta (`float`, *optional*, defaults to 0.0):
676
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
677
+ [`schedulers.DDIMScheduler`], will be ignored for others.
678
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
679
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
680
+ to make generation deterministic.
681
+ latents (`torch.FloatTensor`, *optional*):
682
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
683
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
684
+ tensor will ge generated by sampling using the supplied random `generator`.
685
+ prompt_embeds (`torch.FloatTensor`, *optional*):
686
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
687
+ provided, text embeddings will be generated from `prompt` input argument.
688
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
689
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
690
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
691
+ argument.
692
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
693
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
694
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
695
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
696
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
697
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
698
+ input argument.
699
+ output_type (`str`, *optional*, defaults to `"pil"`):
700
+ The output format of the generate image. Choose between
701
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
702
+ return_dict (`bool`, *optional*, defaults to `True`):
703
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] instead of a
704
+ plain tuple.
705
+ callback (`Callable`, *optional*):
706
+ A function that will be called every `callback_steps` steps during inference. The function will be
707
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
708
+ callback_steps (`int`, *optional*, defaults to 1):
709
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
710
+ called at every step.
711
+ cross_attention_kwargs (`dict`, *optional*):
712
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
713
+ `self.processor` in
714
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
715
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
716
+ Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
717
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
718
+ [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
719
+ Guidance rescale factor should fix overexposure when using zero terminal SNR.
720
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
721
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
722
+ `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
723
+ explained in section 2.2 of
724
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
725
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
726
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
727
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
728
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
729
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
730
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
731
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
732
+ not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
733
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
734
+ aesthetic_score (`float`, *optional*, defaults to 6.0):
735
+ Used to simulate an aesthetic score of the generated image by influencing the positive text condition.
736
+ Part of SDXL's micro-conditioning as explained in section 2.2 of
737
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
738
+ negative_aesthetic_score (`float`, *optional*, defaults to 2.5):
739
+ Part of SDXL's micro-conditioning as explained in section 2.2 of
740
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). Can be used to
741
+ simulate an aesthetic score of the generated image by influencing the negative text condition.
742
+
743
+ Examples:
744
+
745
+ Returns:
746
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] or `tuple`:
747
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
748
+ `tuple`. When returning a tuple, the first element is a list with the generated images.
749
+ """
750
+ # 0. Default height and width to unet
751
+ height = height or self.default_sample_size * self.vae_scale_factor
752
+ width = width or self.default_sample_size * self.vae_scale_factor
753
+
754
+ original_size = original_size or (height, width)
755
+ target_size = target_size or (height, width)
756
+
757
+ # 1. Check inputs. Raise error if not correct
758
+ self.check_inputs(prompt, callback_steps, negative_prompt, prompt_embeds, negative_prompt_embeds)
759
+
760
+ if image is None:
761
+ raise ValueError("`image` input cannot be undefined.")
762
+
763
+ # 2. Define call parameters
764
+ if prompt is not None and isinstance(prompt, str):
765
+ batch_size = 1
766
+ elif prompt is not None and isinstance(prompt, list):
767
+ batch_size = len(prompt)
768
+ else:
769
+ batch_size = prompt_embeds.shape[0]
770
+
771
+ device = self._execution_device
772
+
773
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
774
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
775
+ # corresponds to doing no classifier free guidance.
776
+ do_classifier_free_guidance = guidance_scale > 1.0 and image_guidance_scale >= 1.0
777
+
778
+ # 3. Encode input prompt
779
+ text_encoder_lora_scale = (
780
+ cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
781
+ )
782
+ (
783
+ prompt_embeds,
784
+ negative_prompt_embeds,
785
+ pooled_prompt_embeds,
786
+ negative_pooled_prompt_embeds,
787
+ ) = self.encode_prompt(
788
+ prompt=prompt,
789
+ prompt_2=prompt_2,
790
+ device=device,
791
+ num_images_per_prompt=num_images_per_prompt,
792
+ do_classifier_free_guidance=do_classifier_free_guidance,
793
+ negative_prompt=negative_prompt,
794
+ negative_prompt_2=negative_prompt_2,
795
+ prompt_embeds=prompt_embeds,
796
+ negative_prompt_embeds=negative_prompt_embeds,
797
+ pooled_prompt_embeds=pooled_prompt_embeds,
798
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
799
+ lora_scale=text_encoder_lora_scale,
800
+ )
801
+
802
+ # 4. Preprocess image
803
+ image = self.image_processor.preprocess(image, height=height, width=width).to(device)
804
+
805
+ # 5. Prepare timesteps
806
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
807
+ timesteps = self.scheduler.timesteps
808
+
809
+ # 6. Prepare Image latents
810
+ image_latents = self.prepare_image_latents(
811
+ image,
812
+ batch_size,
813
+ num_images_per_prompt,
814
+ prompt_embeds.dtype,
815
+ device,
816
+ do_classifier_free_guidance,
817
+ )
818
+
819
+ image_latents = image_latents * self.vae.config.scaling_factor
820
+
821
+ # 7. Prepare latent variables
822
+ num_channels_latents = self.vae.config.latent_channels
823
+ latents = self.prepare_latents(
824
+ batch_size * num_images_per_prompt,
825
+ num_channels_latents,
826
+ height,
827
+ width,
828
+ prompt_embeds.dtype,
829
+ device,
830
+ generator,
831
+ latents,
832
+ )
833
+
834
+ # 8. Check that shapes of latents and image match the UNet channels
835
+ num_channels_image = image_latents.shape[1]
836
+ if num_channels_latents + num_channels_image != self.unet.config.in_channels:
837
+ raise ValueError(
838
+ f"Incorrect configuration settings! The config of `pipeline.unet`: {self.unet.config} expects"
839
+ f" {self.unet.config.in_channels} but received `num_channels_latents`: {num_channels_latents} +"
840
+ f" `num_channels_image`: {num_channels_image} "
841
+ f" = {num_channels_latents + num_channels_image}. Please verify the config of"
842
+ " `pipeline.unet` or your `image` input."
843
+ )
844
+
845
+ # 9. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
846
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
847
+
848
+ # 10. Prepare added time ids & embeddings
849
+ add_text_embeds = pooled_prompt_embeds
850
+ if self.text_encoder_2 is None:
851
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
852
+ else:
853
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
854
+
855
+ add_time_ids = self._get_add_time_ids(
856
+ original_size,
857
+ crops_coords_top_left,
858
+ target_size,
859
+ dtype=prompt_embeds.dtype,
860
+ text_encoder_projection_dim=text_encoder_projection_dim,
861
+ )
862
+
863
+ if do_classifier_free_guidance:
864
+ # The extra concat similar to how it's done in SD InstructPix2Pix.
865
+ prompt_embeds = torch.cat([prompt_embeds, negative_prompt_embeds, negative_prompt_embeds], dim=0)
866
+ add_text_embeds = torch.cat(
867
+ [add_text_embeds, negative_pooled_prompt_embeds, negative_pooled_prompt_embeds], dim=0
868
+ )
869
+ add_time_ids = torch.cat([add_time_ids, add_time_ids, add_time_ids], dim=0)
870
+
871
+ prompt_embeds = prompt_embeds.to(device)
872
+ add_text_embeds = add_text_embeds.to(device)
873
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
874
+
875
+ # 11. Denoising loop
876
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
877
+ if denoising_end is not None and isinstance(denoising_end, float) and denoising_end > 0 and denoising_end < 1:
878
+ discrete_timestep_cutoff = int(
879
+ round(
880
+ self.scheduler.config.num_train_timesteps
881
+ - (denoising_end * self.scheduler.config.num_train_timesteps)
882
+ )
883
+ )
884
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
885
+ timesteps = timesteps[:num_inference_steps]
886
+
887
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
888
+ for i, t in enumerate(timesteps):
889
+ # Expand the latents if we are doing classifier free guidance.
890
+ # The latents are expanded 3 times because for pix2pix the guidance
891
+ # is applied for both the text and the input image.
892
+ latent_model_input = torch.cat([latents] * 3) if do_classifier_free_guidance else latents
893
+
894
+ # concat latents, image_latents in the channel dimension
895
+ scaled_latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
896
+ scaled_latent_model_input = torch.cat([scaled_latent_model_input, image_latents], dim=1)
897
+
898
+ # predict the noise residual
899
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
900
+ noise_pred = self.unet(
901
+ scaled_latent_model_input,
902
+ t,
903
+ encoder_hidden_states=prompt_embeds,
904
+ cross_attention_kwargs=cross_attention_kwargs,
905
+ added_cond_kwargs=added_cond_kwargs,
906
+ return_dict=False,
907
+ )[0]
908
+
909
+ # perform guidance
910
+ if do_classifier_free_guidance:
911
+ noise_pred_text, noise_pred_image, noise_pred_uncond = noise_pred.chunk(3)
912
+ noise_pred = (
913
+ noise_pred_uncond
914
+ + guidance_scale * (noise_pred_text - noise_pred_image)
915
+ + image_guidance_scale * (noise_pred_image - noise_pred_uncond)
916
+ )
917
+
918
+ if do_classifier_free_guidance and guidance_rescale > 0.0:
919
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
920
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
921
+
922
+ # compute the previous noisy sample x_t -> x_t-1
923
+ latents_dtype = latents.dtype
924
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
925
+ if latents.dtype != latents_dtype:
926
+ if torch.backends.mps.is_available():
927
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
928
+ latents = latents.to(latents_dtype)
929
+
930
+ # call the callback, if provided
931
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
932
+ progress_bar.update()
933
+ if callback is not None and i % callback_steps == 0:
934
+ step_idx = i // getattr(self.scheduler, "order", 1)
935
+ callback(step_idx, t, latents)
936
+
937
+ if XLA_AVAILABLE:
938
+ xm.mark_step()
939
+
940
+ if not output_type == "latent":
941
+ # make sure the VAE is in float32 mode, as it overflows in float16
942
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
943
+
944
+ if needs_upcasting:
945
+ self.upcast_vae()
946
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
947
+ elif latents.dtype != self.vae.dtype:
948
+ if torch.backends.mps.is_available():
949
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
950
+ self.vae = self.vae.to(latents.dtype)
951
+
952
+ # unscale/denormalize the latents
953
+ # denormalize with the mean and std if available and not None
954
+ has_latents_mean = hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None
955
+ has_latents_std = hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None
956
+ if has_latents_mean and has_latents_std:
957
+ latents_mean = (
958
+ torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1).to(latents.device, latents.dtype)
959
+ )
960
+ latents_std = (
961
+ torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1).to(latents.device, latents.dtype)
962
+ )
963
+ latents = latents * latents_std / self.vae.config.scaling_factor + latents_mean
964
+ else:
965
+ latents = latents / self.vae.config.scaling_factor
966
+
967
+ image = self.vae.decode(latents, return_dict=False)[0]
968
+
969
+ # cast back to fp16 if needed
970
+ if needs_upcasting:
971
+ self.vae.to(dtype=torch.float16)
972
+ else:
973
+ return StableDiffusionXLPipelineOutput(images=latents)
974
+
975
+ # apply watermark if available
976
+ if self.watermark is not None:
977
+ image = self.watermark.apply_watermark(image)
978
+
979
+ image = self.image_processor.postprocess(image, output_type=output_type)
980
+
981
+ # Offload all models
982
+ self.maybe_free_model_hooks()
983
+
984
+ if not return_dict:
985
+ return (image,)
986
+
987
+ return StableDiffusionXLPipelineOutput(images=image)