Indulge-Bai commited on
Commit
3ac6b3a
·
verified ·
1 Parent(s): b9a1bf8

Create utils/pipeline_stable_diffusion_xl

Browse files
Files changed (1) hide show
  1. utils/pipeline_stable_diffusion_xl +1586 -0
utils/pipeline_stable_diffusion_xl ADDED
@@ -0,0 +1,1586 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ import os.path
3
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
4
+ import tqdm
5
+ import torch
6
+ from transformers import CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer
7
+ import pickle
8
+ import matplotlib.pyplot as plt
9
+
10
+ from diffusers.image_processor import VaeImageProcessor
11
+ from diffusers.loaders import (
12
+ FromSingleFileMixin,
13
+ StableDiffusionXLLoraLoaderMixin,
14
+ TextualInversionLoaderMixin,
15
+ LoraLoaderMixin
16
+ )
17
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
18
+ from diffusers.models.attention_processor import (
19
+ AttnProcessor2_0,
20
+ LoRAAttnProcessor2_0,
21
+ LoRAXFormersAttnProcessor,
22
+ XFormersAttnProcessor,
23
+ )
24
+ import math
25
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
26
+ from diffusers.schedulers import KarrasDiffusionSchedulers
27
+ from diffusers.utils import (
28
+ USE_PEFT_BACKEND,
29
+ deprecate,
30
+ is_invisible_watermark_available,
31
+ is_torch_xla_available,
32
+ logging,
33
+ replace_example_docstring,
34
+ scale_lora_layers,
35
+ unscale_lora_layers,
36
+ )
37
+ from diffusers.utils.torch_utils import randn_tensor
38
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
39
+ from diffusers.pipelines.stable_diffusion_xl.pipeline_output import StableDiffusionXLPipelineOutput
40
+
41
+
42
+ if is_invisible_watermark_available():
43
+ from diffusers.pipelines.stable_diffusion_xl.watermark import StableDiffusionXLWatermarker
44
+
45
+ if is_torch_xla_available():
46
+ import torch_xla.core.xla_model as xm
47
+
48
+ XLA_AVAILABLE = True
49
+ else:
50
+ XLA_AVAILABLE = False
51
+
52
+ from scipy import stats
53
+ def mle_gaussian_loss(latents):
54
+ data = latents.clone().detach().to('cpu').flatten().numpy()
55
+ skewness = stats.skew(data)
56
+ kurtosis = stats.kurtosis(data, fisher=False)
57
+ return abs(skewness) + abs(kurtosis - 3)
58
+
59
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
60
+
61
+ EXAMPLE_DOC_STRING = """
62
+ Examples:
63
+ ```py
64
+ >>> import torch
65
+ >>> from diffusers import StableDiffusionXLPipeline
66
+
67
+ >>> pipe = StableDiffusionXLPipeline.from_pretrained(
68
+ ... "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
69
+ ... )
70
+ >>> pipe = pipe.to("cuda")
71
+
72
+ >>> prompt = "a photo of an astronaut riding a horse on mars"
73
+ >>> image = pipe(prompt).images[0]
74
+ ```
75
+ """
76
+
77
+
78
+ def _backward_ddim(x_tm1, alpha_t, alpha_tm1, eps_xt):
79
+ """
80
+ let a = alpha_t, b = alpha_{t - 1}
81
+ We have a > b,
82
+ x_{t} - x_{t - 1} = sqrt(a) ((sqrt(1/b) - sqrt(1/a)) * x_{t-1} + (sqrt(1/a - 1) - sqrt(1/b - 1)) * eps_{t-1})
83
+ From https://arxiv.org/pdf/2105.05233.pdf, section F.
84
+ """
85
+
86
+ a, b = alpha_t, alpha_tm1
87
+ sa = a ** 0.5
88
+ sb = b ** 0.5
89
+
90
+ return sa * ((1 / sb) * x_tm1 + ((1 / a - 1) ** 0.5 - (1 / b - 1) ** 0.5) * eps_xt)
91
+
92
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
93
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
94
+ """
95
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
96
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
97
+ """
98
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
99
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
100
+ # rescale the results from guidance (fixes overexposure)
101
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
102
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
103
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
104
+ return noise_cfg
105
+
106
+ def gaussain_value(data):
107
+ # 计算均值和标准差
108
+ mean = data.mean()
109
+ std = data.std()
110
+ # 损失函数,鼓励均值趋近于0,标准差趋近于1
111
+ loss = (mean - 0) ** 2 + (std - 1) ** 2
112
+ return loss
113
+
114
+ class StableDiffusionXLPipeline(
115
+ DiffusionPipeline, FromSingleFileMixin, StableDiffusionXLLoraLoaderMixin, TextualInversionLoaderMixin
116
+ ):
117
+ r"""
118
+ Pipeline for text-to-image generation using Stable Diffusion XL.
119
+
120
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
121
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
122
+
123
+ In addition the pipeline inherits the following loading methods:
124
+ - *LoRA*: [`loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights`]
125
+ - *Ckpt*: [`loaders.FromSingleFileMixin.from_single_file`]
126
+
127
+ as well as the following saving methods:
128
+ - *LoRA*: [`loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights`]
129
+
130
+ Args:
131
+ vae ([`AutoencoderKL`]):
132
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
133
+ text_encoder ([`CLIPTextModel`]):
134
+ Frozen text-encoder. Stable Diffusion XL uses the text portion of
135
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
136
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
137
+ text_encoder_2 ([` CLIPTextModelWithProjection`]):
138
+ Second frozen text-encoder. Stable Diffusion XL uses the text and pool portion of
139
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
140
+ specifically the
141
+ [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)
142
+ variant.
143
+ tokenizer (`CLIPTokenizer`):
144
+ Tokenizer of class
145
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
146
+ tokenizer_2 (`CLIPTokenizer`):
147
+ Second Tokenizer of class
148
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
149
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
150
+ scheduler ([`SchedulerMixin`]):
151
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
152
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
153
+ force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"True"`):
154
+ Whether the negative prompt embeddings shall be forced to always be set to 0. Also see the config of
155
+ `stabilityai/stable-diffusion-xl-base-1-0`.
156
+ add_watermarker (`bool`, *optional*):
157
+ Whether to use the [invisible_watermark library](https://github.com/ShieldMnt/invisible-watermark/) to
158
+ watermark output images. If not defined, it will default to True if the package is installed, otherwise no
159
+ watermarker will be used.
160
+ """
161
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->unet->vae"
162
+ _optional_components = ["tokenizer", "tokenizer_2", "text_encoder", "text_encoder_2"]
163
+ _callback_tensor_inputs = [
164
+ "latents",
165
+ "prompt_embeds",
166
+ "negative_prompt_embeds",
167
+ "add_text_embeds",
168
+ "add_time_ids",
169
+ "negative_pooled_prompt_embeds",
170
+ "negative_add_time_ids",
171
+ ]
172
+
173
+ def __init__(
174
+ self,
175
+ vae: AutoencoderKL,
176
+ text_encoder: CLIPTextModel,
177
+ text_encoder_2: CLIPTextModelWithProjection,
178
+ tokenizer: CLIPTokenizer,
179
+ tokenizer_2: CLIPTokenizer,
180
+ unet: UNet2DConditionModel,
181
+ scheduler: KarrasDiffusionSchedulers,
182
+ force_zeros_for_empty_prompt: bool = True,
183
+ add_watermarker: Optional[bool] = None,
184
+ ):
185
+ super().__init__()
186
+
187
+ self.register_modules(
188
+ vae=vae,
189
+ text_encoder=text_encoder,
190
+ text_encoder_2=text_encoder_2,
191
+ tokenizer=tokenizer,
192
+ tokenizer_2=tokenizer_2,
193
+ unet=unet,
194
+ scheduler=scheduler,
195
+ )
196
+ self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
197
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
198
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
199
+
200
+ self.default_sample_size = self.unet.config.sample_size
201
+
202
+ add_watermarker = add_watermarker if add_watermarker is not None else is_invisible_watermark_available()
203
+
204
+ if add_watermarker:
205
+ self.watermark = StableDiffusionXLWatermarker()
206
+ else:
207
+ self.watermark = None
208
+
209
+
210
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_slicing
211
+ def enable_vae_slicing(self):
212
+ r"""
213
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
214
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
215
+ """
216
+ self.vae.enable_slicing()
217
+
218
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_slicing
219
+ def disable_vae_slicing(self):
220
+ r"""
221
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
222
+ computing decoding in one step.
223
+ """
224
+ self.vae.disable_slicing()
225
+
226
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_tiling
227
+ def enable_vae_tiling(self):
228
+ r"""
229
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
230
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
231
+ processing larger images.
232
+ """
233
+ self.vae.enable_tiling()
234
+
235
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_tiling
236
+ def disable_vae_tiling(self):
237
+ r"""
238
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
239
+ computing decoding in one step.
240
+ """
241
+ self.vae.disable_tiling()
242
+
243
+ def encode_prompt(
244
+ self,
245
+ prompt: str,
246
+ prompt_2: Optional[str] = None,
247
+ device: Optional[torch.device] = None,
248
+ num_images_per_prompt: int = 1,
249
+ do_classifier_free_guidance: bool = True,
250
+ negative_prompt: Optional[str] = None,
251
+ negative_prompt_2: Optional[str] = None,
252
+ prompt_embeds: Optional[torch.FloatTensor] = None,
253
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
254
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
255
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
256
+ lora_scale: Optional[float] = None,
257
+ clip_skip: Optional[int] = None,
258
+ ):
259
+ r"""
260
+ Encodes the prompt into text encoder hidden states.
261
+
262
+ Args:
263
+ prompt (`str` or `List[str]`, *optional*):
264
+ prompt to be encoded
265
+ prompt_2 (`str` or `List[str]`, *optional*):
266
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
267
+ used in both text-encoders
268
+ device: (`torch.device`):
269
+ torch device
270
+ num_images_per_prompt (`int`):
271
+ number of images that should be generated per prompt
272
+ do_classifier_free_guidance (`bool`):
273
+ whether to use classifier free guidance or not
274
+ negative_prompt (`str` or `List[str]`, *optional*):
275
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
276
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
277
+ less than `1`).
278
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
279
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
280
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
281
+ prompt_embeds (`torch.FloatTensor`, *optional*):
282
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
283
+ provided, text embeddings will be generated from `prompt` input argument.
284
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
285
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
286
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
287
+ argument.
288
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
289
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
290
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
291
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
292
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
293
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
294
+ input argument.
295
+ lora_scale (`float`, *optional*):
296
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
297
+ clip_skip (`int`, *optional*):
298
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
299
+ the output of the pre-final layer will be used for computing the prompt embeddings.
300
+ """
301
+ device = device or self._execution_device
302
+
303
+ # set lora scale so that monkey patched LoRA
304
+ # function of text encoder can correctly access it
305
+ if lora_scale is not None and isinstance(self, StableDiffusionXLLoraLoaderMixin):
306
+ self._lora_scale = lora_scale
307
+
308
+ # dynamically adjust the LoRA scale
309
+ if self.text_encoder is not None:
310
+ if not USE_PEFT_BACKEND:
311
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
312
+ else:
313
+ scale_lora_layers(self.text_encoder, lora_scale)
314
+
315
+ if self.text_encoder_2 is not None:
316
+ if not USE_PEFT_BACKEND:
317
+ adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
318
+ else:
319
+ scale_lora_layers(self.text_encoder_2, lora_scale)
320
+
321
+ prompt = [prompt] if isinstance(prompt, str) else prompt
322
+
323
+ if prompt is not None:
324
+ batch_size = len(prompt)
325
+ else:
326
+ batch_size = prompt_embeds.shape[0]
327
+
328
+ # Define tokenizers and text encoders
329
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
330
+ text_encoders = (
331
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
332
+ )
333
+
334
+ if prompt_embeds is None:
335
+ prompt_2 = prompt_2 or prompt
336
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
337
+
338
+ # textual inversion: procecss multi-vector tokens if necessary
339
+ prompt_embeds_list = []
340
+ prompts = [prompt, prompt_2]
341
+ for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
342
+ if isinstance(self, TextualInversionLoaderMixin):
343
+ prompt = self.maybe_convert_prompt(prompt, tokenizer)
344
+
345
+ text_inputs = tokenizer(
346
+ prompt,
347
+ padding="max_length",
348
+ max_length=tokenizer.model_max_length,
349
+ truncation=True,
350
+ return_tensors="pt",
351
+ )
352
+
353
+ text_input_ids = text_inputs.input_ids
354
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
355
+
356
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
357
+ text_input_ids, untruncated_ids
358
+ ):
359
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
360
+ logger.warning(
361
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
362
+ f" {tokenizer.model_max_length} tokens: {removed_text}"
363
+ )
364
+
365
+ prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=True)
366
+
367
+ # We are only ALWAYS interested in the pooled output of the final text encoder
368
+ pooled_prompt_embeds = prompt_embeds[0]
369
+ if clip_skip is None:
370
+ prompt_embeds = prompt_embeds.hidden_states[-2]
371
+ else:
372
+ # "2" because SDXL always indexes from the penultimate layer.
373
+ prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
374
+
375
+ prompt_embeds_list.append(prompt_embeds)
376
+
377
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
378
+
379
+ # get unconditional embeddings for classifier free guidance
380
+ zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
381
+ if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
382
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
383
+ negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
384
+ elif do_classifier_free_guidance and negative_prompt_embeds is None:
385
+ negative_prompt = negative_prompt or ""
386
+ negative_prompt_2 = negative_prompt_2 or negative_prompt
387
+
388
+ # normalize str to list
389
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
390
+ negative_prompt_2 = (
391
+ batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
392
+ )
393
+
394
+ uncond_tokens: List[str]
395
+ if prompt is not None and type(prompt) is not type(negative_prompt):
396
+ raise TypeError(
397
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
398
+ f" {type(prompt)}."
399
+ )
400
+ elif batch_size != len(negative_prompt):
401
+ raise ValueError(
402
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
403
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
404
+ " the batch size of `prompt`."
405
+ )
406
+ else:
407
+ uncond_tokens = [negative_prompt, negative_prompt_2]
408
+
409
+ negative_prompt_embeds_list = []
410
+ for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
411
+ if isinstance(self, TextualInversionLoaderMixin):
412
+ negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
413
+
414
+ max_length = prompt_embeds.shape[1]
415
+ uncond_input = tokenizer(
416
+ negative_prompt,
417
+ padding="max_length",
418
+ max_length=max_length,
419
+ truncation=True,
420
+ return_tensors="pt",
421
+ )
422
+
423
+ negative_prompt_embeds = text_encoder(
424
+ uncond_input.input_ids.to(device),
425
+ output_hidden_states=True,
426
+ )
427
+ # We are only ALWAYS interested in the pooled output of the final text encoder
428
+ negative_pooled_prompt_embeds = negative_prompt_embeds[0]
429
+ negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
430
+
431
+ negative_prompt_embeds_list.append(negative_prompt_embeds)
432
+
433
+ negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
434
+
435
+ if self.text_encoder_2 is not None:
436
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
437
+ else:
438
+ prompt_embeds = prompt_embeds.to(dtype=self.unet.dtype, device=device)
439
+
440
+ bs_embed, seq_len, _ = prompt_embeds.shape
441
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
442
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
443
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
444
+
445
+ if do_classifier_free_guidance:
446
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
447
+ seq_len = negative_prompt_embeds.shape[1]
448
+
449
+ if self.text_encoder_2 is not None:
450
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
451
+ else:
452
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.unet.dtype, device=device)
453
+
454
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
455
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
456
+
457
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
458
+ bs_embed * num_images_per_prompt, -1
459
+ )
460
+ if do_classifier_free_guidance:
461
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
462
+ bs_embed * num_images_per_prompt, -1
463
+ )
464
+
465
+ if self.text_encoder is not None:
466
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
467
+ # Retrieve the original scale by scaling back the LoRA layers
468
+ unscale_lora_layers(self.text_encoder, lora_scale)
469
+
470
+ if self.text_encoder_2 is not None:
471
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
472
+ # Retrieve the original scale by scaling back the LoRA layers
473
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
474
+
475
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
476
+
477
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
478
+ def prepare_extra_step_kwargs(self, generator, eta):
479
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
480
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
481
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
482
+ # and should be between [0, 1]
483
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
484
+ extra_step_kwargs = {}
485
+ if accepts_eta:
486
+ extra_step_kwargs["eta"] = eta
487
+
488
+ # check if the scheduler accepts generator
489
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
490
+ if accepts_generator:
491
+ extra_step_kwargs["generator"] = generator
492
+ return extra_step_kwargs
493
+
494
+ def check_inputs(
495
+ self,
496
+ prompt,
497
+ prompt_2,
498
+ height,
499
+ width,
500
+ callback_steps,
501
+ negative_prompt=None,
502
+ negative_prompt_2=None,
503
+ prompt_embeds=None,
504
+ negative_prompt_embeds=None,
505
+ pooled_prompt_embeds=None,
506
+ negative_pooled_prompt_embeds=None,
507
+ callback_on_step_end_tensor_inputs=None,
508
+ ):
509
+ if height % 8 != 0 or width % 8 != 0:
510
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
511
+
512
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
513
+ raise ValueError(
514
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
515
+ f" {type(callback_steps)}."
516
+ )
517
+
518
+ if callback_on_step_end_tensor_inputs is not None and not all(
519
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
520
+ ):
521
+ raise ValueError(
522
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
523
+ )
524
+
525
+ if prompt is not None and prompt_embeds is not None:
526
+ raise ValueError(
527
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
528
+ " only forward one of the two."
529
+ )
530
+ elif prompt_2 is not None and prompt_embeds is not None:
531
+ raise ValueError(
532
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
533
+ " only forward one of the two."
534
+ )
535
+ elif prompt is None and prompt_embeds is None:
536
+ raise ValueError(
537
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
538
+ )
539
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
540
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
541
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
542
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
543
+
544
+ if negative_prompt is not None and negative_prompt_embeds is not None:
545
+ raise ValueError(
546
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
547
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
548
+ )
549
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
550
+ raise ValueError(
551
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
552
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
553
+ )
554
+
555
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
556
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
557
+ raise ValueError(
558
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
559
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
560
+ f" {negative_prompt_embeds.shape}."
561
+ )
562
+
563
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
564
+ raise ValueError(
565
+ "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`."
566
+ )
567
+
568
+ if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
569
+ raise ValueError(
570
+ "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`."
571
+ )
572
+
573
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
574
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
575
+ shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
576
+ if isinstance(generator, list) and len(generator) != batch_size:
577
+ raise ValueError(
578
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
579
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
580
+ )
581
+
582
+ if latents is None:
583
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
584
+ else:
585
+ latents = latents.to(device)
586
+
587
+ # scale the initial noise by the standard deviation required by the scheduler
588
+ latents = latents * self.scheduler.init_noise_sigma
589
+ return latents
590
+
591
+ def _get_add_time_ids(
592
+ self, original_size, crops_coords_top_left, target_size, dtype, text_encoder_projection_dim=None
593
+ ):
594
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
595
+
596
+ passed_add_embed_dim = (
597
+ self.unet.config.addition_time_embed_dim * len(add_time_ids) + text_encoder_projection_dim
598
+ )
599
+ expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
600
+
601
+ if expected_add_embed_dim != passed_add_embed_dim:
602
+ raise ValueError(
603
+ 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`."
604
+ )
605
+
606
+ add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
607
+ return add_time_ids
608
+
609
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.StableDiffusionUpscalePipeline.upcast_vae
610
+ def upcast_vae(self):
611
+ dtype = self.vae.dtype
612
+ self.vae.to(dtype=torch.float32)
613
+ use_torch_2_0_or_xformers = isinstance(
614
+ self.vae.decoder.mid_block.attentions[0].processor,
615
+ (
616
+ AttnProcessor2_0,
617
+ XFormersAttnProcessor,
618
+ LoRAXFormersAttnProcessor,
619
+ LoRAAttnProcessor2_0,
620
+ ),
621
+ )
622
+ # if xformers or torch_2_0 is used attention block does not need
623
+ # to be in float32 which can save lots of memory
624
+ if use_torch_2_0_or_xformers:
625
+ self.vae.post_quant_conv.to(dtype)
626
+ self.vae.decoder.conv_in.to(dtype)
627
+ self.vae.decoder.mid_block.to(dtype)
628
+
629
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_freeu
630
+ def enable_freeu(self, s1: float, s2: float, b1: float, b2: float):
631
+ r"""Enables the FreeU mechanism as in https://arxiv.org/abs/2309.11497.
632
+
633
+ The suffixes after the scaling factors represent the stages where they are being applied.
634
+
635
+ Please refer to the [official repository](https://github.com/ChenyangSi/FreeU) for combinations of the values
636
+ that are known to work well for different pipelines such as Stable Diffusion v1, v2, and Stable Diffusion XL.
637
+
638
+ Args:
639
+ s1 (`float`):
640
+ Scaling factor for stage 1 to attenuate the contributions of the skip features. This is done to
641
+ mitigate "oversmoothing effect" in the enhanced denoising process.
642
+ s2 (`float`):
643
+ Scaling factor for stage 2 to attenuate the contributions of the skip features. This is done to
644
+ mitigate "oversmoothing effect" in the enhanced denoising process.
645
+ b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features.
646
+ b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features.
647
+ """
648
+ if not hasattr(self, "unet"):
649
+ raise ValueError("The pipeline must have `unet` for using FreeU.")
650
+ self.unet.enable_freeu(s1=s1, s2=s2, b1=b1, b2=b2)
651
+
652
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_freeu
653
+ def disable_freeu(self):
654
+ """Disables the FreeU mechanism if enabled."""
655
+ self.unet.disable_freeu()
656
+
657
+ @property
658
+ def guidance_scale(self):
659
+ return self._guidance_scale
660
+
661
+ @property
662
+ def guidance_rescale(self):
663
+ return self._guidance_rescale
664
+
665
+ @property
666
+ def clip_skip(self):
667
+ return self._clip_skip
668
+
669
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
670
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
671
+ # corresponds to doing no classifier free guidance.
672
+ @property
673
+ def do_classifier_free_guidance(self):
674
+ return self._guidance_scale > 1
675
+
676
+ @property
677
+ def cross_attention_kwargs(self):
678
+ return self._cross_attention_kwargs
679
+
680
+ @property
681
+ def denoising_end(self):
682
+ return self._denoising_end
683
+
684
+ @property
685
+ def num_timesteps(self):
686
+ return self._num_timesteps
687
+
688
+ @torch.no_grad()
689
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
690
+ def __call__(
691
+ self,
692
+ prompt: Union[str, List[str]] = None,
693
+ prompt_2: Optional[Union[str, List[str]]] = None,
694
+ height: Optional[int] = None,
695
+ width: Optional[int] = None,
696
+ num_inference_steps: int = 50,
697
+ denoising_end: Optional[float] = None,
698
+ guidance_scale: float = 5.0,
699
+ negative_prompt: Optional[Union[str, List[str]]] = None,
700
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
701
+ num_images_per_prompt: Optional[int] = 1,
702
+ eta: float = 0.0,
703
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
704
+ latents: Optional[torch.FloatTensor] = None,
705
+ prompt_embeds: Optional[torch.FloatTensor] = None,
706
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
707
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
708
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
709
+ output_type: Optional[str] = "pil",
710
+ return_dict: bool = True,
711
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
712
+ guidance_rescale: float = 0.0,
713
+ original_size: Optional[Tuple[int, int]] = None,
714
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
715
+ target_size: Optional[Tuple[int, int]] = None,
716
+ negative_original_size: Optional[Tuple[int, int]] = None,
717
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
718
+ negative_target_size: Optional[Tuple[int, int]] = None,
719
+ clip_skip: Optional[int] = None,
720
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
721
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
722
+ **kwargs,
723
+ ):
724
+ r"""
725
+ Function invoked when calling the pipeline for generation.
726
+
727
+ Args:
728
+ prompt (`str` or `List[str]`, *optional*):
729
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
730
+ instead.
731
+ prompt_2 (`str` or `List[str]`, *optional*):
732
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
733
+ used in both text-encoders
734
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
735
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
736
+ Anything below 512 pixels won't work well for
737
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
738
+ and checkpoints that are not specifically fine-tuned on low resolutions.
739
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
740
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
741
+ Anything below 512 pixels won't work well for
742
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
743
+ and checkpoints that are not specifically fine-tuned on low resolutions.
744
+ num_inference_steps (`int`, *optional*, defaults to 50):
745
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
746
+ expense of slower inference.
747
+ denoising_end (`float`, *optional*):
748
+ When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
749
+ completed before it is intentionally prematurely terminated. As a result, the returned sample will
750
+ still retain a substantial amount of noise as determined by the discrete timesteps selected by the
751
+ scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
752
+ "Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
753
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)
754
+ guidance_scale (`float`, *optional*, defaults to 5.0):
755
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
756
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
757
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
758
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
759
+ usually at the expense of lower image quality.
760
+ negative_prompt (`str` or `List[str]`, *optional*):
761
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
762
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
763
+ less than `1`).
764
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
765
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
766
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
767
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
768
+ The number of images to generate per prompt.
769
+ eta (`float`, *optional*, defaults to 0.0):
770
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
771
+ [`schedulers.DDIMScheduler`], will be ignored for others.
772
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
773
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
774
+ to make generation deterministic.
775
+ latents (`torch.FloatTensor`, *optional*):
776
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
777
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
778
+ tensor will ge generated by sampling using the supplied random `generator`.
779
+ prompt_embeds (`torch.FloatTensor`, *optional*):
780
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
781
+ provided, text embeddings will be generated from `prompt` input argument.
782
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
783
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
784
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
785
+ argument.
786
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
787
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
788
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
789
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
790
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
791
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
792
+ input argument.
793
+ output_type (`str`, *optional*, defaults to `"pil"`):
794
+ The output format of the generate image. Choose between
795
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
796
+ return_dict (`bool`, *optional*, defaults to `True`):
797
+ Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
798
+ of a plain tuple.
799
+ cross_attention_kwargs (`dict`, *optional*):
800
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
801
+ `self.processor` in
802
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
803
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
804
+ Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
805
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
806
+ [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
807
+ Guidance rescale factor should fix overexposure when using zero terminal SNR.
808
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
809
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
810
+ `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
811
+ explained in section 2.2 of
812
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
813
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
814
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
815
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
816
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
817
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
818
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
819
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
820
+ not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
821
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
822
+ negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
823
+ To negatively condition the generation process based on a specific image resolution. Part of SDXL's
824
+ micro-conditioning as explained in section 2.2 of
825
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
826
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
827
+ negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
828
+ To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
829
+ micro-conditioning as explained in section 2.2 of
830
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
831
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
832
+ negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
833
+ To negatively condition the generation process based on a target image resolution. It should be as same
834
+ as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
835
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
836
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
837
+ callback_on_step_end (`Callable`, *optional*):
838
+ A function that calls at the end of each denoising steps during the inference. The function is called
839
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
840
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
841
+ `callback_on_step_end_tensor_inputs`.
842
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
843
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
844
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
845
+ `._callback_tensor_inputs` attribute of your pipeine class.
846
+
847
+ Examples:
848
+
849
+ Returns:
850
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] or `tuple`:
851
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
852
+ `tuple`. When returning a tuple, the first element is a list with the generated images.
853
+ """
854
+
855
+ callback = kwargs.pop("callback", None)
856
+ callback_steps = kwargs.pop("callback_steps", None)
857
+
858
+ if callback is not None:
859
+ deprecate(
860
+ "callback",
861
+ "1.0.0",
862
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
863
+ )
864
+ if callback_steps is not None:
865
+ deprecate(
866
+ "callback_steps",
867
+ "1.0.0",
868
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
869
+ )
870
+
871
+ # 0. Default height and width to unet
872
+ height = height or self.default_sample_size * self.vae_scale_factor
873
+ width = width or self.default_sample_size * self.vae_scale_factor
874
+
875
+ original_size = original_size or (height, width)
876
+ target_size = target_size or (height, width)
877
+
878
+ # 1. Check inputs. Raise error if not correct
879
+ self.check_inputs(
880
+ prompt,
881
+ prompt_2,
882
+ height,
883
+ width,
884
+ callback_steps,
885
+ negative_prompt,
886
+ negative_prompt_2,
887
+ prompt_embeds,
888
+ negative_prompt_embeds,
889
+ pooled_prompt_embeds,
890
+ negative_pooled_prompt_embeds,
891
+ callback_on_step_end_tensor_inputs,
892
+ )
893
+
894
+ self._guidance_scale = guidance_scale
895
+ self._guidance_rescale = guidance_rescale
896
+ self._clip_skip = clip_skip
897
+ self._cross_attention_kwargs = cross_attention_kwargs
898
+ self._denoising_end = denoising_end
899
+
900
+ # 2. Define call parameters
901
+ if prompt is not None and isinstance(prompt, str):
902
+ batch_size = 1
903
+ elif prompt is not None and isinstance(prompt, list):
904
+ batch_size = len(prompt)
905
+ else:
906
+ batch_size = prompt_embeds.shape[0]
907
+
908
+ device = self._execution_device
909
+
910
+ # 3. Encode input prompt
911
+ lora_scale = (
912
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
913
+ )
914
+
915
+ (
916
+ prompt_embeds,
917
+ negative_prompt_embeds,
918
+ pooled_prompt_embeds,
919
+ negative_pooled_prompt_embeds,
920
+ ) = self.encode_prompt(
921
+ prompt=prompt,
922
+ prompt_2=prompt_2,
923
+ device=device,
924
+ num_images_per_prompt=num_images_per_prompt,
925
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
926
+ negative_prompt=negative_prompt,
927
+ negative_prompt_2=negative_prompt_2,
928
+ prompt_embeds=prompt_embeds,
929
+ negative_prompt_embeds=negative_prompt_embeds,
930
+ pooled_prompt_embeds=pooled_prompt_embeds,
931
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
932
+ lora_scale=lora_scale,
933
+ clip_skip=self.clip_skip,
934
+ )
935
+
936
+ # 4. Prepare timesteps
937
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
938
+
939
+ timesteps = self.scheduler.timesteps
940
+
941
+ # 5. Prepare latent variables
942
+ num_channels_latents = self.unet.config.in_channels
943
+ latents = self.prepare_latents(
944
+ batch_size * num_images_per_prompt,
945
+ num_channels_latents,
946
+ height,
947
+ width,
948
+ prompt_embeds.dtype,
949
+ device,
950
+ generator,
951
+ latents,
952
+ )
953
+
954
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
955
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
956
+
957
+ # 7. Prepare added time ids & embeddings
958
+ add_text_embeds = pooled_prompt_embeds
959
+ if self.text_encoder_2 is None:
960
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
961
+ else:
962
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
963
+
964
+ add_time_ids = self._get_add_time_ids(
965
+ original_size,
966
+ crops_coords_top_left,
967
+ target_size,
968
+ dtype=prompt_embeds.dtype,
969
+ text_encoder_projection_dim=text_encoder_projection_dim,
970
+ )
971
+ if negative_original_size is not None and negative_target_size is not None:
972
+ negative_add_time_ids = self._get_add_time_ids(
973
+ negative_original_size,
974
+ negative_crops_coords_top_left,
975
+ negative_target_size,
976
+ dtype=prompt_embeds.dtype,
977
+ text_encoder_projection_dim=text_encoder_projection_dim,
978
+ )
979
+ else:
980
+ negative_add_time_ids = add_time_ids
981
+
982
+ if self.do_classifier_free_guidance:
983
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
984
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
985
+ add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
986
+
987
+ prompt_embeds = prompt_embeds.to(device)
988
+ add_text_embeds = add_text_embeds.to(device)
989
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
990
+
991
+ # 8. Denoising loop
992
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
993
+
994
+ # 8.1 Apply denoising_end
995
+ if (
996
+ self.denoising_end is not None
997
+ and isinstance(self.denoising_end, float)
998
+ and self.denoising_end > 0
999
+ and self.denoising_end < 1
1000
+ ):
1001
+ discrete_timestep_cutoff = int(
1002
+ round(
1003
+ self.scheduler.config.num_train_timesteps
1004
+ - (self.denoising_end * self.scheduler.config.num_train_timesteps)
1005
+ )
1006
+ )
1007
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
1008
+ timesteps = timesteps[:num_inference_steps]
1009
+ self._num_timesteps = len(timesteps)
1010
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1011
+ for i, t in enumerate(timesteps):
1012
+ # expand the latents if we are doing classifier free guidance
1013
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1014
+
1015
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1016
+
1017
+ # predict the noise residual
1018
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
1019
+ noise_pred = self.unet(
1020
+ latent_model_input,
1021
+ t,
1022
+ encoder_hidden_states=prompt_embeds,
1023
+ cross_attention_kwargs=self.cross_attention_kwargs,
1024
+ added_cond_kwargs=added_cond_kwargs,
1025
+ return_dict=False,
1026
+ )[0]
1027
+
1028
+ # perform guidance
1029
+ if self.do_classifier_free_guidance:
1030
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1031
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
1032
+
1033
+ if self.do_classifier_free_guidance and self.guidance_rescale > 0.0:
1034
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1035
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale)
1036
+
1037
+ # compute the previous noisy sample x_t -> x_t-1
1038
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1039
+
1040
+ if callback_on_step_end is not None:
1041
+ callback_kwargs = {}
1042
+ for k in callback_on_step_end_tensor_inputs:
1043
+ callback_kwargs[k] = locals()[k]
1044
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1045
+
1046
+ latents = callback_outputs.pop("latents", latents)
1047
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1048
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1049
+ add_text_embeds = callback_outputs.pop("add_text_embeds", add_text_embeds)
1050
+ negative_pooled_prompt_embeds = callback_outputs.pop(
1051
+ "negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
1052
+ )
1053
+ add_time_ids = callback_outputs.pop("add_time_ids", add_time_ids)
1054
+ negative_add_time_ids = callback_outputs.pop("negative_add_time_ids", negative_add_time_ids)
1055
+
1056
+ # call the callback, if provided
1057
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1058
+ progress_bar.update()
1059
+ if callback is not None and i % callback_steps == 0:
1060
+ step_idx = i // getattr(self.scheduler, "order", 1)
1061
+ callback(step_idx, t, latents)
1062
+
1063
+ if XLA_AVAILABLE:
1064
+ xm.mark_step()
1065
+
1066
+
1067
+ if not output_type == "latent":
1068
+ # make sure the VAE is in float32 mode, as it overflows in float16
1069
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
1070
+
1071
+ if needs_upcasting:
1072
+ self.upcast_vae()
1073
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1074
+
1075
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
1076
+
1077
+ # cast back to fp16 if needed
1078
+ if needs_upcasting:
1079
+ self.vae.to(dtype=torch.float16)
1080
+ else:
1081
+ image = latents
1082
+
1083
+ if not output_type == "latent":
1084
+ # apply watermark if available
1085
+ if self.watermark is not None:
1086
+ image = self.watermark.apply_watermark(image)
1087
+
1088
+ image = self.image_processor.postprocess(image, output_type=output_type)
1089
+
1090
+ # Offload all models
1091
+ self.maybe_free_model_hooks()
1092
+
1093
+ if not return_dict:
1094
+ return (image,)
1095
+
1096
+ return StableDiffusionXLPipelineOutput(images=image)
1097
+
1098
+
1099
+ def reflection_operation(self, i, latents, cfg_gap_list, lora_gap_list, lora_name, lora_scale, prompt_embeds, timesteps, add_text_embeds, add_time_ids, extra_step_kwargs):
1100
+ #TODO zig
1101
+ t = timesteps[i]
1102
+ latent_model_input = torch.cat([latents] * 2) if cfg_gap_list[0] >= 0 else latents
1103
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1104
+ # predict the noise residual
1105
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
1106
+ if lora_name is not "SDXL":
1107
+ self.disable_lora()
1108
+ self.enable_lora()
1109
+ self.set_adapters(lora_name, adapter_weights=lora_gap_list[0])
1110
+ with torch.no_grad():
1111
+ noise_pred = self.unet(
1112
+ latent_model_input,
1113
+ t,
1114
+ encoder_hidden_states=prompt_embeds,
1115
+ cross_attention_kwargs=self.cross_attention_kwargs,
1116
+ added_cond_kwargs=added_cond_kwargs,
1117
+ return_dict=False,
1118
+ )[0]
1119
+
1120
+ # perform guidance
1121
+ if cfg_gap_list[0] >= 0:
1122
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1123
+ noise_pred = noise_pred_uncond + cfg_gap_list[0] * (noise_pred_text - noise_pred_uncond)
1124
+ # compute the previous noisy sample x_t -> x_t-1
1125
+ self.scheduler._step_index = None
1126
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1127
+
1128
+ #TODO zag
1129
+ latent_model_input = torch.cat([latents] * 2) if cfg_gap_list[1] >= 0 else latents
1130
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1131
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
1132
+ if lora_name is not "SDXL":
1133
+ self.disable_lora()
1134
+ self.enable_lora()
1135
+ self.set_adapters(lora_name, adapter_weights=lora_gap_list[1])
1136
+ with torch.no_grad():
1137
+ noise_pred = self.unet(
1138
+ latent_model_input,
1139
+ t,
1140
+ encoder_hidden_states=prompt_embeds,
1141
+ cross_attention_kwargs=self.cross_attention_kwargs,
1142
+ added_cond_kwargs=added_cond_kwargs,
1143
+ return_dict=False,
1144
+ )[0]
1145
+ # TODO weak perform guidance
1146
+ if cfg_gap_list[1] >= 0:
1147
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1148
+ noise_pred = noise_pred_uncond + cfg_gap_list[1] * (
1149
+ noise_pred_text - noise_pred_uncond)
1150
+
1151
+ self.inv_scheduler._step_index = None
1152
+ inv_latents = self.inv_scheduler.step(noise_pred, timesteps[i + 1], latents, return_dict=False)[0]
1153
+
1154
+ self.disable_lora()
1155
+ if lora_scale !=0:
1156
+ self.enable_lora()
1157
+ self.set_adapters(lora_name, adapter_weights=lora_scale)
1158
+ else:
1159
+ pass
1160
+ #no APG
1161
+ return inv_latents
1162
+
1163
+
1164
+ @torch.no_grad()
1165
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
1166
+ def w2sd_lora(
1167
+ self,
1168
+ prompt: Union[str, List[str]] = None,
1169
+ prompt_2: Optional[Union[str, List[str]]] = None,
1170
+ height: Optional[int] = None,
1171
+ width: Optional[int] = None,
1172
+ num_inference_steps: int = 50,
1173
+ denoising_end: Optional[float] = None,
1174
+ guidance_scale: float = 5.0,
1175
+ negative_prompt: Optional[Union[str, List[str]]] = None,
1176
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
1177
+ num_images_per_prompt: Optional[int] = 1,
1178
+ eta: float = 0.0,
1179
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
1180
+ latents: Optional[torch.FloatTensor] = None,
1181
+ prompt_embeds: Optional[torch.FloatTensor] = None,
1182
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
1183
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
1184
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
1185
+ output_type: Optional[str] = "pil",
1186
+ return_dict: bool = True,
1187
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1188
+ guidance_rescale: float = 0.0,
1189
+ original_size: Optional[Tuple[int, int]] = None,
1190
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
1191
+ target_size: Optional[Tuple[int, int]] = None,
1192
+ negative_original_size: Optional[Tuple[int, int]] = None,
1193
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
1194
+ negative_target_size: Optional[Tuple[int, int]] = None,
1195
+ clip_skip: Optional[int] = None,
1196
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
1197
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
1198
+ cfg_gap_list = [5.5, 1.0],
1199
+ lora_gap_list = [0.8,-1.5],
1200
+ lora_name="user_lora",
1201
+ denoise_lora_scale = 0.8,
1202
+ **kwargs,
1203
+ ):
1204
+ r"""
1205
+ Function invoked when calling the pipeline for generation.
1206
+
1207
+ Args:
1208
+ prompt (`str` or `List[str]`, *optional*):
1209
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
1210
+ instead.
1211
+ prompt_2 (`str` or `List[str]`, *optional*):
1212
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
1213
+ used in both text-encoders
1214
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
1215
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
1216
+ Anything below 512 pixels won't work well for
1217
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
1218
+ and checkpoints that are not specifically fine-tuned on low resolutions.
1219
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
1220
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
1221
+ Anything below 512 pixels won't work well for
1222
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
1223
+ and checkpoints that are not specifically fine-tuned on low resolutions.
1224
+ num_inference_steps (`int`, *optional*, defaults to 50):
1225
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
1226
+ expense of slower inference.
1227
+ denoising_end (`float`, *optional*):
1228
+ When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
1229
+ completed before it is intentionally prematurely terminated. As a result, the returned sample will
1230
+ still retain a substantial amount of noise as determined by the discrete timesteps selected by the
1231
+ scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
1232
+ "Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
1233
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)
1234
+ guidance_scale (`float`, *optional*, defaults to 5.0):
1235
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
1236
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
1237
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
1238
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
1239
+ usually at the expense of lower image quality.
1240
+ negative_prompt (`str` or `List[str]`, *optional*):
1241
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
1242
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
1243
+ less than `1`).
1244
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
1245
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
1246
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
1247
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1248
+ The number of images to generate per prompt.
1249
+ eta (`float`, *optional*, defaults to 0.0):
1250
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
1251
+ [`schedulers.DDIMScheduler`], will be ignored for others.
1252
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
1253
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
1254
+ to make generation deterministic.
1255
+ latents (`torch.FloatTensor`, *optional*):
1256
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
1257
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
1258
+ tensor will ge generated by sampling using the supplied random `generator`.
1259
+ prompt_embeds (`torch.FloatTensor`, *optional*):
1260
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
1261
+ provided, text embeddings will be generated from `prompt` input argument.
1262
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
1263
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
1264
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
1265
+ argument.
1266
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
1267
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
1268
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
1269
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
1270
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
1271
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
1272
+ input argument.
1273
+ output_type (`str`, *optional*, defaults to `"pil"`):
1274
+ The output format of the generate image. Choose between
1275
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
1276
+ return_dict (`bool`, *optional*, defaults to `True`):
1277
+ Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
1278
+ of a plain tuple.
1279
+ cross_attention_kwargs (`dict`, *optional*):
1280
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
1281
+ `self.processor` in
1282
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1283
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
1284
+ Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
1285
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
1286
+ [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
1287
+ Guidance rescale factor should fix overexposure when using zero terminal SNR.
1288
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1289
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
1290
+ `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
1291
+ explained in section 2.2 of
1292
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1293
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
1294
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
1295
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
1296
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
1297
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1298
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1299
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
1300
+ not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
1301
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1302
+ negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1303
+ To negatively condition the generation process based on a specific image resolution. Part of SDXL's
1304
+ micro-conditioning as explained in section 2.2 of
1305
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1306
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1307
+ negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
1308
+ To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
1309
+ micro-conditioning as explained in section 2.2 of
1310
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1311
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1312
+ negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1313
+ To negatively condition the generation process based on a target image resolution. It should be as same
1314
+ as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
1315
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1316
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1317
+ callback_on_step_end (`Callable`, *optional*):
1318
+ A function that calls at the end of each denoising steps during the inference. The function is called
1319
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
1320
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
1321
+ `callback_on_step_end_tensor_inputs`.
1322
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
1323
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
1324
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
1325
+ `._callback_tensor_inputs` attribute of your pipeine class.
1326
+
1327
+ Examples:
1328
+
1329
+ Returns:
1330
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] or `tuple`:
1331
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
1332
+ `tuple`. When returning a tuple, the first element is a list with the generated images.
1333
+ """
1334
+
1335
+ callback = kwargs.pop("callback", None)
1336
+ callback_steps = kwargs.pop("callback_steps", None)
1337
+
1338
+ if callback is not None:
1339
+ deprecate(
1340
+ "callback",
1341
+ "1.0.0",
1342
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
1343
+ )
1344
+ if callback_steps is not None:
1345
+ deprecate(
1346
+ "callback_steps",
1347
+ "1.0.0",
1348
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
1349
+ )
1350
+
1351
+ # 0. Default height and width to unet
1352
+ height = height or self.default_sample_size * self.vae_scale_factor
1353
+ width = width or self.default_sample_size * self.vae_scale_factor
1354
+
1355
+ original_size = original_size or (height, width)
1356
+ target_size = target_size or (height, width)
1357
+
1358
+ # 1. Check inputs. Raise error if not correct
1359
+ self.check_inputs(
1360
+ prompt,
1361
+ prompt_2,
1362
+ height,
1363
+ width,
1364
+ callback_steps,
1365
+ negative_prompt,
1366
+ negative_prompt_2,
1367
+ prompt_embeds,
1368
+ negative_prompt_embeds,
1369
+ pooled_prompt_embeds,
1370
+ negative_pooled_prompt_embeds,
1371
+ callback_on_step_end_tensor_inputs,
1372
+ )
1373
+
1374
+ self._guidance_scale = guidance_scale
1375
+ self._guidance_rescale = guidance_rescale
1376
+ self._clip_skip = clip_skip
1377
+ self._cross_attention_kwargs = cross_attention_kwargs
1378
+ self._denoising_end = denoising_end
1379
+
1380
+ # 2. Define call parameters
1381
+ if prompt is not None and isinstance(prompt, str):
1382
+ batch_size = 1
1383
+ elif prompt is not None and isinstance(prompt, list):
1384
+ batch_size = len(prompt)
1385
+ else:
1386
+ batch_size = prompt_embeds.shape[0]
1387
+
1388
+ device = self._execution_device
1389
+
1390
+ # 3. Encode input prompt
1391
+ lora_scale = (
1392
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
1393
+ )
1394
+
1395
+ (
1396
+ prompt_embeds,
1397
+ negative_prompt_embeds,
1398
+ pooled_prompt_embeds,
1399
+ negative_pooled_prompt_embeds,
1400
+ ) = self.encode_prompt(
1401
+ prompt=prompt,
1402
+ prompt_2=prompt_2,
1403
+ device=device,
1404
+ num_images_per_prompt=num_images_per_prompt,
1405
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1406
+ negative_prompt=negative_prompt,
1407
+ negative_prompt_2=negative_prompt_2,
1408
+ prompt_embeds=prompt_embeds,
1409
+ negative_prompt_embeds=negative_prompt_embeds,
1410
+ pooled_prompt_embeds=pooled_prompt_embeds,
1411
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
1412
+ lora_scale=lora_scale,
1413
+ clip_skip=self.clip_skip,
1414
+ )
1415
+
1416
+ # 4. Prepare timesteps
1417
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
1418
+ self.inv_scheduler.set_timesteps(num_inference_steps, device=device)
1419
+
1420
+ timesteps = self.scheduler.timesteps
1421
+
1422
+ # 5. Prepare latent variables
1423
+ num_channels_latents = self.unet.config.in_channels
1424
+ latents = self.prepare_latents(
1425
+ batch_size * num_images_per_prompt,
1426
+ num_channels_latents,
1427
+ height,
1428
+ width,
1429
+ prompt_embeds.dtype,
1430
+ device,
1431
+ generator,
1432
+ latents,
1433
+ )
1434
+
1435
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1436
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1437
+
1438
+ # 7. Prepare added time ids & embeddings
1439
+ add_text_embeds = pooled_prompt_embeds
1440
+ if self.text_encoder_2 is None:
1441
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
1442
+ else:
1443
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
1444
+
1445
+ add_time_ids = self._get_add_time_ids(
1446
+ original_size,
1447
+ crops_coords_top_left,
1448
+ target_size,
1449
+ dtype=prompt_embeds.dtype,
1450
+ text_encoder_projection_dim=text_encoder_projection_dim,
1451
+ )
1452
+ if negative_original_size is not None and negative_target_size is not None:
1453
+ negative_add_time_ids = self._get_add_time_ids(
1454
+ negative_original_size,
1455
+ negative_crops_coords_top_left,
1456
+ negative_target_size,
1457
+ dtype=prompt_embeds.dtype,
1458
+ text_encoder_projection_dim=text_encoder_projection_dim,
1459
+ )
1460
+ else:
1461
+ negative_add_time_ids = add_time_ids
1462
+
1463
+ if self.do_classifier_free_guidance:
1464
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
1465
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
1466
+ add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
1467
+
1468
+
1469
+ prompt_embeds = prompt_embeds.to(device)
1470
+ add_text_embeds = add_text_embeds.to(device)
1471
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
1472
+
1473
+ # 8. Denoising loop
1474
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
1475
+
1476
+ # 8.1 Apply denoising_end
1477
+ if (
1478
+ self.denoising_end is not None
1479
+ and isinstance(self.denoising_end, float)
1480
+ and self.denoising_end > 0
1481
+ and self.denoising_end < 1
1482
+ ):
1483
+ discrete_timestep_cutoff = int(
1484
+ round(
1485
+ self.scheduler.config.num_train_timesteps
1486
+ - (self.denoising_end * self.scheduler.config.num_train_timesteps)
1487
+ )
1488
+ )
1489
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
1490
+ timesteps = timesteps[:num_inference_steps]
1491
+ self._num_timesteps = len(timesteps)
1492
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1493
+ for i, t in enumerate(timesteps):
1494
+
1495
+ #TODO w2sd
1496
+ # if i < len(timesteps)-1:
1497
+ if i < len(timesteps)//2:
1498
+ latents = self.reflection_operation(i, latents, cfg_gap_list, lora_gap_list, lora_name, denoise_lora_scale,
1499
+ prompt_embeds, timesteps,
1500
+ add_text_embeds, add_time_ids, extra_step_kwargs)
1501
+
1502
+
1503
+ # expand the latents if we are doing classifier free guidance
1504
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1505
+
1506
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1507
+
1508
+ # predict the noise residual
1509
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
1510
+ noise_pred = self.unet(
1511
+ latent_model_input,
1512
+ t,
1513
+ encoder_hidden_states=prompt_embeds,
1514
+ cross_attention_kwargs=self.cross_attention_kwargs,
1515
+ added_cond_kwargs=added_cond_kwargs,
1516
+ return_dict=False,
1517
+ )[0]
1518
+
1519
+ # perform guidance
1520
+ if self.do_classifier_free_guidance:
1521
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1522
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
1523
+
1524
+ if self.do_classifier_free_guidance and self.guidance_rescale > 0.0:
1525
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1526
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale)
1527
+
1528
+ # compute the previous noisy sample x_t -> x_t-1
1529
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1530
+
1531
+ if callback_on_step_end is not None:
1532
+ callback_kwargs = {}
1533
+ for k in callback_on_step_end_tensor_inputs:
1534
+ callback_kwargs[k] = locals()[k]
1535
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1536
+
1537
+ latents = callback_outputs.pop("latents", latents)
1538
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1539
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1540
+ add_text_embeds = callback_outputs.pop("add_text_embeds", add_text_embeds)
1541
+ negative_pooled_prompt_embeds = callback_outputs.pop(
1542
+ "negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
1543
+ )
1544
+ add_time_ids = callback_outputs.pop("add_time_ids", add_time_ids)
1545
+ negative_add_time_ids = callback_outputs.pop("negative_add_time_ids", negative_add_time_ids)
1546
+
1547
+ # call the callback, if provided
1548
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1549
+ progress_bar.update()
1550
+ if callback is not None and i % callback_steps == 0:
1551
+ step_idx = i // getattr(self.scheduler, "order", 1)
1552
+ callback(step_idx, t, latents)
1553
+
1554
+ if XLA_AVAILABLE:
1555
+ xm.mark_step()
1556
+
1557
+ if not output_type == "latent":
1558
+ # make sure the VAE is in float32 mode, as it overflows in float16
1559
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
1560
+
1561
+ if needs_upcasting:
1562
+ self.upcast_vae()
1563
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1564
+
1565
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
1566
+
1567
+ # cast back to fp16 if needed
1568
+ if needs_upcasting:
1569
+ self.vae.to(dtype=torch.float16)
1570
+ else:
1571
+ image = latents
1572
+
1573
+ if not output_type == "latent":
1574
+ # apply watermark if available
1575
+ if self.watermark is not None:
1576
+ image = self.watermark.apply_watermark(image)
1577
+
1578
+ image = self.image_processor.postprocess(image, output_type=output_type)
1579
+
1580
+ # Offload all models
1581
+ self.maybe_free_model_hooks()
1582
+
1583
+ if not return_dict:
1584
+ return (image,)
1585
+
1586
+ return StableDiffusionXLPipelineOutput(images=image)