Niansuh commited on
Commit
f082f11
1 Parent(s): 38ee86f

Create custom_pipeline.py

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