SunderAli17 commited on
Commit
ba90d89
1 Parent(s): 85dc639

Create pipeline_stable_diffusion_xl_chatglm_256_ipadapter.py

Browse files
SAK/pipelines/pipeline_stable_diffusion_xl_chatglm_256_ipadapter.py ADDED
@@ -0,0 +1,932 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import sys
15
+ import os
16
+ sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
17
+ from kolors.models.modeling_chatglm import ChatGLMModel
18
+ from kolors.models.tokenization_chatglm import ChatGLMTokenizer
19
+ import inspect
20
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
21
+ import torch
22
+ from transformers import (
23
+ CLIPImageProcessor,
24
+ CLIPTextModel,
25
+ CLIPTextModelWithProjection,
26
+ CLIPTokenizer,
27
+ CLIPVisionModelWithProjection,
28
+ )
29
+ from transformers import XLMRobertaModel, ChineseCLIPTextModel
30
+
31
+ from diffusers.image_processor import VaeImageProcessor,PipelineImageInput
32
+ from diffusers.loaders import (
33
+ FromSingleFileMixin,
34
+ IPAdapterMixin,
35
+ LoraLoaderMixin,
36
+ TextualInversionLoaderMixin
37
+ )
38
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel,ImageProjection
39
+ from diffusers.models.attention_processor import (
40
+ AttnProcessor2_0,
41
+ LoRAAttnProcessor2_0,
42
+ LoRAXFormersAttnProcessor,
43
+ XFormersAttnProcessor,
44
+ )
45
+ from diffusers.schedulers import KarrasDiffusionSchedulers
46
+ from diffusers.utils import (
47
+ is_accelerate_available,
48
+ is_accelerate_version,
49
+ logging,
50
+ replace_example_docstring,
51
+ )
52
+ try:
53
+ from diffusers.utils import randn_tensor
54
+ except:
55
+ from diffusers.utils.torch_utils import randn_tensor
56
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
57
+ from diffusers.pipelines.stable_diffusion_xl import StableDiffusionXLPipelineOutput
58
+
59
+
60
+
61
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
62
+
63
+ EXAMPLE_DOC_STRING = """
64
+ Examples:
65
+ ```py
66
+ >>> import torch
67
+ >>> from diffusers import StableDiffusionXLPipeline
68
+ >>> pipe = StableDiffusionXLPipeline.from_pretrained(
69
+ ... "stabilityai/stable-diffusion-xl-base-0.9", torch_dtype=torch.float16
70
+ ... )
71
+ >>> pipe = pipe.to("cuda")
72
+ >>> prompt = "a photo of an astronaut riding a horse on mars"
73
+ >>> image = pipe(prompt).images[0]
74
+ ```
75
+ """
76
+
77
+
78
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
79
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
80
+ """
81
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
82
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
83
+ """
84
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
85
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
86
+ # rescale the results from guidance (fixes overexposure)
87
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
88
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
89
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
90
+ return noise_cfg
91
+
92
+
93
+ class StableDiffusionXLPipeline(DiffusionPipeline, FromSingleFileMixin, LoraLoaderMixin, IPAdapterMixin,):
94
+ r"""
95
+ Pipeline for text-to-image generation using Stable Diffusion XL.
96
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
97
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
98
+ In addition the pipeline inherits the following loading methods:
99
+ - *Textual-Inversion*: [`loaders.TextualInversionLoaderMixin.load_textual_inversion`]
100
+ - *LoRA*: [`loaders.LoraLoaderMixin.load_lora_weights`]
101
+ - *Ckpt*: [`loaders.FromSingleFileMixin.from_single_file`]
102
+ as well as the following saving methods:
103
+ - *LoRA*: [`loaders.LoraLoaderMixin.save_lora_weights`]
104
+ Args:
105
+ vae ([`AutoencoderKL`]):
106
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
107
+ text_encoder ([`CLIPTextModel`]):
108
+ Frozen text-encoder. Stable Diffusion XL uses the text portion of
109
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
110
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
111
+ tokenizer (`CLIPTokenizer`):
112
+ Tokenizer of class
113
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
114
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
115
+ scheduler ([`SchedulerMixin`]):
116
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
117
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
118
+ """
119
+
120
+ def __init__(
121
+ self,
122
+ vae: AutoencoderKL,
123
+ text_encoder: ChatGLMModel,
124
+ tokenizer: ChatGLMTokenizer,
125
+ unet: UNet2DConditionModel,
126
+ scheduler: KarrasDiffusionSchedulers,
127
+ image_encoder: CLIPVisionModelWithProjection = None,
128
+ feature_extractor: CLIPImageProcessor = None,
129
+ force_zeros_for_empty_prompt: bool = True,
130
+ ):
131
+ super().__init__()
132
+
133
+ self.register_modules(
134
+ vae=vae,
135
+ text_encoder=text_encoder,
136
+ tokenizer=tokenizer,
137
+ unet=unet,
138
+ scheduler=scheduler,
139
+ image_encoder=image_encoder,
140
+ feature_extractor=feature_extractor,
141
+ )
142
+ self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
143
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
144
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
145
+ self.default_sample_size = self.unet.config.sample_size
146
+
147
+ # self.watermark = StableDiffusionXLWatermarker()
148
+
149
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_slicing
150
+ def enable_vae_slicing(self):
151
+ r"""
152
+ Enable sliced VAE decoding.
153
+ When this option is enabled, the VAE will split the input tensor in slices to compute decoding in several
154
+ steps. This is useful to save some memory and allow larger batch sizes.
155
+ """
156
+ self.vae.enable_slicing()
157
+
158
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_slicing
159
+ def disable_vae_slicing(self):
160
+ r"""
161
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously invoked, this method will go back to
162
+ computing decoding in one step.
163
+ """
164
+ self.vae.disable_slicing()
165
+
166
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_tiling
167
+ def enable_vae_tiling(self):
168
+ r"""
169
+ Enable tiled VAE decoding.
170
+ When this option is enabled, the VAE will split the input tensor into tiles to compute decoding and encoding in
171
+ several steps. This is useful to save a large amount of memory and to allow the processing of larger images.
172
+ """
173
+ self.vae.enable_tiling()
174
+
175
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_tiling
176
+ def disable_vae_tiling(self):
177
+ r"""
178
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously invoked, this method will go back to
179
+ computing decoding in one step.
180
+ """
181
+ self.vae.disable_tiling()
182
+
183
+ def enable_sequential_cpu_offload(self, gpu_id=0):
184
+ r"""
185
+ Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet,
186
+ text_encoder, vae and safety checker have their state dicts saved to CPU and then are moved to a
187
+ `torch.device('meta') and loaded to GPU only when their specific submodule has its `forward` method called.
188
+ Note that offloading happens on a submodule basis. Memory savings are higher than with
189
+ `enable_model_cpu_offload`, but performance is lower.
190
+ """
191
+ if is_accelerate_available() and is_accelerate_version(">=", "0.14.0"):
192
+ from accelerate import cpu_offload
193
+ else:
194
+ raise ImportError("`enable_sequential_cpu_offload` requires `accelerate v0.14.0` or higher")
195
+
196
+ device = torch.device(f"cuda:{gpu_id}")
197
+
198
+ if self.device.type != "cpu":
199
+ self.to("cpu", silence_dtype_warnings=True)
200
+ torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
201
+
202
+ for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae]:
203
+ cpu_offload(cpu_offloaded_model, device)
204
+
205
+ def enable_model_cpu_offload(self, gpu_id=0):
206
+ r"""
207
+ Offloads all models to CPU using accelerate, reducing memory usage with a low impact on performance. Compared
208
+ to `enable_sequential_cpu_offload`, this method moves one whole model at a time to the GPU when its `forward`
209
+ method is called, and the model remains in GPU until the next model runs. Memory savings are lower than with
210
+ `enable_sequential_cpu_offload`, but performance is much better due to the iterative execution of the `unet`.
211
+ """
212
+ if is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"):
213
+ from accelerate import cpu_offload_with_hook
214
+ else:
215
+ raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.")
216
+
217
+ device = torch.device(f"cuda:{gpu_id}")
218
+
219
+ if self.device.type != "cpu":
220
+ self.to("cpu", silence_dtype_warnings=True)
221
+ torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
222
+
223
+ model_sequence = (
224
+ [self.text_encoder, self.image_encoder]
225
+ )
226
+ model_sequence.extend([self.unet, self.vae])
227
+
228
+ hook = None
229
+ for cpu_offloaded_model in model_sequence:
230
+ _, hook = cpu_offload_with_hook(cpu_offloaded_model, device, prev_module_hook=hook)
231
+
232
+ # We'll offload the last model manually.
233
+ self.final_offload_hook = hook
234
+
235
+ @property
236
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
237
+ def _execution_device(self):
238
+ r"""
239
+ Returns the device on which the pipeline's models will be executed. After calling
240
+ `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
241
+ hooks.
242
+ """
243
+ if not hasattr(self.unet, "_hf_hook"):
244
+ return self.device
245
+ for module in self.unet.modules():
246
+ if (
247
+ hasattr(module, "_hf_hook")
248
+ and hasattr(module._hf_hook, "execution_device")
249
+ and module._hf_hook.execution_device is not None
250
+ ):
251
+ return torch.device(module._hf_hook.execution_device)
252
+ return self.device
253
+
254
+ def encode_prompt(
255
+ self,
256
+ prompt,
257
+ device: Optional[torch.device] = None,
258
+ num_images_per_prompt: int = 1,
259
+ do_classifier_free_guidance: bool = True,
260
+ negative_prompt=None,
261
+ prompt_embeds: Optional[torch.FloatTensor] = None,
262
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
263
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
264
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
265
+ lora_scale: Optional[float] = None,
266
+ ):
267
+ r"""
268
+ Encodes the prompt into text encoder hidden states.
269
+ Args:
270
+ prompt (`str` or `List[str]`, *optional*):
271
+ prompt to be encoded
272
+ device: (`torch.device`):
273
+ torch device
274
+ num_images_per_prompt (`int`):
275
+ number of images that should be generated per prompt
276
+ do_classifier_free_guidance (`bool`):
277
+ whether to use classifier free guidance or not
278
+ negative_prompt (`str` or `List[str]`, *optional*):
279
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
280
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
281
+ less than `1`).
282
+ prompt_embeds (`torch.FloatTensor`, *optional*):
283
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
284
+ provided, text embeddings will be generated from `prompt` input argument.
285
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
286
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
287
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
288
+ argument.
289
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
290
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
291
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
292
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
293
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
294
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
295
+ input argument.
296
+ lora_scale (`float`, *optional*):
297
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
298
+ """
299
+ # from IPython import embed; embed(); exit()
300
+ device = device or self._execution_device
301
+
302
+ # set lora scale so that monkey patched LoRA
303
+ # function of text encoder can correctly access it
304
+ if lora_scale is not None and isinstance(self, LoraLoaderMixin):
305
+ self._lora_scale = lora_scale
306
+
307
+ if prompt is not None and isinstance(prompt, str):
308
+ batch_size = 1
309
+ elif prompt is not None and isinstance(prompt, list):
310
+ batch_size = len(prompt)
311
+ else:
312
+ batch_size = prompt_embeds.shape[0]
313
+
314
+ # Define tokenizers and text encoders
315
+ tokenizers = [self.tokenizer]
316
+ text_encoders = [self.text_encoder]
317
+
318
+ if prompt_embeds is None:
319
+ # textual inversion: procecss multi-vector tokens if necessary
320
+ prompt_embeds_list = []
321
+ for tokenizer, text_encoder in zip(tokenizers, text_encoders):
322
+ if isinstance(self, TextualInversionLoaderMixin):
323
+ prompt = self.maybe_convert_prompt(prompt, tokenizer)
324
+
325
+ text_inputs = tokenizer(
326
+ prompt,
327
+ padding="max_length",
328
+ max_length=256,
329
+ truncation=True,
330
+ return_tensors="pt",
331
+ ).to('cuda')
332
+ output = text_encoder(
333
+ input_ids=text_inputs['input_ids'] ,
334
+ attention_mask=text_inputs['attention_mask'],
335
+ position_ids=text_inputs['position_ids'],
336
+ output_hidden_states=True)
337
+ prompt_embeds = output.hidden_states[-2].permute(1, 0, 2).clone()
338
+ pooled_prompt_embeds = output.hidden_states[-1][-1, :, :].clone() # [batch_size, 4096]
339
+ bs_embed, seq_len, _ = prompt_embeds.shape
340
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
341
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
342
+
343
+ prompt_embeds_list.append(prompt_embeds)
344
+
345
+ # prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
346
+ prompt_embeds = prompt_embeds_list[0]
347
+
348
+ # get unconditional embeddings for classifier free guidance
349
+ zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
350
+ if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
351
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
352
+ negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
353
+ elif do_classifier_free_guidance and negative_prompt_embeds is None:
354
+ # negative_prompt = negative_prompt or ""
355
+ uncond_tokens: List[str]
356
+ if negative_prompt is None:
357
+ uncond_tokens = [""] * batch_size
358
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
359
+ raise TypeError(
360
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
361
+ f" {type(prompt)}."
362
+ )
363
+ elif isinstance(negative_prompt, str):
364
+ uncond_tokens = [negative_prompt]
365
+ elif batch_size != len(negative_prompt):
366
+ raise ValueError(
367
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
368
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
369
+ " the batch size of `prompt`."
370
+ )
371
+ else:
372
+ uncond_tokens = negative_prompt
373
+
374
+ negative_prompt_embeds_list = []
375
+ for tokenizer, text_encoder in zip(tokenizers, text_encoders):
376
+ # textual inversion: procecss multi-vector tokens if necessary
377
+ if isinstance(self, TextualInversionLoaderMixin):
378
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, tokenizer)
379
+
380
+ max_length = prompt_embeds.shape[1]
381
+ uncond_input = tokenizer(
382
+ uncond_tokens,
383
+ padding="max_length",
384
+ max_length=max_length,
385
+ truncation=True,
386
+ return_tensors="pt",
387
+ ).to('cuda')
388
+ output = text_encoder(
389
+ input_ids=uncond_input['input_ids'] ,
390
+ attention_mask=uncond_input['attention_mask'],
391
+ position_ids=uncond_input['position_ids'],
392
+ output_hidden_states=True)
393
+ negative_prompt_embeds = output.hidden_states[-2].permute(1, 0, 2).clone()
394
+ negative_pooled_prompt_embeds = output.hidden_states[-1][-1, :, :].clone() # [batch_size, 4096]
395
+
396
+ if do_classifier_free_guidance:
397
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
398
+ seq_len = negative_prompt_embeds.shape[1]
399
+
400
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=text_encoder.dtype, device=device)
401
+
402
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
403
+ negative_prompt_embeds = negative_prompt_embeds.view(
404
+ batch_size * num_images_per_prompt, seq_len, -1
405
+ )
406
+
407
+ # For classifier free guidance, we need to do two forward passes.
408
+ # Here we concatenate the unconditional and text embeddings into a single batch
409
+ # to avoid doing two forward passes
410
+
411
+ negative_prompt_embeds_list.append(negative_prompt_embeds)
412
+
413
+ # negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
414
+ negative_prompt_embeds = negative_prompt_embeds_list[0]
415
+
416
+ bs_embed = pooled_prompt_embeds.shape[0]
417
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
418
+ bs_embed * num_images_per_prompt, -1
419
+ )
420
+ if do_classifier_free_guidance:
421
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
422
+ bs_embed * num_images_per_prompt, -1
423
+ )
424
+
425
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
426
+
427
+
428
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
429
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
430
+ dtype = next(self.image_encoder.parameters()).dtype
431
+
432
+ if not isinstance(image, torch.Tensor):
433
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
434
+
435
+ image = image.to(device=device, dtype=dtype)
436
+ if output_hidden_states:
437
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
438
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
439
+ uncond_image_enc_hidden_states = self.image_encoder(
440
+ torch.zeros_like(image), output_hidden_states=True
441
+ ).hidden_states[-2]
442
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
443
+ num_images_per_prompt, dim=0
444
+ )
445
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
446
+ else:
447
+ image_embeds = self.image_encoder(image).image_embeds
448
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
449
+ uncond_image_embeds = torch.zeros_like(image_embeds)
450
+
451
+ return image_embeds, uncond_image_embeds
452
+
453
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
454
+ def prepare_ip_adapter_image_embeds(
455
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
456
+ ):
457
+ image_embeds = []
458
+ if do_classifier_free_guidance:
459
+ negative_image_embeds = []
460
+ if ip_adapter_image_embeds is None:
461
+ if not isinstance(ip_adapter_image, list):
462
+ ip_adapter_image = [ip_adapter_image]
463
+
464
+ if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
465
+ raise ValueError(
466
+ 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."
467
+ )
468
+
469
+ for single_ip_adapter_image, image_proj_layer in zip(
470
+ ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
471
+ ):
472
+ output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
473
+ single_image_embeds, single_negative_image_embeds = self.encode_image(
474
+ single_ip_adapter_image, device, 1, output_hidden_state
475
+ )
476
+
477
+ image_embeds.append(single_image_embeds[None, :])
478
+ if do_classifier_free_guidance:
479
+ negative_image_embeds.append(single_negative_image_embeds[None, :])
480
+ else:
481
+ for single_image_embeds in ip_adapter_image_embeds:
482
+ if do_classifier_free_guidance:
483
+ single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
484
+ negative_image_embeds.append(single_negative_image_embeds)
485
+ image_embeds.append(single_image_embeds)
486
+
487
+ ip_adapter_image_embeds = []
488
+ for i, single_image_embeds in enumerate(image_embeds):
489
+ single_image_embeds = torch.cat([single_image_embeds] * num_images_per_prompt, dim=0)
490
+ if do_classifier_free_guidance:
491
+ single_negative_image_embeds = torch.cat([negative_image_embeds[i]] * num_images_per_prompt, dim=0)
492
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds], dim=0)
493
+
494
+ single_image_embeds = single_image_embeds.to(device=device)
495
+ ip_adapter_image_embeds.append(single_image_embeds)
496
+
497
+ return ip_adapter_image_embeds
498
+
499
+
500
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
501
+ def prepare_extra_step_kwargs(self, generator, eta):
502
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
503
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
504
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
505
+ # and should be between [0, 1]
506
+
507
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
508
+ extra_step_kwargs = {}
509
+ if accepts_eta:
510
+ extra_step_kwargs["eta"] = eta
511
+
512
+ # check if the scheduler accepts generator
513
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
514
+ if accepts_generator:
515
+ extra_step_kwargs["generator"] = generator
516
+ return extra_step_kwargs
517
+
518
+ def check_inputs(
519
+ self,
520
+ prompt,
521
+ height,
522
+ width,
523
+ callback_steps,
524
+ negative_prompt=None,
525
+ prompt_embeds=None,
526
+ negative_prompt_embeds=None,
527
+ pooled_prompt_embeds=None,
528
+ negative_pooled_prompt_embeds=None,
529
+ ):
530
+ if height % 8 != 0 or width % 8 != 0:
531
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
532
+
533
+ if (callback_steps is None) or (
534
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
535
+ ):
536
+ raise ValueError(
537
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
538
+ f" {type(callback_steps)}."
539
+ )
540
+
541
+ if prompt is not None and prompt_embeds is not None:
542
+ raise ValueError(
543
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
544
+ " only forward one of the two."
545
+ )
546
+ elif prompt is None and prompt_embeds is None:
547
+ raise ValueError(
548
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
549
+ )
550
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
551
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
552
+
553
+ if negative_prompt is not None and negative_prompt_embeds is not None:
554
+ raise ValueError(
555
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
556
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
557
+ )
558
+
559
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
560
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
561
+ raise ValueError(
562
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
563
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
564
+ f" {negative_prompt_embeds.shape}."
565
+ )
566
+
567
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
568
+ raise ValueError(
569
+ "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`."
570
+ )
571
+
572
+ if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
573
+ raise ValueError(
574
+ "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`."
575
+ )
576
+
577
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
578
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
579
+ shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
580
+ if isinstance(generator, list) and len(generator) != batch_size:
581
+ raise ValueError(
582
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
583
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
584
+ )
585
+
586
+ if latents is None:
587
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
588
+ else:
589
+ latents = latents.to(device)
590
+
591
+ # scale the initial noise by the standard deviation required by the scheduler
592
+ latents = latents * self.scheduler.init_noise_sigma
593
+ return latents
594
+
595
+ def _get_add_time_ids(self, original_size, crops_coords_top_left, target_size, dtype):
596
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
597
+
598
+ passed_add_embed_dim = (
599
+ self.unet.config.addition_time_embed_dim * len(add_time_ids) + 4096
600
+ )
601
+ expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
602
+
603
+ if expected_add_embed_dim != passed_add_embed_dim:
604
+ raise ValueError(
605
+ 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`."
606
+ )
607
+
608
+ add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
609
+ return add_time_ids
610
+
611
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.StableDiffusionUpscalePipeline.upcast_vae
612
+ def upcast_vae(self):
613
+ dtype = self.vae.dtype
614
+ self.vae.to(dtype=torch.float32)
615
+ use_torch_2_0_or_xformers = isinstance(
616
+ self.vae.decoder.mid_block.attentions[0].processor,
617
+ (
618
+ AttnProcessor2_0,
619
+ XFormersAttnProcessor,
620
+ LoRAXFormersAttnProcessor,
621
+ LoRAAttnProcessor2_0,
622
+ ),
623
+ )
624
+ # if xformers or torch_2_0 is used attention block does not need
625
+ # to be in float32 which can save lots of memory
626
+ if use_torch_2_0_or_xformers:
627
+ self.vae.post_quant_conv.to(dtype)
628
+ self.vae.decoder.conv_in.to(dtype)
629
+ self.vae.decoder.mid_block.to(dtype)
630
+
631
+ @torch.no_grad()
632
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
633
+ def __call__(
634
+ self,
635
+ prompt: Union[str, List[str]] = None,
636
+ height: Optional[int] = None,
637
+ width: Optional[int] = None,
638
+ num_inference_steps: int = 50,
639
+ denoising_end: Optional[float] = None,
640
+ guidance_scale: float = 5.0,
641
+ negative_prompt: Optional[Union[str, List[str]]] = None,
642
+ num_images_per_prompt: Optional[int] = 1,
643
+ eta: float = 0.0,
644
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
645
+ latents: Optional[torch.FloatTensor] = None,
646
+ prompt_embeds: Optional[torch.FloatTensor] = None,
647
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
648
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
649
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
650
+ ip_adapter_image: Optional[PipelineImageInput] = None,
651
+ ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
652
+ output_type: Optional[str] = "pil",
653
+ return_dict: bool = True,
654
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
655
+ callback_steps: int = 1,
656
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
657
+ guidance_rescale: float = 0.0,
658
+ original_size: Optional[Tuple[int, int]] = None,
659
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
660
+ target_size: Optional[Tuple[int, int]] = None,
661
+ use_dynamic_threshold: Optional[bool] = False,
662
+ ):
663
+ r"""
664
+ Function invoked when calling the pipeline for generation.
665
+ Args:
666
+ prompt (`str` or `List[str]`, *optional*):
667
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
668
+ instead.
669
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
670
+ The height in pixels of the generated image.
671
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
672
+ The width in pixels of the generated image.
673
+ num_inference_steps (`int`, *optional*, defaults to 50):
674
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
675
+ expense of slower inference.
676
+ denoising_end (`float`, *optional*):
677
+ When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
678
+ completed before it is intentionally prematurely terminated. For instance, if denoising_end is set to
679
+ 0.7 and `num_inference_steps` is fixed at 50, the process will execute only 35 (i.e., 0.7 * 50)
680
+ Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
681
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)
682
+ guidance_scale (`float`, *optional*, defaults to 7.5):
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
+ negative_prompt (`str` or `List[str]`, *optional*):
687
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
688
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
689
+ less than `1`).
690
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
691
+ The number of images to generate per prompt.
692
+ eta (`float`, *optional*, defaults to 0.0):
693
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
694
+ [`schedulers.DDIMScheduler`], will be ignored for others.
695
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
696
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
697
+ to make generation deterministic.
698
+ latents (`torch.FloatTensor`, *optional*):
699
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
700
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
701
+ tensor will ge generated by sampling using the supplied random `generator`.
702
+ prompt_embeds (`torch.FloatTensor`, *optional*):
703
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
704
+ provided, text embeddings will be generated from `prompt` input argument.
705
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
706
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
707
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
708
+ argument.
709
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
710
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
711
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
712
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
713
+ output_type (`str`, *optional*, defaults to `"pil"`):
714
+ The output format of the generate image. Choose between
715
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
716
+ return_dict (`bool`, *optional*, defaults to `True`):
717
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] instead of a
718
+ callback (`Callable`, *optional*):
719
+ A function that will be called every `callback_steps` steps during inference. The function will be
720
+ callback_steps (`int`, *optional*, defaults to 1):
721
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
722
+ called at every step.
723
+ cross_attention_kwargs (`dict`, *optional*):
724
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
725
+ `self.processor` in
726
+ [diffusers.cross_attention](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/cross_attention.py).
727
+ guidance_rescale (`float`, *optional*, defaults to 0.7):
728
+ Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
729
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
730
+ [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
731
+ Guidance rescale factor should fix overexposure when using zero terminal SNR.
732
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
733
+ TODO
734
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
735
+ TODO
736
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
737
+ TODO
738
+ Examples:
739
+ Returns:
740
+ [`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] or `tuple`:
741
+ [`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
742
+ `tuple. When returning a tuple, the first element is a list with the generated images, and the second
743
+ element is a list of `bool`s denoting whether the corresponding generated image likely represents
744
+ "not-safe-for-work" (nsfw) content, according to the `safety_checker`.
745
+ """
746
+ # 0. Default height and width to unet
747
+ height = height or self.default_sample_size * self.vae_scale_factor
748
+ width = width or self.default_sample_size * self.vae_scale_factor
749
+
750
+ original_size = original_size or (height, width)
751
+ target_size = target_size or (height, width)
752
+
753
+ # 1. Check inputs. Raise error if not correct
754
+ self.check_inputs(
755
+ prompt,
756
+ height,
757
+ width,
758
+ callback_steps,
759
+ negative_prompt,
760
+ prompt_embeds,
761
+ negative_prompt_embeds,
762
+ pooled_prompt_embeds,
763
+ negative_pooled_prompt_embeds,
764
+ )
765
+
766
+ # 2. Define call parameters
767
+ if prompt is not None and isinstance(prompt, str):
768
+ batch_size = 1
769
+ elif prompt is not None and isinstance(prompt, list):
770
+ batch_size = len(prompt)
771
+ else:
772
+ batch_size = prompt_embeds.shape[0]
773
+
774
+ device = self._execution_device
775
+
776
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
777
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
778
+ # corresponds to doing no classifier free guidance.
779
+ do_classifier_free_guidance = guidance_scale > 1.0
780
+
781
+ # 3. Encode input prompt
782
+ text_encoder_lora_scale = (
783
+ cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
784
+ )
785
+ (
786
+ prompt_embeds,
787
+ negative_prompt_embeds,
788
+ pooled_prompt_embeds,
789
+ negative_pooled_prompt_embeds,
790
+ ) = self.encode_prompt(
791
+ prompt,
792
+ device,
793
+ num_images_per_prompt,
794
+ do_classifier_free_guidance,
795
+ negative_prompt,
796
+ prompt_embeds=prompt_embeds,
797
+ negative_prompt_embeds=negative_prompt_embeds,
798
+ pooled_prompt_embeds=pooled_prompt_embeds,
799
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
800
+ lora_scale=text_encoder_lora_scale,
801
+ )
802
+
803
+ # 4. Prepare timesteps
804
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
805
+
806
+ timesteps = self.scheduler.timesteps
807
+
808
+ # 5. Prepare latent variables
809
+ num_channels_latents = self.unet.config.in_channels
810
+ latents = self.prepare_latents(
811
+ batch_size * num_images_per_prompt,
812
+ num_channels_latents,
813
+ height,
814
+ width,
815
+ prompt_embeds.dtype,
816
+ device,
817
+ generator,
818
+ latents,
819
+ )
820
+
821
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
822
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
823
+
824
+ # 7. Prepare added time ids & embeddings
825
+ add_text_embeds = pooled_prompt_embeds
826
+ add_time_ids = self._get_add_time_ids(
827
+ original_size, crops_coords_top_left, target_size, dtype=prompt_embeds.dtype
828
+ )
829
+
830
+ if do_classifier_free_guidance:
831
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
832
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
833
+ add_time_ids = torch.cat([add_time_ids, add_time_ids], dim=0)
834
+
835
+ prompt_embeds = prompt_embeds.to(device)
836
+ add_text_embeds = add_text_embeds.to(device)
837
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
838
+
839
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
840
+ image_embeds = self.prepare_ip_adapter_image_embeds(
841
+ ip_adapter_image,
842
+ ip_adapter_image_embeds,
843
+ device,
844
+ batch_size * num_images_per_prompt,
845
+ do_classifier_free_guidance,
846
+ )
847
+
848
+ # 8. Denoising loop
849
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
850
+
851
+ # 7.1 Apply denoising_end
852
+ if denoising_end is not None:
853
+ num_inference_steps = int(round(denoising_end * num_inference_steps))
854
+ timesteps = timesteps[: num_warmup_steps + self.scheduler.order * num_inference_steps]
855
+
856
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
857
+ for i, t in enumerate(timesteps):
858
+ # expand the latents if we are doing classifier free guidance
859
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
860
+
861
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
862
+
863
+ # predict the noise residual
864
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
865
+
866
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
867
+ added_cond_kwargs["image_embeds"] = image_embeds
868
+
869
+ # import pdb; pdb.set_trace()
870
+
871
+ noise_pred = self.unet(
872
+ latent_model_input,
873
+ t,
874
+ encoder_hidden_states=prompt_embeds,
875
+ cross_attention_kwargs=cross_attention_kwargs,
876
+ added_cond_kwargs=added_cond_kwargs,
877
+ return_dict=False,
878
+ )[0]
879
+
880
+ # perform guidance
881
+ if do_classifier_free_guidance:
882
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
883
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
884
+ if use_dynamic_threshold:
885
+ DynamicThresh = DynThresh(maxSteps=num_inference_steps, experiment_mode=0)
886
+ noise_pred = DynamicThresh.dynthresh(noise_pred_text,
887
+ noise_pred_uncond,
888
+ guidance_scale,
889
+ None)
890
+
891
+ if do_classifier_free_guidance and guidance_rescale > 0.0:
892
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
893
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
894
+
895
+ # compute the previous noisy sample x_t -> x_t-1
896
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
897
+
898
+ # call the callback, if provided
899
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
900
+ progress_bar.update()
901
+ if callback is not None and i % callback_steps == 0:
902
+ callback(i, t, latents)
903
+
904
+ # make sureo the VAE is in float32 mode, as it overflows in float16
905
+ # torch.cuda.empty_cache()
906
+ if self.vae.dtype == torch.float16 and self.vae.config.force_upcast:
907
+ self.upcast_vae()
908
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
909
+
910
+
911
+ if not output_type == "latent":
912
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
913
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
914
+ else:
915
+ image = latents
916
+ return StableDiffusionXLPipelineOutput(images=image)
917
+
918
+ # image = self.watermark.apply_watermark(image)
919
+ image = self.image_processor.postprocess(image, output_type=output_type)
920
+
921
+ # Offload last model to CPU
922
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
923
+ self.final_offload_hook.offload()
924
+
925
+ if not return_dict:
926
+ return (image,)
927
+
928
+ return StableDiffusionXLPipelineOutput(images=image)
929
+
930
+
931
+ if __name__ == "__main__":
932
+ pass