SunderAli17 commited on
Commit
13aeda5
·
verified ·
1 Parent(s): 5d58002

Create pipeline_stable_diffusion_xl_chatglm_256.py

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