SunderAli17 commited on
Commit
8cce744
1 Parent(s): ba90d89

Create pipeline_stable_diffusion_xl_chatglm_256_ipadapter_FaceID.py

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