SunderAli17 commited on
Commit
be1d2b9
·
verified ·
1 Parent(s): bb86011

Create stage1_sdxl_pipeline.py

Browse files
Files changed (1) hide show
  1. pipelines/stage1_sdxl_pipeline.py +1270 -0
pipelines/stage1_sdxl_pipeline.py ADDED
@@ -0,0 +1,1270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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 (
20
+ CLIPImageProcessor,
21
+ CLIPTextModel,
22
+ CLIPTextModelWithProjection,
23
+ CLIPTokenizer,
24
+ CLIPVisionModelWithProjection,
25
+ )
26
+
27
+ from ...image_processor import PipelineImageInput, VaeImageProcessor
28
+ from ...loaders import (
29
+ FromSingleFileMixin,
30
+ IPAdapterMixin,
31
+ StableDiffusionXLLoraLoaderMixin,
32
+ TextualInversionLoaderMixin,
33
+ )
34
+ from ...models import AutoencoderKL, ImageProjection, UNet2DConditionModel
35
+ from ...models.attention_processor import (
36
+ AttnProcessor2_0,
37
+ FusedAttnProcessor2_0,
38
+ LoRAAttnProcessor2_0,
39
+ LoRAXFormersAttnProcessor,
40
+ XFormersAttnProcessor,
41
+ )
42
+ from ...models.lora import adjust_lora_scale_text_encoder
43
+ from ...schedulers import KarrasDiffusionSchedulers
44
+ from ...utils import (
45
+ USE_PEFT_BACKEND,
46
+ deprecate,
47
+ is_invisible_watermark_available,
48
+ is_torch_xla_available,
49
+ logging,
50
+ replace_example_docstring,
51
+ scale_lora_layers,
52
+ unscale_lora_layers,
53
+ )
54
+ from ...utils.torch_utils import randn_tensor
55
+ from ..pipeline_utils import DiffusionPipeline, StableDiffusionMixin
56
+ from .pipeline_output import StableDiffusionXLPipelineOutput
57
+
58
+
59
+ if is_invisible_watermark_available():
60
+ from .watermark import StableDiffusionXLWatermarker
61
+
62
+ if is_torch_xla_available():
63
+ import torch_xla.core.xla_model as xm
64
+
65
+ XLA_AVAILABLE = True
66
+ else:
67
+ XLA_AVAILABLE = False
68
+
69
+
70
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
71
+
72
+ EXAMPLE_DOC_STRING = """
73
+ Examples:
74
+ ```py
75
+ >>> import torch
76
+ >>> from diffusers import StableDiffusionXLPipeline
77
+ >>> pipe = StableDiffusionXLPipeline.from_pretrained(
78
+ ... "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
79
+ ... )
80
+ >>> pipe = pipe.to("cuda")
81
+ >>> prompt = "a photo of an astronaut riding a horse on mars"
82
+ >>> image = pipe(prompt).images[0]
83
+ ```
84
+ """
85
+
86
+
87
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
88
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
89
+ """
90
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
91
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
92
+ """
93
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
94
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
95
+ # rescale the results from guidance (fixes overexposure)
96
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
97
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
98
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
99
+ return noise_cfg
100
+
101
+
102
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
103
+ def retrieve_timesteps(
104
+ scheduler,
105
+ num_inference_steps: Optional[int] = None,
106
+ device: Optional[Union[str, torch.device]] = None,
107
+ timesteps: Optional[List[int]] = None,
108
+ **kwargs,
109
+ ):
110
+ """
111
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
112
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
113
+ Args:
114
+ scheduler (`SchedulerMixin`):
115
+ The scheduler to get timesteps from.
116
+ num_inference_steps (`int`):
117
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
118
+ must be `None`.
119
+ device (`str` or `torch.device`, *optional*):
120
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
121
+ timesteps (`List[int]`, *optional*):
122
+ Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
123
+ timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
124
+ must be `None`.
125
+ Returns:
126
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
127
+ second element is the number of inference steps.
128
+ """
129
+ if timesteps is not None:
130
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
131
+ if not accepts_timesteps:
132
+ raise ValueError(
133
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
134
+ f" timestep schedules. Please check whether you are using the correct scheduler."
135
+ )
136
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
137
+ timesteps = scheduler.timesteps
138
+ num_inference_steps = len(timesteps)
139
+ else:
140
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
141
+ timesteps = scheduler.timesteps
142
+ return timesteps, num_inference_steps
143
+
144
+
145
+ class StableDiffusionXLPipeline(
146
+ DiffusionPipeline,
147
+ StableDiffusionMixin,
148
+ FromSingleFileMixin,
149
+ StableDiffusionXLLoraLoaderMixin,
150
+ TextualInversionLoaderMixin,
151
+ IPAdapterMixin,
152
+ ):
153
+ r"""
154
+ Pipeline for text-to-image generation using Stable Diffusion XL.
155
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
156
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
157
+ The pipeline also inherits the following loading methods:
158
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
159
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
160
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
161
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
162
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
163
+ Args:
164
+ vae ([`AutoencoderKL`]):
165
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
166
+ text_encoder ([`CLIPTextModel`]):
167
+ Frozen text-encoder. Stable Diffusion XL uses the text portion of
168
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
169
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
170
+ text_encoder_2 ([` CLIPTextModelWithProjection`]):
171
+ Second frozen text-encoder. Stable Diffusion XL uses the text and pool portion of
172
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
173
+ specifically the
174
+ [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)
175
+ variant.
176
+ tokenizer (`CLIPTokenizer`):
177
+ Tokenizer of class
178
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
179
+ tokenizer_2 (`CLIPTokenizer`):
180
+ Second Tokenizer of class
181
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
182
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
183
+ scheduler ([`SchedulerMixin`]):
184
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
185
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
186
+ force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"True"`):
187
+ Whether the negative prompt embeddings shall be forced to always be set to 0. Also see the config of
188
+ `stabilityai/stable-diffusion-xl-base-1-0`.
189
+ add_watermarker (`bool`, *optional*):
190
+ Whether to use the [invisible_watermark library](https://github.com/ShieldMnt/invisible-watermark/) to
191
+ watermark output images. If not defined, it will default to True if the package is installed, otherwise no
192
+ watermarker will be used.
193
+ """
194
+
195
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->image_encoder->unet->vae"
196
+ _optional_components = [
197
+ "tokenizer",
198
+ "tokenizer_2",
199
+ "text_encoder",
200
+ "text_encoder_2",
201
+ "image_encoder",
202
+ "feature_extractor",
203
+ ]
204
+ _callback_tensor_inputs = [
205
+ "latents",
206
+ "prompt_embeds",
207
+ "negative_prompt_embeds",
208
+ "add_text_embeds",
209
+ "add_time_ids",
210
+ "negative_pooled_prompt_embeds",
211
+ "negative_add_time_ids",
212
+ ]
213
+
214
+ def __init__(
215
+ self,
216
+ vae: AutoencoderKL,
217
+ text_encoder: CLIPTextModel,
218
+ text_encoder_2: CLIPTextModelWithProjection,
219
+ tokenizer: CLIPTokenizer,
220
+ tokenizer_2: CLIPTokenizer,
221
+ unet: UNet2DConditionModel,
222
+ scheduler: KarrasDiffusionSchedulers,
223
+ image_encoder: CLIPVisionModelWithProjection = None,
224
+ feature_extractor: CLIPImageProcessor = None,
225
+ force_zeros_for_empty_prompt: bool = True,
226
+ add_watermarker: Optional[bool] = None,
227
+ ):
228
+ super().__init__()
229
+
230
+ self.register_modules(
231
+ vae=vae,
232
+ text_encoder=text_encoder,
233
+ text_encoder_2=text_encoder_2,
234
+ tokenizer=tokenizer,
235
+ tokenizer_2=tokenizer_2,
236
+ unet=unet,
237
+ scheduler=scheduler,
238
+ image_encoder=image_encoder,
239
+ feature_extractor=feature_extractor,
240
+ )
241
+ self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
242
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
243
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
244
+
245
+ self.default_sample_size = self.unet.config.sample_size
246
+
247
+ add_watermarker = add_watermarker if add_watermarker is not None else is_invisible_watermark_available()
248
+
249
+ if add_watermarker:
250
+ self.watermark = StableDiffusionXLWatermarker()
251
+ else:
252
+ self.watermark = None
253
+
254
+ def encode_prompt(
255
+ self,
256
+ prompt: str,
257
+ prompt_2: Optional[str] = None,
258
+ device: Optional[torch.device] = None,
259
+ num_images_per_prompt: int = 1,
260
+ do_classifier_free_guidance: bool = True,
261
+ negative_prompt: Optional[str] = None,
262
+ negative_prompt_2: Optional[str] = None,
263
+ prompt_embeds: Optional[torch.FloatTensor] = None,
264
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
265
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
266
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
267
+ lora_scale: Optional[float] = None,
268
+ clip_skip: Optional[int] = None,
269
+ ):
270
+ r"""
271
+ Encodes the prompt into text encoder hidden states.
272
+ Args:
273
+ prompt (`str` or `List[str]`, *optional*):
274
+ prompt to be encoded
275
+ prompt_2 (`str` or `List[str]`, *optional*):
276
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
277
+ used in both text-encoders
278
+ device: (`torch.device`):
279
+ torch device
280
+ num_images_per_prompt (`int`):
281
+ number of images that should be generated per prompt
282
+ do_classifier_free_guidance (`bool`):
283
+ whether to use classifier free guidance or not
284
+ negative_prompt (`str` or `List[str]`, *optional*):
285
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
286
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
287
+ less than `1`).
288
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
289
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
290
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
291
+ prompt_embeds (`torch.FloatTensor`, *optional*):
292
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
293
+ provided, text embeddings will be generated from `prompt` input argument.
294
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
295
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
296
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
297
+ argument.
298
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
299
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
300
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
301
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
302
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
303
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
304
+ input argument.
305
+ lora_scale (`float`, *optional*):
306
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
307
+ clip_skip (`int`, *optional*):
308
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
309
+ the output of the pre-final layer will be used for computing the prompt embeddings.
310
+ """
311
+ device = device or self._execution_device
312
+
313
+ # set lora scale so that monkey patched LoRA
314
+ # function of text encoder can correctly access it
315
+ if lora_scale is not None and isinstance(self, StableDiffusionXLLoraLoaderMixin):
316
+ self._lora_scale = lora_scale
317
+
318
+ # dynamically adjust the LoRA scale
319
+ if self.text_encoder is not None:
320
+ if not USE_PEFT_BACKEND:
321
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
322
+ else:
323
+ scale_lora_layers(self.text_encoder, lora_scale)
324
+
325
+ if self.text_encoder_2 is not None:
326
+ if not USE_PEFT_BACKEND:
327
+ adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
328
+ else:
329
+ scale_lora_layers(self.text_encoder_2, lora_scale)
330
+
331
+ prompt = [prompt] if isinstance(prompt, str) else prompt
332
+
333
+ if prompt is not None:
334
+ batch_size = len(prompt)
335
+ else:
336
+ batch_size = prompt_embeds.shape[0]
337
+
338
+ # Define tokenizers and text encoders
339
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
340
+ text_encoders = (
341
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
342
+ )
343
+
344
+ if prompt_embeds is None:
345
+ prompt_2 = prompt_2 or prompt
346
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
347
+
348
+ # textual inversion: process multi-vector tokens if necessary
349
+ prompt_embeds_list = []
350
+ prompts = [prompt, prompt_2]
351
+ for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
352
+ if isinstance(self, TextualInversionLoaderMixin):
353
+ prompt = self.maybe_convert_prompt(prompt, tokenizer)
354
+
355
+ text_inputs = tokenizer(
356
+ prompt,
357
+ padding="max_length",
358
+ max_length=tokenizer.model_max_length,
359
+ truncation=True,
360
+ return_tensors="pt",
361
+ )
362
+
363
+ text_input_ids = text_inputs.input_ids
364
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
365
+
366
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
367
+ text_input_ids, untruncated_ids
368
+ ):
369
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
370
+ logger.warning(
371
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
372
+ f" {tokenizer.model_max_length} tokens: {removed_text}"
373
+ )
374
+
375
+ prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=True)
376
+
377
+ # We are only ALWAYS interested in the pooled output of the final text encoder
378
+ pooled_prompt_embeds = prompt_embeds[0]
379
+ if clip_skip is None:
380
+ prompt_embeds = prompt_embeds.hidden_states[-2]
381
+ else:
382
+ # "2" because SDXL always indexes from the penultimate layer.
383
+ prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
384
+
385
+ prompt_embeds_list.append(prompt_embeds)
386
+
387
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
388
+
389
+ # get unconditional embeddings for classifier free guidance
390
+ zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
391
+ if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
392
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
393
+ negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
394
+ elif do_classifier_free_guidance and negative_prompt_embeds is None:
395
+ negative_prompt = negative_prompt or ""
396
+ negative_prompt_2 = negative_prompt_2 or negative_prompt
397
+
398
+ # normalize str to list
399
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
400
+ negative_prompt_2 = (
401
+ batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
402
+ )
403
+
404
+ uncond_tokens: List[str]
405
+ if prompt is not None and type(prompt) is not type(negative_prompt):
406
+ raise TypeError(
407
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
408
+ f" {type(prompt)}."
409
+ )
410
+ elif batch_size != len(negative_prompt):
411
+ raise ValueError(
412
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
413
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
414
+ " the batch size of `prompt`."
415
+ )
416
+ else:
417
+ uncond_tokens = [negative_prompt, negative_prompt_2]
418
+
419
+ negative_prompt_embeds_list = []
420
+ for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
421
+ if isinstance(self, TextualInversionLoaderMixin):
422
+ negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
423
+
424
+ max_length = prompt_embeds.shape[1]
425
+ uncond_input = tokenizer(
426
+ negative_prompt,
427
+ padding="max_length",
428
+ max_length=max_length,
429
+ truncation=True,
430
+ return_tensors="pt",
431
+ )
432
+
433
+ negative_prompt_embeds = text_encoder(
434
+ uncond_input.input_ids.to(device),
435
+ output_hidden_states=True,
436
+ )
437
+ # We are only ALWAYS interested in the pooled output of the final text encoder
438
+ negative_pooled_prompt_embeds = negative_prompt_embeds[0]
439
+ negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
440
+
441
+ negative_prompt_embeds_list.append(negative_prompt_embeds)
442
+
443
+ negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
444
+
445
+ if self.text_encoder_2 is not None:
446
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
447
+ else:
448
+ prompt_embeds = prompt_embeds.to(dtype=self.unet.dtype, device=device)
449
+
450
+ bs_embed, seq_len, _ = prompt_embeds.shape
451
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
452
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
453
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
454
+
455
+ if do_classifier_free_guidance:
456
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
457
+ seq_len = negative_prompt_embeds.shape[1]
458
+
459
+ if self.text_encoder_2 is not None:
460
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
461
+ else:
462
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.unet.dtype, device=device)
463
+
464
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
465
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
466
+
467
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
468
+ bs_embed * num_images_per_prompt, -1
469
+ )
470
+ if do_classifier_free_guidance:
471
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
472
+ bs_embed * num_images_per_prompt, -1
473
+ )
474
+
475
+ if self.text_encoder is not None:
476
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
477
+ # Retrieve the original scale by scaling back the LoRA layers
478
+ unscale_lora_layers(self.text_encoder, lora_scale)
479
+
480
+ if self.text_encoder_2 is not None:
481
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
482
+ # Retrieve the original scale by scaling back the LoRA layers
483
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
484
+
485
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
486
+
487
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
488
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
489
+ dtype = next(self.image_encoder.parameters()).dtype
490
+
491
+ if not isinstance(image, torch.Tensor):
492
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
493
+
494
+ image = image.to(device=device, dtype=dtype)
495
+ if output_hidden_states:
496
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
497
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
498
+ uncond_image_enc_hidden_states = self.image_encoder(
499
+ torch.zeros_like(image), output_hidden_states=True
500
+ ).hidden_states[-2]
501
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
502
+ num_images_per_prompt, dim=0
503
+ )
504
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
505
+ else:
506
+ image_embeds = self.image_encoder(image).image_embeds
507
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
508
+ uncond_image_embeds = torch.zeros_like(image_embeds)
509
+
510
+ return image_embeds, uncond_image_embeds
511
+
512
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
513
+ def prepare_ip_adapter_image_embeds(
514
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
515
+ ):
516
+ if ip_adapter_image_embeds is None:
517
+ if not isinstance(ip_adapter_image, list):
518
+ ip_adapter_image = [ip_adapter_image]
519
+
520
+ if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
521
+ raise ValueError(
522
+ f"`ip_adapter_image` must have same length as the number of IP Adapters. Got {len(ip_adapter_image)} images and {len(self.unet.encoder_hid_proj.image_projection_layers)} IP Adapters."
523
+ )
524
+
525
+ image_embeds = []
526
+ for single_ip_adapter_image, image_proj_layer in zip(
527
+ ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
528
+ ):
529
+ output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
530
+ single_image_embeds, single_negative_image_embeds = self.encode_image(
531
+ single_ip_adapter_image, device, 1, output_hidden_state
532
+ )
533
+ single_image_embeds = torch.stack([single_image_embeds] * num_images_per_prompt, dim=0)
534
+ single_negative_image_embeds = torch.stack(
535
+ [single_negative_image_embeds] * num_images_per_prompt, dim=0
536
+ )
537
+
538
+ if do_classifier_free_guidance:
539
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds])
540
+ single_image_embeds = single_image_embeds.to(device)
541
+
542
+ image_embeds.append(single_image_embeds)
543
+ else:
544
+ repeat_dims = [1]
545
+ image_embeds = []
546
+ for single_image_embeds in ip_adapter_image_embeds:
547
+ if do_classifier_free_guidance:
548
+ single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
549
+ single_image_embeds = single_image_embeds.repeat(
550
+ num_images_per_prompt, *(repeat_dims * len(single_image_embeds.shape[1:]))
551
+ )
552
+ single_negative_image_embeds = single_negative_image_embeds.repeat(
553
+ num_images_per_prompt, *(repeat_dims * len(single_negative_image_embeds.shape[1:]))
554
+ )
555
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds])
556
+ else:
557
+ single_image_embeds = single_image_embeds.repeat(
558
+ num_images_per_prompt, *(repeat_dims * len(single_image_embeds.shape[1:]))
559
+ )
560
+ image_embeds.append(single_image_embeds)
561
+
562
+ return image_embeds
563
+
564
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
565
+ def prepare_extra_step_kwargs(self, generator, eta):
566
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
567
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
568
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
569
+ # and should be between [0, 1]
570
+
571
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
572
+ extra_step_kwargs = {}
573
+ if accepts_eta:
574
+ extra_step_kwargs["eta"] = eta
575
+
576
+ # check if the scheduler accepts generator
577
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
578
+ if accepts_generator:
579
+ extra_step_kwargs["generator"] = generator
580
+ return extra_step_kwargs
581
+
582
+ def check_inputs(
583
+ self,
584
+ prompt,
585
+ prompt_2,
586
+ height,
587
+ width,
588
+ callback_steps,
589
+ negative_prompt=None,
590
+ negative_prompt_2=None,
591
+ prompt_embeds=None,
592
+ negative_prompt_embeds=None,
593
+ pooled_prompt_embeds=None,
594
+ negative_pooled_prompt_embeds=None,
595
+ ip_adapter_image=None,
596
+ ip_adapter_image_embeds=None,
597
+ callback_on_step_end_tensor_inputs=None,
598
+ ):
599
+ if height % 8 != 0 or width % 8 != 0:
600
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
601
+
602
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
603
+ raise ValueError(
604
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
605
+ f" {type(callback_steps)}."
606
+ )
607
+
608
+ if callback_on_step_end_tensor_inputs is not None and not all(
609
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
610
+ ):
611
+ raise ValueError(
612
+ 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]}"
613
+ )
614
+
615
+ if prompt is not None and prompt_embeds is not None:
616
+ raise ValueError(
617
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
618
+ " only forward one of the two."
619
+ )
620
+ elif prompt_2 is not None and prompt_embeds is not None:
621
+ raise ValueError(
622
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
623
+ " only forward one of the two."
624
+ )
625
+ elif prompt is None and prompt_embeds is None:
626
+ raise ValueError(
627
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
628
+ )
629
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
630
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
631
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
632
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
633
+
634
+ if negative_prompt is not None and negative_prompt_embeds is not None:
635
+ raise ValueError(
636
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
637
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
638
+ )
639
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
640
+ raise ValueError(
641
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
642
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
643
+ )
644
+
645
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
646
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
647
+ raise ValueError(
648
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
649
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
650
+ f" {negative_prompt_embeds.shape}."
651
+ )
652
+
653
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
654
+ raise ValueError(
655
+ "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`."
656
+ )
657
+
658
+ if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
659
+ raise ValueError(
660
+ "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`."
661
+ )
662
+
663
+ if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
664
+ raise ValueError(
665
+ "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
666
+ )
667
+
668
+ if ip_adapter_image_embeds is not None:
669
+ if not isinstance(ip_adapter_image_embeds, list):
670
+ raise ValueError(
671
+ f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
672
+ )
673
+ elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
674
+ raise ValueError(
675
+ f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
676
+ )
677
+
678
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
679
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
680
+ shape = (
681
+ batch_size,
682
+ num_channels_latents,
683
+ int(height) // self.vae_scale_factor,
684
+ int(width) // self.vae_scale_factor,
685
+ )
686
+ if isinstance(generator, list) and len(generator) != batch_size:
687
+ raise ValueError(
688
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
689
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
690
+ )
691
+
692
+ if latents is None:
693
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
694
+ else:
695
+ latents = latents.to(device)
696
+
697
+ # scale the initial noise by the standard deviation required by the scheduler
698
+ latents = latents * self.scheduler.init_noise_sigma
699
+ return latents
700
+
701
+ def _get_add_time_ids(
702
+ self, original_size, crops_coords_top_left, target_size, dtype, text_encoder_projection_dim=None
703
+ ):
704
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
705
+
706
+ passed_add_embed_dim = (
707
+ self.unet.config.addition_time_embed_dim * len(add_time_ids) + text_encoder_projection_dim
708
+ )
709
+ expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
710
+
711
+ if expected_add_embed_dim != passed_add_embed_dim:
712
+ raise ValueError(
713
+ 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`."
714
+ )
715
+
716
+ add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
717
+ return add_time_ids
718
+
719
+ def upcast_vae(self):
720
+ dtype = self.vae.dtype
721
+ self.vae.to(dtype=torch.float32)
722
+ use_torch_2_0_or_xformers = isinstance(
723
+ self.vae.decoder.mid_block.attentions[0].processor,
724
+ (
725
+ AttnProcessor2_0,
726
+ XFormersAttnProcessor,
727
+ LoRAXFormersAttnProcessor,
728
+ LoRAAttnProcessor2_0,
729
+ FusedAttnProcessor2_0,
730
+ ),
731
+ )
732
+ # if xformers or torch_2_0 is used attention block does not need
733
+ # to be in float32 which can save lots of memory
734
+ if use_torch_2_0_or_xformers:
735
+ self.vae.post_quant_conv.to(dtype)
736
+ self.vae.decoder.conv_in.to(dtype)
737
+ self.vae.decoder.mid_block.to(dtype)
738
+
739
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
740
+ def get_guidance_scale_embedding(
741
+ self, w: torch.Tensor, embedding_dim: int = 512, dtype: torch.dtype = torch.float32
742
+ ) -> torch.FloatTensor:
743
+ """
744
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
745
+ Args:
746
+ w (`torch.Tensor`):
747
+ Generate embedding vectors with a specified guidance scale to subsequently enrich timestep embeddings.
748
+ embedding_dim (`int`, *optional*, defaults to 512):
749
+ Dimension of the embeddings to generate.
750
+ dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
751
+ Data type of the generated embeddings.
752
+ Returns:
753
+ `torch.FloatTensor`: Embedding vectors with shape `(len(w), embedding_dim)`.
754
+ """
755
+ assert len(w.shape) == 1
756
+ w = w * 1000.0
757
+
758
+ half_dim = embedding_dim // 2
759
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
760
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
761
+ emb = w.to(dtype)[:, None] * emb[None, :]
762
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
763
+ if embedding_dim % 2 == 1: # zero pad
764
+ emb = torch.nn.functional.pad(emb, (0, 1))
765
+ assert emb.shape == (w.shape[0], embedding_dim)
766
+ return emb
767
+
768
+ @property
769
+ def guidance_scale(self):
770
+ return self._guidance_scale
771
+
772
+ @property
773
+ def guidance_rescale(self):
774
+ return self._guidance_rescale
775
+
776
+ @property
777
+ def clip_skip(self):
778
+ return self._clip_skip
779
+
780
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
781
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
782
+ # corresponds to doing no classifier free guidance.
783
+ @property
784
+ def do_classifier_free_guidance(self):
785
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
786
+
787
+ @property
788
+ def cross_attention_kwargs(self):
789
+ return self._cross_attention_kwargs
790
+
791
+ @property
792
+ def denoising_end(self):
793
+ return self._denoising_end
794
+
795
+ @property
796
+ def num_timesteps(self):
797
+ return self._num_timesteps
798
+
799
+ @property
800
+ def interrupt(self):
801
+ return self._interrupt
802
+
803
+ @torch.no_grad()
804
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
805
+ def __call__(
806
+ self,
807
+ prompt: Union[str, List[str]] = None,
808
+ prompt_2: Optional[Union[str, List[str]]] = None,
809
+ height: Optional[int] = None,
810
+ width: Optional[int] = None,
811
+ num_inference_steps: int = 50,
812
+ timesteps: List[int] = None,
813
+ denoising_end: Optional[float] = None,
814
+ guidance_scale: float = 5.0,
815
+ negative_prompt: Optional[Union[str, List[str]]] = None,
816
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
817
+ num_images_per_prompt: Optional[int] = 1,
818
+ eta: float = 0.0,
819
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
820
+ latents: Optional[torch.FloatTensor] = None,
821
+ prompt_embeds: Optional[torch.FloatTensor] = None,
822
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
823
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
824
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
825
+ ip_adapter_image: Optional[PipelineImageInput] = None,
826
+ ip_adapter_image_embeds: Optional[List[torch.FloatTensor]] = None,
827
+ output_type: Optional[str] = "pil",
828
+ return_dict: bool = True,
829
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
830
+ guidance_rescale: float = 0.0,
831
+ original_size: Optional[Tuple[int, int]] = None,
832
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
833
+ target_size: Optional[Tuple[int, int]] = None,
834
+ negative_original_size: Optional[Tuple[int, int]] = None,
835
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
836
+ negative_target_size: Optional[Tuple[int, int]] = None,
837
+ clip_skip: Optional[int] = None,
838
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
839
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
840
+ **kwargs,
841
+ ):
842
+ r"""
843
+ Function invoked when calling the pipeline for generation.
844
+ Args:
845
+ prompt (`str` or `List[str]`, *optional*):
846
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
847
+ instead.
848
+ prompt_2 (`str` or `List[str]`, *optional*):
849
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
850
+ used in both text-encoders
851
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
852
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
853
+ Anything below 512 pixels won't work well for
854
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
855
+ and checkpoints that are not specifically fine-tuned on low resolutions.
856
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
857
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
858
+ Anything below 512 pixels won't work well for
859
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
860
+ and checkpoints that are not specifically fine-tuned on low resolutions.
861
+ num_inference_steps (`int`, *optional*, defaults to 50):
862
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
863
+ expense of slower inference.
864
+ timesteps (`List[int]`, *optional*):
865
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
866
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
867
+ passed will be used. Must be in descending order.
868
+ denoising_end (`float`, *optional*):
869
+ When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
870
+ completed before it is intentionally prematurely terminated. As a result, the returned sample will
871
+ still retain a substantial amount of noise as determined by the discrete timesteps selected by the
872
+ scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
873
+ "Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
874
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)
875
+ guidance_scale (`float`, *optional*, defaults to 5.0):
876
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
877
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
878
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
879
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
880
+ usually at the expense of lower image quality.
881
+ negative_prompt (`str` or `List[str]`, *optional*):
882
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
883
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
884
+ less than `1`).
885
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
886
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
887
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
888
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
889
+ The number of images to generate per prompt.
890
+ eta (`float`, *optional*, defaults to 0.0):
891
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
892
+ [`schedulers.DDIMScheduler`], will be ignored for others.
893
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
894
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
895
+ to make generation deterministic.
896
+ latents (`torch.FloatTensor`, *optional*):
897
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
898
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
899
+ tensor will ge generated by sampling using the supplied random `generator`.
900
+ prompt_embeds (`torch.FloatTensor`, *optional*):
901
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
902
+ provided, text embeddings will be generated from `prompt` input argument.
903
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
904
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
905
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
906
+ argument.
907
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
908
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
909
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
910
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
911
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
912
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
913
+ input argument.
914
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
915
+ ip_adapter_image_embeds (`List[torch.FloatTensor]`, *optional*):
916
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
917
+ IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should
918
+ contain the negative image embedding if `do_classifier_free_guidance` is set to `True`. If not
919
+ provided, embeddings are computed from the `ip_adapter_image` input argument.
920
+ output_type (`str`, *optional*, defaults to `"pil"`):
921
+ The output format of the generate image. Choose between
922
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
923
+ return_dict (`bool`, *optional*, defaults to `True`):
924
+ Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
925
+ of a plain tuple.
926
+ cross_attention_kwargs (`dict`, *optional*):
927
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
928
+ `self.processor` in
929
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
930
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
931
+ Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
932
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
933
+ [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
934
+ Guidance rescale factor should fix overexposure when using zero terminal SNR.
935
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
936
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
937
+ `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
938
+ explained in section 2.2 of
939
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
940
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
941
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
942
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
943
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
944
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
945
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
946
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
947
+ not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
948
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
949
+ negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
950
+ To negatively condition the generation process based on a specific image resolution. Part of SDXL's
951
+ micro-conditioning as explained in section 2.2 of
952
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
953
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
954
+ negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
955
+ To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
956
+ micro-conditioning as explained in section 2.2 of
957
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
958
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
959
+ negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
960
+ To negatively condition the generation process based on a target image resolution. It should be as same
961
+ as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
962
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
963
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
964
+ callback_on_step_end (`Callable`, *optional*):
965
+ A function that calls at the end of each denoising steps during the inference. The function is called
966
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
967
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
968
+ `callback_on_step_end_tensor_inputs`.
969
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
970
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
971
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
972
+ `._callback_tensor_inputs` attribute of your pipeline class.
973
+ Examples:
974
+ Returns:
975
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] or `tuple`:
976
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
977
+ `tuple`. When returning a tuple, the first element is a list with the generated images.
978
+ """
979
+
980
+ callback = kwargs.pop("callback", None)
981
+ callback_steps = kwargs.pop("callback_steps", None)
982
+
983
+ if callback is not None:
984
+ deprecate(
985
+ "callback",
986
+ "1.0.0",
987
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
988
+ )
989
+ if callback_steps is not None:
990
+ deprecate(
991
+ "callback_steps",
992
+ "1.0.0",
993
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
994
+ )
995
+
996
+ # 0. Default height and width to unet
997
+ height = height or self.default_sample_size * self.vae_scale_factor
998
+ width = width or self.default_sample_size * self.vae_scale_factor
999
+
1000
+ original_size = original_size or (height, width)
1001
+ target_size = target_size or (height, width)
1002
+
1003
+ # 1. Check inputs. Raise error if not correct
1004
+ self.check_inputs(
1005
+ prompt,
1006
+ prompt_2,
1007
+ height,
1008
+ width,
1009
+ callback_steps,
1010
+ negative_prompt,
1011
+ negative_prompt_2,
1012
+ prompt_embeds,
1013
+ negative_prompt_embeds,
1014
+ pooled_prompt_embeds,
1015
+ negative_pooled_prompt_embeds,
1016
+ ip_adapter_image,
1017
+ ip_adapter_image_embeds,
1018
+ callback_on_step_end_tensor_inputs,
1019
+ )
1020
+
1021
+ self._guidance_scale = guidance_scale
1022
+ self._guidance_rescale = guidance_rescale
1023
+ self._clip_skip = clip_skip
1024
+ self._cross_attention_kwargs = cross_attention_kwargs
1025
+ self._denoising_end = denoising_end
1026
+ self._interrupt = False
1027
+
1028
+ # 2. Define call parameters
1029
+ if prompt is not None and isinstance(prompt, str):
1030
+ batch_size = 1
1031
+ elif prompt is not None and isinstance(prompt, list):
1032
+ batch_size = len(prompt)
1033
+ else:
1034
+ batch_size = prompt_embeds.shape[0]
1035
+
1036
+ device = self._execution_device
1037
+
1038
+ # 3. Encode input prompt
1039
+ lora_scale = (
1040
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
1041
+ )
1042
+
1043
+ (
1044
+ prompt_embeds,
1045
+ negative_prompt_embeds,
1046
+ pooled_prompt_embeds,
1047
+ negative_pooled_prompt_embeds,
1048
+ ) = self.encode_prompt(
1049
+ prompt=prompt,
1050
+ prompt_2=prompt_2,
1051
+ device=device,
1052
+ num_images_per_prompt=num_images_per_prompt,
1053
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1054
+ negative_prompt=negative_prompt,
1055
+ negative_prompt_2=negative_prompt_2,
1056
+ prompt_embeds=prompt_embeds,
1057
+ negative_prompt_embeds=negative_prompt_embeds,
1058
+ pooled_prompt_embeds=pooled_prompt_embeds,
1059
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
1060
+ lora_scale=lora_scale,
1061
+ clip_skip=self.clip_skip,
1062
+ )
1063
+
1064
+ # 4. Prepare timesteps
1065
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
1066
+
1067
+ # 5. Prepare latent variables
1068
+ num_channels_latents = self.unet.config.in_channels
1069
+ latents = self.prepare_latents(
1070
+ batch_size * num_images_per_prompt,
1071
+ num_channels_latents,
1072
+ height,
1073
+ width,
1074
+ prompt_embeds.dtype,
1075
+ device,
1076
+ generator,
1077
+ latents,
1078
+ )
1079
+
1080
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1081
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1082
+
1083
+ # 7. Prepare added time ids & embeddings
1084
+ add_text_embeds = pooled_prompt_embeds
1085
+ if self.text_encoder_2 is None:
1086
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
1087
+ else:
1088
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
1089
+
1090
+ add_time_ids = self._get_add_time_ids(
1091
+ original_size,
1092
+ crops_coords_top_left,
1093
+ target_size,
1094
+ dtype=prompt_embeds.dtype,
1095
+ text_encoder_projection_dim=text_encoder_projection_dim,
1096
+ )
1097
+ if negative_original_size is not None and negative_target_size is not None:
1098
+ negative_add_time_ids = self._get_add_time_ids(
1099
+ negative_original_size,
1100
+ negative_crops_coords_top_left,
1101
+ negative_target_size,
1102
+ dtype=prompt_embeds.dtype,
1103
+ text_encoder_projection_dim=text_encoder_projection_dim,
1104
+ )
1105
+ else:
1106
+ negative_add_time_ids = add_time_ids
1107
+
1108
+ if self.do_classifier_free_guidance:
1109
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
1110
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
1111
+ add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
1112
+
1113
+ prompt_embeds = prompt_embeds.to(device)
1114
+ add_text_embeds = add_text_embeds.to(device)
1115
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
1116
+
1117
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1118
+ image_embeds = self.prepare_ip_adapter_image_embeds(
1119
+ ip_adapter_image,
1120
+ ip_adapter_image_embeds,
1121
+ device,
1122
+ batch_size * num_images_per_prompt,
1123
+ self.do_classifier_free_guidance,
1124
+ )
1125
+
1126
+ # 8. Denoising loop
1127
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
1128
+
1129
+ # 8.1 Apply denoising_end
1130
+ if (
1131
+ self.denoising_end is not None
1132
+ and isinstance(self.denoising_end, float)
1133
+ and self.denoising_end > 0
1134
+ and self.denoising_end < 1
1135
+ ):
1136
+ discrete_timestep_cutoff = int(
1137
+ round(
1138
+ self.scheduler.config.num_train_timesteps
1139
+ - (self.denoising_end * self.scheduler.config.num_train_timesteps)
1140
+ )
1141
+ )
1142
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
1143
+ timesteps = timesteps[:num_inference_steps]
1144
+
1145
+ # 9. Optionally get Guidance Scale Embedding
1146
+ timestep_cond = None
1147
+ if self.unet.config.time_cond_proj_dim is not None:
1148
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
1149
+ timestep_cond = self.get_guidance_scale_embedding(
1150
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
1151
+ ).to(device=device, dtype=latents.dtype)
1152
+
1153
+ self._num_timesteps = len(timesteps)
1154
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1155
+ for i, t in enumerate(timesteps):
1156
+ if self.interrupt:
1157
+ continue
1158
+
1159
+ # expand the latents if we are doing classifier free guidance
1160
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1161
+
1162
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1163
+
1164
+ # predict the noise residual
1165
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
1166
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1167
+ added_cond_kwargs["image_embeds"] = image_embeds
1168
+
1169
+ noise_pred = self.unet(
1170
+ latent_model_input,
1171
+ t,
1172
+ encoder_hidden_states=prompt_embeds, # [B, 77, 2048]
1173
+ timestep_cond=timestep_cond, # None
1174
+ cross_attention_kwargs=self.cross_attention_kwargs, # None
1175
+ added_cond_kwargs=added_cond_kwargs, # {[B, 1280], [B, 6]}
1176
+ return_dict=False,
1177
+ )[0]
1178
+
1179
+ # perform guidance
1180
+ if self.do_classifier_free_guidance:
1181
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1182
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
1183
+
1184
+ if self.do_classifier_free_guidance and self.guidance_rescale > 0.0:
1185
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1186
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale)
1187
+
1188
+ # compute the previous noisy sample x_t -> x_t-1
1189
+ latents_dtype = latents.dtype
1190
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1191
+ if latents.dtype != latents_dtype:
1192
+ if torch.backends.mps.is_available():
1193
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1194
+ latents = latents.to(latents_dtype)
1195
+
1196
+ if callback_on_step_end is not None:
1197
+ callback_kwargs = {}
1198
+ for k in callback_on_step_end_tensor_inputs:
1199
+ callback_kwargs[k] = locals()[k]
1200
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1201
+
1202
+ latents = callback_outputs.pop("latents", latents)
1203
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1204
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1205
+ add_text_embeds = callback_outputs.pop("add_text_embeds", add_text_embeds)
1206
+ negative_pooled_prompt_embeds = callback_outputs.pop(
1207
+ "negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
1208
+ )
1209
+ add_time_ids = callback_outputs.pop("add_time_ids", add_time_ids)
1210
+ negative_add_time_ids = callback_outputs.pop("negative_add_time_ids", negative_add_time_ids)
1211
+
1212
+ # call the callback, if provided
1213
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1214
+ progress_bar.update()
1215
+ if callback is not None and i % callback_steps == 0:
1216
+ step_idx = i // getattr(self.scheduler, "order", 1)
1217
+ callback(step_idx, t, latents)
1218
+
1219
+ if XLA_AVAILABLE:
1220
+ xm.mark_step()
1221
+
1222
+ if not output_type == "latent":
1223
+ # make sure the VAE is in float32 mode, as it overflows in float16
1224
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
1225
+
1226
+ if needs_upcasting:
1227
+ self.upcast_vae()
1228
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1229
+ elif latents.dtype != self.vae.dtype:
1230
+ if torch.backends.mps.is_available():
1231
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1232
+ self.vae = self.vae.to(latents.dtype)
1233
+
1234
+ # unscale/denormalize the latents
1235
+ # denormalize with the mean and std if available and not None
1236
+ has_latents_mean = hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None
1237
+ has_latents_std = hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None
1238
+ if has_latents_mean and has_latents_std:
1239
+ latents_mean = (
1240
+ torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1241
+ )
1242
+ latents_std = (
1243
+ torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1244
+ )
1245
+ latents = latents * latents_std / self.vae.config.scaling_factor + latents_mean
1246
+ else:
1247
+ latents = latents / self.vae.config.scaling_factor
1248
+
1249
+ image = self.vae.decode(latents, return_dict=False)[0]
1250
+
1251
+ # cast back to fp16 if needed
1252
+ if needs_upcasting:
1253
+ self.vae.to(dtype=torch.float16)
1254
+ else:
1255
+ image = latents
1256
+
1257
+ if not output_type == "latent":
1258
+ # apply watermark if available
1259
+ if self.watermark is not None:
1260
+ image = self.watermark.apply_watermark(image)
1261
+
1262
+ image = self.image_processor.postprocess(image, output_type=output_type)
1263
+
1264
+ # Offload all models
1265
+ self.maybe_free_model_hooks()
1266
+
1267
+ if not return_dict:
1268
+ return (image,)
1269
+
1270
+ return StableDiffusionXLPipelineOutput(images=image)