patrickvonplaten commited on
Commit
8ae0dea
1 Parent(s): 648f989

Create my_pipeline.py

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