gaur3009 commited on
Commit
de6a69b
·
verified ·
1 Parent(s): 98d80f4

Create custom_pipeline.py

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