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

Create pipelines/sdxl_SAKBIR.py

Browse files
Files changed (1) hide show
  1. pipelines/sdxl_SAKBIR.py +1721 -0
pipelines/sdxl_SAKBIR.py ADDED
@@ -0,0 +1,1721 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The InstantX Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ import inspect
17
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
18
+
19
+ import numpy as np
20
+ import PIL.Image
21
+ import torch
22
+ import torch.nn.functional as F
23
+ from transformers import (
24
+ CLIPImageProcessor,
25
+ CLIPTextModel,
26
+ CLIPTextModelWithProjection,
27
+ CLIPTokenizer,
28
+ CLIPVisionModelWithProjection,
29
+ )
30
+
31
+ from diffusers.utils.import_utils import is_invisible_watermark_available
32
+
33
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
34
+ from diffusers.loaders import (
35
+ FromSingleFileMixin,
36
+ IPAdapterMixin,
37
+ StableDiffusionXLLoraLoaderMixin,
38
+ TextualInversionLoaderMixin,
39
+ )
40
+ from diffusers.models import AutoencoderKL, ImageProjection, UNet2DConditionModel
41
+ from diffusers.models.attention_processor import (
42
+ AttnProcessor2_0,
43
+ LoRAAttnProcessor2_0,
44
+ LoRAXFormersAttnProcessor,
45
+ XFormersAttnProcessor,
46
+ )
47
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
48
+ from diffusers.schedulers import KarrasDiffusionSchedulers, LCMScheduler
49
+ from diffusers.utils import (
50
+ USE_PEFT_BACKEND,
51
+ deprecate,
52
+ logging,
53
+ replace_example_docstring,
54
+ scale_lora_layers,
55
+ unscale_lora_layers,
56
+ convert_unet_state_dict_to_peft
57
+ )
58
+ from diffusers.utils.torch_utils import is_compiled_module, is_torch_version, randn_tensor
59
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
60
+ from diffusers.pipelines.stable_diffusion_xl.pipeline_output import StableDiffusionXLPipelineOutput
61
+
62
+
63
+ if is_invisible_watermark_available():
64
+ from diffusers.pipelines.stable_diffusion_xl.watermark import StableDiffusionXLWatermarker
65
+
66
+ from peft import LoraConfig, set_peft_model_state_dict
67
+ from module.aggregator import Aggregator
68
+
69
+
70
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
71
+
72
+
73
+ EXAMPLE_DOC_STRING = """
74
+ Examples:
75
+ ```py
76
+ >>> # !pip install diffusers pillow transformers accelerate
77
+ >>> import torch
78
+ >>> from PIL import Image
79
+ >>> from diffusers import DDPMScheduler
80
+ >>> from schedulers.lcm_single_step_scheduler import LCMSingleStepScheduler
81
+ >>> from module.ip_adapter.utils import load_adapter_to_pipe
82
+ >>> from pipelines.sdxl_instantir import InstantIRPipeline
83
+ >>> # download models under ./models
84
+ >>> dcp_adapter = f'./models/adapter.pt'
85
+ >>> previewer_lora_path = f'./models'
86
+ >>> instantir_path = f'./models/aggregator.pt'
87
+ >>> # load pretrained models
88
+ >>> pipe = InstantIRPipeline.from_pretrained(
89
+ ... "stabilityai/stable-diffusion-xl-base-1.0", controlnet=controlnet, vae=vae, torch_dtype=torch.float16
90
+ ... )
91
+ >>> # load adapter
92
+ >>> load_adapter_to_pipe(
93
+ ... pipe,
94
+ ... dcp_adapter,
95
+ ... image_encoder_or_path = 'facebook/dinov2-large',
96
+ ... )
97
+ >>> # load previewer lora
98
+ >>> pipe.prepare_previewers(previewer_lora_path)
99
+ >>> pipe.scheduler = DDPMScheduler.from_pretrained('stabilityai/stable-diffusion-xl-base-1.0', subfolder="scheduler")
100
+ >>> lcm_scheduler = LCMSingleStepScheduler.from_config(pipe.scheduler.config)
101
+ >>> # load aggregator weights
102
+ >>> pretrained_state_dict = torch.load(instantir_path)
103
+ >>> pipe.aggregator.load_state_dict(pretrained_state_dict)
104
+ >>> # send to GPU and fp16
105
+ >>> pipe.to(device="cuda", dtype=torch.float16)
106
+ >>> pipe.aggregator.to(device="cuda", dtype=torch.float16)
107
+ >>> pipe.enable_model_cpu_offload()
108
+ >>> # load a broken image
109
+ >>> low_quality_image = Image.open('path/to/your-image').convert("RGB")
110
+ >>> # restoration
111
+ >>> image = pipe(
112
+ ... image=low_quality_image,
113
+ ... previewer_scheduler=lcm_scheduler,
114
+ ... ).images[0]
115
+ ```
116
+ """
117
+
118
+ LCM_LORA_MODULES = [
119
+ "to_q",
120
+ "to_k",
121
+ "to_v",
122
+ "to_out.0",
123
+ "proj_in",
124
+ "proj_out",
125
+ "ff.net.0.proj",
126
+ "ff.net.2",
127
+ "conv1",
128
+ "conv2",
129
+ "conv_shortcut",
130
+ "downsamplers.0.conv",
131
+ "upsamplers.0.conv",
132
+ "time_emb_proj",
133
+ ]
134
+ PREVIEWER_LORA_MODULES = [
135
+ "to_q",
136
+ "to_kv",
137
+ "0.to_out",
138
+ "attn1.to_k",
139
+ "attn1.to_v",
140
+ "to_k_ip",
141
+ "to_v_ip",
142
+ "ln_k_ip.linear",
143
+ "ln_v_ip.linear",
144
+ "to_out.0",
145
+ "proj_in",
146
+ "proj_out",
147
+ "ff.net.0.proj",
148
+ "ff.net.2",
149
+ "conv1",
150
+ "conv2",
151
+ "conv_shortcut",
152
+ "downsamplers.0.conv",
153
+ "upsamplers.0.conv",
154
+ "time_emb_proj",
155
+ ]
156
+
157
+
158
+ def remove_attn2(model):
159
+ def recursive_find_module(name, module):
160
+ if not "up_blocks" in name and not "down_blocks" in name and not "mid_block" in name: return
161
+ elif "resnets" in name: return
162
+ if hasattr(module, "attn2"):
163
+ setattr(module, "attn2", None)
164
+ setattr(module, "norm2", None)
165
+ return
166
+ for sub_name, sub_module in module.named_children():
167
+ recursive_find_module(f"{name}.{sub_name}", sub_module)
168
+
169
+ for name, module in model.named_children():
170
+ recursive_find_module(name, module)
171
+
172
+
173
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
174
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
175
+ """
176
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
177
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
178
+ """
179
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
180
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
181
+ # rescale the results from guidance (fixes overexposure)
182
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
183
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
184
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
185
+ return noise_cfg
186
+
187
+
188
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
189
+ def retrieve_timesteps(
190
+ scheduler,
191
+ num_inference_steps: Optional[int] = None,
192
+ device: Optional[Union[str, torch.device]] = None,
193
+ timesteps: Optional[List[int]] = None,
194
+ **kwargs,
195
+ ):
196
+ """
197
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
198
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
199
+ Args:
200
+ scheduler (`SchedulerMixin`):
201
+ The scheduler to get timesteps from.
202
+ num_inference_steps (`int`):
203
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
204
+ must be `None`.
205
+ device (`str` or `torch.device`, *optional*):
206
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
207
+ timesteps (`List[int]`, *optional*):
208
+ Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
209
+ timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
210
+ must be `None`.
211
+ Returns:
212
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
213
+ second element is the number of inference steps.
214
+ """
215
+ if timesteps is not None:
216
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
217
+ if not accepts_timesteps:
218
+ raise ValueError(
219
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
220
+ f" timestep schedules. Please check whether you are using the correct scheduler."
221
+ )
222
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
223
+ timesteps = scheduler.timesteps
224
+ num_inference_steps = len(timesteps)
225
+ else:
226
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
227
+ timesteps = scheduler.timesteps
228
+ return timesteps, num_inference_steps
229
+
230
+
231
+ class InstantIRPipeline(
232
+ DiffusionPipeline,
233
+ StableDiffusionMixin,
234
+ TextualInversionLoaderMixin,
235
+ StableDiffusionXLLoraLoaderMixin,
236
+ IPAdapterMixin,
237
+ FromSingleFileMixin,
238
+ ):
239
+ r"""
240
+ Pipeline for text-to-image generation using Stable Diffusion XL with ControlNet guidance.
241
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
242
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
243
+ The pipeline also inherits the following loading methods:
244
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
245
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
246
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
247
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
248
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
249
+ Args:
250
+ vae ([`AutoencoderKL`]):
251
+ Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
252
+ text_encoder ([`~transformers.CLIPTextModel`]):
253
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
254
+ text_encoder_2 ([`~transformers.CLIPTextModelWithProjection`]):
255
+ Second frozen text-encoder
256
+ ([laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)).
257
+ tokenizer ([`~transformers.CLIPTokenizer`]):
258
+ A `CLIPTokenizer` to tokenize text.
259
+ tokenizer_2 ([`~transformers.CLIPTokenizer`]):
260
+ A `CLIPTokenizer` to tokenize text.
261
+ unet ([`UNet2DConditionModel`]):
262
+ A `UNet2DConditionModel` to denoise the encoded image latents.
263
+ controlnet ([`ControlNetModel`] or `List[ControlNetModel]`):
264
+ Provides additional conditioning to the `unet` during the denoising process. If you set multiple
265
+ ControlNets as a list, the outputs from each ControlNet are added together to create one combined
266
+ additional conditioning.
267
+ scheduler ([`SchedulerMixin`]):
268
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
269
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
270
+ force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"True"`):
271
+ Whether the negative prompt embeddings should always be set to 0. Also see the config of
272
+ `stabilityai/stable-diffusion-xl-base-1-0`.
273
+ add_watermarker (`bool`, *optional*):
274
+ Whether to use the [invisible_watermark](https://github.com/ShieldMnt/invisible-watermark/) library to
275
+ watermark output images. If not defined, it defaults to `True` if the package is installed; otherwise no
276
+ watermarker is used.
277
+ """
278
+
279
+ # leave controlnet out on purpose because it iterates with unet
280
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->image_encoder->unet->vae"
281
+ _optional_components = [
282
+ "tokenizer",
283
+ "tokenizer_2",
284
+ "text_encoder",
285
+ "text_encoder_2",
286
+ "feature_extractor",
287
+ "image_encoder",
288
+ ]
289
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
290
+
291
+ def __init__(
292
+ self,
293
+ vae: AutoencoderKL,
294
+ text_encoder: CLIPTextModel,
295
+ text_encoder_2: CLIPTextModelWithProjection,
296
+ tokenizer: CLIPTokenizer,
297
+ tokenizer_2: CLIPTokenizer,
298
+ unet: UNet2DConditionModel,
299
+ scheduler: KarrasDiffusionSchedulers,
300
+ aggregator: Aggregator = None,
301
+ force_zeros_for_empty_prompt: bool = True,
302
+ add_watermarker: Optional[bool] = None,
303
+ feature_extractor: CLIPImageProcessor = None,
304
+ image_encoder: CLIPVisionModelWithProjection = None,
305
+ ):
306
+ super().__init__()
307
+
308
+ if aggregator is None:
309
+ aggregator = Aggregator.from_unet(unet)
310
+ remove_attn2(aggregator)
311
+
312
+ self.register_modules(
313
+ vae=vae,
314
+ text_encoder=text_encoder,
315
+ text_encoder_2=text_encoder_2,
316
+ tokenizer=tokenizer,
317
+ tokenizer_2=tokenizer_2,
318
+ unet=unet,
319
+ aggregator=aggregator,
320
+ scheduler=scheduler,
321
+ feature_extractor=feature_extractor,
322
+ image_encoder=image_encoder,
323
+ )
324
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
325
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True)
326
+ self.control_image_processor = VaeImageProcessor(
327
+ vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True, do_normalize=True
328
+ )
329
+ add_watermarker = add_watermarker if add_watermarker is not None else is_invisible_watermark_available()
330
+
331
+ if add_watermarker:
332
+ self.watermark = StableDiffusionXLWatermarker()
333
+ else:
334
+ self.watermark = None
335
+
336
+ self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
337
+
338
+ def prepare_previewers(self, previewer_lora_path: str, use_lcm=False):
339
+ if use_lcm:
340
+ lora_state_dict, alpha_dict = self.lora_state_dict(
341
+ previewer_lora_path,
342
+ )
343
+ else:
344
+ lora_state_dict, alpha_dict = self.lora_state_dict(
345
+ previewer_lora_path,
346
+ weight_name="previewer_lora_weights.bin"
347
+ )
348
+ unet_state_dict = {
349
+ f'{k.replace("unet.", "")}': v for k, v in lora_state_dict.items() if k.startswith("unet.")
350
+ }
351
+ unet_state_dict = convert_unet_state_dict_to_peft(unet_state_dict)
352
+ lora_state_dict = dict()
353
+ for k, v in unet_state_dict.items():
354
+ if "ip" in k:
355
+ k = k.replace("attn2", "attn2.processor")
356
+ lora_state_dict[k] = v
357
+ else:
358
+ lora_state_dict[k] = v
359
+ if alpha_dict:
360
+ lora_alpha = next(iter(alpha_dict.values()))
361
+ else:
362
+ lora_alpha = 1
363
+ logger.info(f"use lora alpha {lora_alpha}")
364
+ lora_config = LoraConfig(
365
+ r=64,
366
+ target_modules=LCM_LORA_MODULES if use_lcm else PREVIEWER_LORA_MODULES,
367
+ lora_alpha=lora_alpha,
368
+ lora_dropout=0.0,
369
+ )
370
+
371
+ adapter_name = "lcm" if use_lcm else "previewer"
372
+ self.unet.add_adapter(lora_config, adapter_name)
373
+ incompatible_keys = set_peft_model_state_dict(self.unet, lora_state_dict, adapter_name=adapter_name)
374
+ if incompatible_keys is not None:
375
+ # check only for unexpected keys
376
+ unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None)
377
+ missing_keys = getattr(incompatible_keys, "missing_keys", None)
378
+ if unexpected_keys:
379
+ raise ValueError(
380
+ f"Loading adapter weights from state_dict led to unexpected keys not found in the model: "
381
+ f" {unexpected_keys}. "
382
+ )
383
+ self.unet.disable_adapters()
384
+
385
+ return lora_alpha
386
+
387
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.encode_prompt
388
+ def encode_prompt(
389
+ self,
390
+ prompt: str,
391
+ prompt_2: Optional[str] = None,
392
+ device: Optional[torch.device] = None,
393
+ num_images_per_prompt: int = 1,
394
+ do_classifier_free_guidance: bool = True,
395
+ negative_prompt: Optional[str] = None,
396
+ negative_prompt_2: Optional[str] = None,
397
+ prompt_embeds: Optional[torch.FloatTensor] = None,
398
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
399
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
400
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
401
+ lora_scale: Optional[float] = None,
402
+ clip_skip: Optional[int] = None,
403
+ ):
404
+ r"""
405
+ Encodes the prompt into text encoder hidden states.
406
+ Args:
407
+ prompt (`str` or `List[str]`, *optional*):
408
+ prompt to be encoded
409
+ prompt_2 (`str` or `List[str]`, *optional*):
410
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
411
+ used in both text-encoders
412
+ device: (`torch.device`):
413
+ torch device
414
+ num_images_per_prompt (`int`):
415
+ number of images that should be generated per prompt
416
+ do_classifier_free_guidance (`bool`):
417
+ whether to use classifier free guidance or not
418
+ negative_prompt (`str` or `List[str]`, *optional*):
419
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
420
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
421
+ less than `1`).
422
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
423
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
424
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
425
+ prompt_embeds (`torch.FloatTensor`, *optional*):
426
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
427
+ provided, text embeddings will be generated from `prompt` input argument.
428
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
429
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
430
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
431
+ argument.
432
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
433
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
434
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
435
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
436
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
437
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
438
+ input argument.
439
+ lora_scale (`float`, *optional*):
440
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
441
+ clip_skip (`int`, *optional*):
442
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
443
+ the output of the pre-final layer will be used for computing the prompt embeddings.
444
+ """
445
+ device = device or self._execution_device
446
+
447
+ # set lora scale so that monkey patched LoRA
448
+ # function of text encoder can correctly access it
449
+ if lora_scale is not None and isinstance(self, StableDiffusionXLLoraLoaderMixin):
450
+ self._lora_scale = lora_scale
451
+
452
+ # dynamically adjust the LoRA scale
453
+ if self.text_encoder is not None:
454
+ if not USE_PEFT_BACKEND:
455
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
456
+ else:
457
+ scale_lora_layers(self.text_encoder, lora_scale)
458
+
459
+ if self.text_encoder_2 is not None:
460
+ if not USE_PEFT_BACKEND:
461
+ adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
462
+ else:
463
+ scale_lora_layers(self.text_encoder_2, lora_scale)
464
+
465
+ prompt = [prompt] if isinstance(prompt, str) else prompt
466
+
467
+ if prompt is not None:
468
+ batch_size = len(prompt)
469
+ else:
470
+ batch_size = prompt_embeds.shape[0]
471
+
472
+ # Define tokenizers and text encoders
473
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
474
+ text_encoders = (
475
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
476
+ )
477
+
478
+ if prompt_embeds is None:
479
+ prompt_2 = prompt_2 or prompt
480
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
481
+
482
+ # textual inversion: process multi-vector tokens if necessary
483
+ prompt_embeds_list = []
484
+ prompts = [prompt, prompt_2]
485
+ for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
486
+ if isinstance(self, TextualInversionLoaderMixin):
487
+ prompt = self.maybe_convert_prompt(prompt, tokenizer)
488
+
489
+ text_inputs = tokenizer(
490
+ prompt,
491
+ padding="max_length",
492
+ max_length=tokenizer.model_max_length,
493
+ truncation=True,
494
+ return_tensors="pt",
495
+ )
496
+
497
+ text_input_ids = text_inputs.input_ids
498
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
499
+
500
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
501
+ text_input_ids, untruncated_ids
502
+ ):
503
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
504
+ logger.warning(
505
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
506
+ f" {tokenizer.model_max_length} tokens: {removed_text}"
507
+ )
508
+
509
+ prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=True)
510
+
511
+ # We are only ALWAYS interested in the pooled output of the final text encoder
512
+ pooled_prompt_embeds = prompt_embeds[0]
513
+ if clip_skip is None:
514
+ prompt_embeds = prompt_embeds.hidden_states[-2]
515
+ else:
516
+ # "2" because SDXL always indexes from the penultimate layer.
517
+ prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
518
+
519
+ prompt_embeds_list.append(prompt_embeds)
520
+
521
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
522
+
523
+ # get unconditional embeddings for classifier free guidance
524
+ zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
525
+ if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
526
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
527
+ negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
528
+ elif do_classifier_free_guidance and negative_prompt_embeds is None:
529
+ negative_prompt = negative_prompt or ""
530
+ negative_prompt_2 = negative_prompt_2 or negative_prompt
531
+
532
+ # normalize str to list
533
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
534
+ negative_prompt_2 = (
535
+ batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
536
+ )
537
+
538
+ uncond_tokens: List[str]
539
+ if prompt is not None and type(prompt) is not type(negative_prompt):
540
+ raise TypeError(
541
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
542
+ f" {type(prompt)}."
543
+ )
544
+ elif batch_size != len(negative_prompt):
545
+ raise ValueError(
546
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
547
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
548
+ " the batch size of `prompt`."
549
+ )
550
+ else:
551
+ uncond_tokens = [negative_prompt, negative_prompt_2]
552
+
553
+ negative_prompt_embeds_list = []
554
+ for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
555
+ if isinstance(self, TextualInversionLoaderMixin):
556
+ negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
557
+
558
+ max_length = prompt_embeds.shape[1]
559
+ uncond_input = tokenizer(
560
+ negative_prompt,
561
+ padding="max_length",
562
+ max_length=max_length,
563
+ truncation=True,
564
+ return_tensors="pt",
565
+ )
566
+
567
+ negative_prompt_embeds = text_encoder(
568
+ uncond_input.input_ids.to(device),
569
+ output_hidden_states=True,
570
+ )
571
+ # We are only ALWAYS interested in the pooled output of the final text encoder
572
+ negative_pooled_prompt_embeds = negative_prompt_embeds[0]
573
+ negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
574
+
575
+ negative_prompt_embeds_list.append(negative_prompt_embeds)
576
+
577
+ negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
578
+
579
+ if self.text_encoder_2 is not None:
580
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
581
+ else:
582
+ prompt_embeds = prompt_embeds.to(dtype=self.unet.dtype, device=device)
583
+
584
+ bs_embed, seq_len, _ = prompt_embeds.shape
585
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
586
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
587
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
588
+
589
+ if do_classifier_free_guidance:
590
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
591
+ seq_len = negative_prompt_embeds.shape[1]
592
+
593
+ if self.text_encoder_2 is not None:
594
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
595
+ else:
596
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.unet.dtype, device=device)
597
+
598
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
599
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
600
+
601
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
602
+ bs_embed * num_images_per_prompt, -1
603
+ )
604
+ if do_classifier_free_guidance:
605
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
606
+ bs_embed * num_images_per_prompt, -1
607
+ )
608
+
609
+ if self.text_encoder is not None:
610
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
611
+ # Retrieve the original scale by scaling back the LoRA layers
612
+ unscale_lora_layers(self.text_encoder, lora_scale)
613
+
614
+ if self.text_encoder_2 is not None:
615
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
616
+ # Retrieve the original scale by scaling back the LoRA layers
617
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
618
+
619
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
620
+
621
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
622
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
623
+ dtype = next(self.image_encoder.parameters()).dtype
624
+
625
+ if not isinstance(image, torch.Tensor):
626
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
627
+
628
+ image = image.to(device=device, dtype=dtype)
629
+ if output_hidden_states:
630
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
631
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
632
+ uncond_image_enc_hidden_states = self.image_encoder(
633
+ torch.zeros_like(image), output_hidden_states=True
634
+ ).hidden_states[-2]
635
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
636
+ num_images_per_prompt, dim=0
637
+ )
638
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
639
+ else:
640
+ if isinstance(self.image_encoder, CLIPVisionModelWithProjection):
641
+ # CLIP image encoder.
642
+ image_embeds = self.image_encoder(image).image_embeds
643
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
644
+ uncond_image_embeds = torch.zeros_like(image_embeds)
645
+ else:
646
+ # DINO image encoder.
647
+ image_embeds = self.image_encoder(image).last_hidden_state
648
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
649
+ uncond_image_embeds = self.image_encoder(
650
+ torch.zeros_like(image)
651
+ ).last_hidden_state
652
+ uncond_image_embeds = uncond_image_embeds.repeat_interleave(
653
+ num_images_per_prompt, dim=0
654
+ )
655
+
656
+ return image_embeds, uncond_image_embeds
657
+
658
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
659
+ def prepare_ip_adapter_image_embeds(
660
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
661
+ ):
662
+ if ip_adapter_image_embeds is None:
663
+ if not isinstance(ip_adapter_image, list):
664
+ ip_adapter_image = [ip_adapter_image]
665
+
666
+ if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
667
+ if isinstance(ip_adapter_image[0], list):
668
+ raise ValueError(
669
+ f"`ip_adapter_image` must have same length as the number of IP Adapters. Got {len(ip_adapter_image)} images and {len(self.unet.encoder_hid_proj.image_projection_layers)} IP Adapters."
670
+ )
671
+ else:
672
+ logger.warning(
673
+ f"Got {len(ip_adapter_image)} images for {len(self.unet.encoder_hid_proj.image_projection_layers)} IP Adapters."
674
+ " By default, these images will be sent to each IP-Adapter. If this is not your use-case, please specify `ip_adapter_image` as a list of image-list, with"
675
+ f" length equals to the number of IP-Adapters."
676
+ )
677
+ ip_adapter_image = [ip_adapter_image] * len(self.unet.encoder_hid_proj.image_projection_layers)
678
+
679
+ image_embeds = []
680
+ for single_ip_adapter_image, image_proj_layer in zip(
681
+ ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
682
+ ):
683
+ output_hidden_state = isinstance(self.image_encoder, CLIPVisionModelWithProjection) and not isinstance(image_proj_layer, ImageProjection)
684
+ single_image_embeds, single_negative_image_embeds = self.encode_image(
685
+ single_ip_adapter_image, device, 1, output_hidden_state
686
+ )
687
+ single_image_embeds = torch.stack([single_image_embeds] * (num_images_per_prompt//single_image_embeds.shape[0]), dim=0)
688
+ single_negative_image_embeds = torch.stack(
689
+ [single_negative_image_embeds] * (num_images_per_prompt//single_negative_image_embeds.shape[0]), dim=0
690
+ )
691
+
692
+ if do_classifier_free_guidance:
693
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds])
694
+ single_image_embeds = single_image_embeds.to(device)
695
+
696
+ image_embeds.append(single_image_embeds)
697
+ else:
698
+ repeat_dims = [1]
699
+ image_embeds = []
700
+ for single_image_embeds in ip_adapter_image_embeds:
701
+ if do_classifier_free_guidance:
702
+ single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
703
+ single_image_embeds = single_image_embeds.repeat(
704
+ num_images_per_prompt, *(repeat_dims * len(single_image_embeds.shape[1:]))
705
+ )
706
+ single_negative_image_embeds = single_negative_image_embeds.repeat(
707
+ num_images_per_prompt, *(repeat_dims * len(single_negative_image_embeds.shape[1:]))
708
+ )
709
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds])
710
+ else:
711
+ single_image_embeds = single_image_embeds.repeat(
712
+ num_images_per_prompt, *(repeat_dims * len(single_image_embeds.shape[1:]))
713
+ )
714
+ image_embeds.append(single_image_embeds)
715
+
716
+ return image_embeds
717
+
718
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
719
+ def prepare_extra_step_kwargs(self, generator, eta):
720
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
721
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
722
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
723
+ # and should be between [0, 1]
724
+
725
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
726
+ extra_step_kwargs = {}
727
+ if accepts_eta:
728
+ extra_step_kwargs["eta"] = eta
729
+
730
+ # check if the scheduler accepts generator
731
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
732
+ if accepts_generator:
733
+ extra_step_kwargs["generator"] = generator
734
+ return extra_step_kwargs
735
+
736
+ def check_inputs(
737
+ self,
738
+ prompt,
739
+ prompt_2,
740
+ image,
741
+ callback_steps,
742
+ negative_prompt=None,
743
+ negative_prompt_2=None,
744
+ prompt_embeds=None,
745
+ negative_prompt_embeds=None,
746
+ pooled_prompt_embeds=None,
747
+ ip_adapter_image=None,
748
+ ip_adapter_image_embeds=None,
749
+ negative_pooled_prompt_embeds=None,
750
+ controlnet_conditioning_scale=1.0,
751
+ control_guidance_start=0.0,
752
+ control_guidance_end=1.0,
753
+ callback_on_step_end_tensor_inputs=None,
754
+ ):
755
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
756
+ raise ValueError(
757
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
758
+ f" {type(callback_steps)}."
759
+ )
760
+
761
+ if callback_on_step_end_tensor_inputs is not None and not all(
762
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
763
+ ):
764
+ raise ValueError(
765
+ 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]}"
766
+ )
767
+
768
+ if prompt is not None and prompt_embeds is not None:
769
+ raise ValueError(
770
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
771
+ " only forward one of the two."
772
+ )
773
+ elif prompt_2 is not None and prompt_embeds is not None:
774
+ raise ValueError(
775
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
776
+ " only forward one of the two."
777
+ )
778
+ elif prompt is None and prompt_embeds is None:
779
+ raise ValueError(
780
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
781
+ )
782
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
783
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
784
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
785
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
786
+
787
+ if negative_prompt is not None and negative_prompt_embeds is not None:
788
+ raise ValueError(
789
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
790
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
791
+ )
792
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
793
+ raise ValueError(
794
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
795
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
796
+ )
797
+
798
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
799
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
800
+ raise ValueError(
801
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
802
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
803
+ f" {negative_prompt_embeds.shape}."
804
+ )
805
+
806
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
807
+ raise ValueError(
808
+ "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`."
809
+ )
810
+
811
+ if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
812
+ raise ValueError(
813
+ "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`."
814
+ )
815
+
816
+ # Check `image`
817
+ is_compiled = hasattr(F, "scaled_dot_product_attention") and isinstance(
818
+ self.aggregator, torch._dynamo.eval_frame.OptimizedModule
819
+ )
820
+ if (
821
+ isinstance(self.aggregator, Aggregator)
822
+ or is_compiled
823
+ and isinstance(self.aggregator._orig_mod, Aggregator)
824
+ ):
825
+ self.check_image(image, prompt, prompt_embeds)
826
+ else:
827
+ assert False
828
+
829
+ if control_guidance_start >= control_guidance_end:
830
+ raise ValueError(
831
+ f"control guidance start: {control_guidance_start} cannot be larger or equal to control guidance end: {control_guidance_end}."
832
+ )
833
+ if control_guidance_start < 0.0:
834
+ raise ValueError(f"control guidance start: {control_guidance_start} can't be smaller than 0.")
835
+ if control_guidance_end > 1.0:
836
+ raise ValueError(f"control guidance end: {control_guidance_end} can't be larger than 1.0.")
837
+
838
+ if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
839
+ raise ValueError(
840
+ "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
841
+ )
842
+
843
+ if ip_adapter_image_embeds is not None:
844
+ if not isinstance(ip_adapter_image_embeds, list):
845
+ raise ValueError(
846
+ f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
847
+ )
848
+ elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
849
+ raise ValueError(
850
+ f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
851
+ )
852
+
853
+ # Copied from diffusers.pipelines.controlnet.pipeline_controlnet.StableDiffusionControlNetPipeline.check_image
854
+ def check_image(self, image, prompt, prompt_embeds):
855
+ image_is_pil = isinstance(image, PIL.Image.Image)
856
+ image_is_tensor = isinstance(image, torch.Tensor)
857
+ image_is_np = isinstance(image, np.ndarray)
858
+ image_is_pil_list = isinstance(image, list) and isinstance(image[0], PIL.Image.Image)
859
+ image_is_tensor_list = isinstance(image, list) and isinstance(image[0], torch.Tensor)
860
+ image_is_np_list = isinstance(image, list) and isinstance(image[0], np.ndarray)
861
+
862
+ if (
863
+ not image_is_pil
864
+ and not image_is_tensor
865
+ and not image_is_np
866
+ and not image_is_pil_list
867
+ and not image_is_tensor_list
868
+ and not image_is_np_list
869
+ ):
870
+ raise TypeError(
871
+ f"image must be passed and be one of PIL image, numpy array, torch tensor, list of PIL images, list of numpy arrays or list of torch tensors, but is {type(image)}"
872
+ )
873
+
874
+ if image_is_pil:
875
+ image_batch_size = 1
876
+ else:
877
+ image_batch_size = len(image)
878
+
879
+ if prompt is not None and isinstance(prompt, str):
880
+ prompt_batch_size = 1
881
+ elif prompt is not None and isinstance(prompt, list):
882
+ prompt_batch_size = len(prompt)
883
+ elif prompt_embeds is not None:
884
+ prompt_batch_size = prompt_embeds.shape[0]
885
+
886
+ if image_batch_size != 1 and image_batch_size != prompt_batch_size:
887
+ raise ValueError(
888
+ f"If image batch size is not 1, image batch size must be same as prompt batch size. image batch size: {image_batch_size}, prompt batch size: {prompt_batch_size}"
889
+ )
890
+
891
+ # Copied from diffusers.pipelines.controlnet.pipeline_controlnet.StableDiffusionControlNetPipeline.prepare_image
892
+ def prepare_image(
893
+ self,
894
+ image,
895
+ width,
896
+ height,
897
+ batch_size,
898
+ num_images_per_prompt,
899
+ device,
900
+ dtype,
901
+ do_classifier_free_guidance=False,
902
+ ):
903
+ image = self.control_image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32)
904
+ image_batch_size = image.shape[0]
905
+
906
+ if image_batch_size == 1:
907
+ repeat_by = batch_size
908
+ else:
909
+ # image batch size is the same as prompt batch size
910
+ repeat_by = num_images_per_prompt
911
+
912
+ image = image.repeat_interleave(repeat_by, dim=0)
913
+
914
+ image = image.to(device=device, dtype=dtype)
915
+
916
+ return image
917
+
918
+ @torch.no_grad()
919
+ def init_latents(self, latents, generator, timestep):
920
+ noise = torch.randn(latents.shape, generator=generator, device=self.vae.device, dtype=self.vae.dtype, layout=torch.strided)
921
+ bsz = latents.shape[0]
922
+ print(f"init latent at {timestep}")
923
+ timestep = torch.tensor([timestep]*bsz, device=self.vae.device)
924
+ # Note that the latents will be scaled aleady by scheduler.add_noise
925
+ latents = self.scheduler.add_noise(latents, noise, timestep)
926
+ return latents
927
+
928
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
929
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
930
+ shape = (
931
+ batch_size,
932
+ num_channels_latents,
933
+ int(height) // self.vae_scale_factor,
934
+ int(width) // self.vae_scale_factor,
935
+ )
936
+ if isinstance(generator, list) and len(generator) != batch_size:
937
+ raise ValueError(
938
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
939
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
940
+ )
941
+
942
+ if latents is None:
943
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
944
+ else:
945
+ latents = latents.to(device)
946
+
947
+ # scale the initial noise by the standard deviation required by the scheduler
948
+ latents = latents * self.scheduler.init_noise_sigma
949
+ return latents
950
+
951
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline._get_add_time_ids
952
+ def _get_add_time_ids(
953
+ self, original_size, crops_coords_top_left, target_size, dtype, text_encoder_projection_dim=None
954
+ ):
955
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
956
+
957
+ passed_add_embed_dim = (
958
+ self.unet.config.addition_time_embed_dim * len(add_time_ids) + text_encoder_projection_dim
959
+ )
960
+ expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
961
+
962
+ if expected_add_embed_dim != passed_add_embed_dim:
963
+ raise ValueError(
964
+ 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`."
965
+ )
966
+
967
+ add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
968
+ return add_time_ids
969
+
970
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.StableDiffusionUpscalePipeline.upcast_vae
971
+ def upcast_vae(self):
972
+ dtype = self.vae.dtype
973
+ self.vae.to(dtype=torch.float32)
974
+ use_torch_2_0_or_xformers = isinstance(
975
+ self.vae.decoder.mid_block.attentions[0].processor,
976
+ (
977
+ AttnProcessor2_0,
978
+ XFormersAttnProcessor,
979
+ LoRAXFormersAttnProcessor,
980
+ LoRAAttnProcessor2_0,
981
+ ),
982
+ )
983
+ # if xformers or torch_2_0 is used attention block does not need
984
+ # to be in float32 which can save lots of memory
985
+ if use_torch_2_0_or_xformers:
986
+ self.vae.post_quant_conv.to(dtype)
987
+ self.vae.decoder.conv_in.to(dtype)
988
+ self.vae.decoder.mid_block.to(dtype)
989
+
990
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
991
+ def get_guidance_scale_embedding(
992
+ self, w: torch.Tensor, embedding_dim: int = 512, dtype: torch.dtype = torch.float32
993
+ ) -> torch.FloatTensor:
994
+ """
995
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
996
+ Args:
997
+ w (`torch.Tensor`):
998
+ Generate embedding vectors with a specified guidance scale to subsequently enrich timestep embeddings.
999
+ embedding_dim (`int`, *optional*, defaults to 512):
1000
+ Dimension of the embeddings to generate.
1001
+ dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
1002
+ Data type of the generated embeddings.
1003
+ Returns:
1004
+ `torch.FloatTensor`: Embedding vectors with shape `(len(w), embedding_dim)`.
1005
+ """
1006
+ assert len(w.shape) == 1
1007
+ w = w * 1000.0
1008
+
1009
+ half_dim = embedding_dim // 2
1010
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
1011
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
1012
+ emb = w.to(dtype)[:, None] * emb[None, :]
1013
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
1014
+ if embedding_dim % 2 == 1: # zero pad
1015
+ emb = torch.nn.functional.pad(emb, (0, 1))
1016
+ assert emb.shape == (w.shape[0], embedding_dim)
1017
+ return emb
1018
+
1019
+ @property
1020
+ def guidance_scale(self):
1021
+ return self._guidance_scale
1022
+
1023
+ @property
1024
+ def guidance_rescale(self):
1025
+ return self._guidance_rescale
1026
+
1027
+ @property
1028
+ def clip_skip(self):
1029
+ return self._clip_skip
1030
+
1031
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
1032
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
1033
+ # corresponds to doing no classifier free guidance.
1034
+ @property
1035
+ def do_classifier_free_guidance(self):
1036
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
1037
+
1038
+ @property
1039
+ def cross_attention_kwargs(self):
1040
+ return self._cross_attention_kwargs
1041
+
1042
+ @property
1043
+ def denoising_end(self):
1044
+ return self._denoising_end
1045
+
1046
+ @property
1047
+ def num_timesteps(self):
1048
+ return self._num_timesteps
1049
+
1050
+ @torch.no_grad()
1051
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
1052
+ def __call__(
1053
+ self,
1054
+ prompt: Union[str, List[str]] = None,
1055
+ prompt_2: Optional[Union[str, List[str]]] = None,
1056
+ image: PipelineImageInput = None,
1057
+ height: Optional[int] = None,
1058
+ width: Optional[int] = None,
1059
+ num_inference_steps: int = 30,
1060
+ timesteps: List[int] = None,
1061
+ denoising_end: Optional[float] = None,
1062
+ guidance_scale: float = 7.0,
1063
+ negative_prompt: Optional[Union[str, List[str]]] = None,
1064
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
1065
+ num_images_per_prompt: Optional[int] = 1,
1066
+ eta: float = 0.0,
1067
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
1068
+ latents: Optional[torch.FloatTensor] = None,
1069
+ prompt_embeds: Optional[torch.FloatTensor] = None,
1070
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
1071
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
1072
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
1073
+ ip_adapter_image: Optional[PipelineImageInput] = None,
1074
+ ip_adapter_image_embeds: Optional[List[torch.FloatTensor]] = None,
1075
+ output_type: Optional[str] = "pil",
1076
+ return_dict: bool = True,
1077
+ save_preview_row: bool = False,
1078
+ init_latents_with_lq: bool = True,
1079
+ multistep_restore: bool = False,
1080
+ adastep_restore: bool = False,
1081
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1082
+ guidance_rescale: float = 0.0,
1083
+ controlnet_conditioning_scale: float = 1.0,
1084
+ control_guidance_start: float = 0.0,
1085
+ control_guidance_end: float = 1.0,
1086
+ preview_start: float = 0.0,
1087
+ preview_end: float = 1.0,
1088
+ original_size: Tuple[int, int] = None,
1089
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
1090
+ target_size: Tuple[int, int] = None,
1091
+ negative_original_size: Optional[Tuple[int, int]] = None,
1092
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
1093
+ negative_target_size: Optional[Tuple[int, int]] = None,
1094
+ clip_skip: Optional[int] = None,
1095
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
1096
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
1097
+ previewer_scheduler: KarrasDiffusionSchedulers = None,
1098
+ reference_latents: Optional[torch.FloatTensor] = None,
1099
+ **kwargs,
1100
+ ):
1101
+ r"""
1102
+ The call function to the pipeline for generation.
1103
+ Args:
1104
+ prompt (`str` or `List[str]`, *optional*):
1105
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
1106
+ prompt_2 (`str` or `List[str]`, *optional*):
1107
+ The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
1108
+ used in both text-encoders.
1109
+ image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
1110
+ `List[List[torch.FloatTensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
1111
+ The ControlNet input condition to provide guidance to the `unet` for generation. If the type is
1112
+ specified as `torch.FloatTensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also be
1113
+ accepted as an image. The dimensions of the output image defaults to `image`'s dimensions. If height
1114
+ and/or width are passed, `image` is resized accordingly. If multiple ControlNets are specified in
1115
+ `init`, images must be passed as a list such that each element of the list can be correctly batched for
1116
+ input to a single ControlNet.
1117
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
1118
+ The height in pixels of the generated image. Anything below 512 pixels won't work well for
1119
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
1120
+ and checkpoints that are not specifically fine-tuned on low resolutions.
1121
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
1122
+ The width in pixels of the generated image. Anything below 512 pixels won't work well for
1123
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
1124
+ and checkpoints that are not specifically fine-tuned on low resolutions.
1125
+ num_inference_steps (`int`, *optional*, defaults to 50):
1126
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
1127
+ expense of slower inference.
1128
+ timesteps (`List[int]`, *optional*):
1129
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
1130
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
1131
+ passed will be used. Must be in descending order.
1132
+ denoising_end (`float`, *optional*):
1133
+ When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
1134
+ completed before it is intentionally prematurely terminated. As a result, the returned sample will
1135
+ still retain a substantial amount of noise as determined by the discrete timesteps selected by the
1136
+ scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
1137
+ "Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
1138
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)
1139
+ guidance_scale (`float`, *optional*, defaults to 5.0):
1140
+ A higher guidance scale value encourages the model to generate images closely linked to the text
1141
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
1142
+ negative_prompt (`str` or `List[str]`, *optional*):
1143
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
1144
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
1145
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
1146
+ The prompt or prompts to guide what to not include in image generation. This is sent to `tokenizer_2`
1147
+ and `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders.
1148
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1149
+ The number of images to generate per prompt.
1150
+ eta (`float`, *optional*, defaults to 0.0):
1151
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
1152
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
1153
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
1154
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
1155
+ generation deterministic.
1156
+ latents (`torch.FloatTensor`, *optional*):
1157
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
1158
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
1159
+ tensor is generated by sampling using the supplied random `generator`.
1160
+ prompt_embeds (`torch.FloatTensor`, *optional*):
1161
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
1162
+ provided, text embeddings are generated from the `prompt` input argument.
1163
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
1164
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
1165
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
1166
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
1167
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
1168
+ not provided, pooled text embeddings are generated from `prompt` input argument.
1169
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
1170
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs (prompt
1171
+ weighting). If not provided, pooled `negative_prompt_embeds` are generated from `negative_prompt` input
1172
+ argument.
1173
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
1174
+ ip_adapter_image_embeds (`List[torch.FloatTensor]`, *optional*):
1175
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
1176
+ IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should
1177
+ contain the negative image embedding if `do_classifier_free_guidance` is set to `True`. If not
1178
+ provided, embeddings are computed from the `ip_adapter_image` input argument.
1179
+ output_type (`str`, *optional*, defaults to `"pil"`):
1180
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
1181
+ return_dict (`bool`, *optional*, defaults to `True`):
1182
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
1183
+ plain tuple.
1184
+ cross_attention_kwargs (`dict`, *optional*):
1185
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
1186
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1187
+ controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
1188
+ The outputs of the ControlNet are multiplied by `controlnet_conditioning_scale` before they are added
1189
+ to the residual in the original `unet`. If multiple ControlNets are specified in `init`, you can set
1190
+ the corresponding scale as a list.
1191
+ control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0):
1192
+ The percentage of total steps at which the ControlNet starts applying.
1193
+ control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0):
1194
+ The percentage of total steps at which the ControlNet stops applying.
1195
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1196
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
1197
+ `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
1198
+ explained in section 2.2 of
1199
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1200
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
1201
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
1202
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
1203
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
1204
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1205
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1206
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
1207
+ not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
1208
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1209
+ negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1210
+ To negatively condition the generation process based on a specific image resolution. Part of SDXL's
1211
+ micro-conditioning as explained in section 2.2 of
1212
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1213
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1214
+ negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
1215
+ To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
1216
+ micro-conditioning as explained in section 2.2 of
1217
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1218
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1219
+ negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1220
+ To negatively condition the generation process based on a target image resolution. It should be as same
1221
+ as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
1222
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1223
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1224
+ clip_skip (`int`, *optional*):
1225
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
1226
+ the output of the pre-final layer will be used for computing the prompt embeddings.
1227
+ callback_on_step_end (`Callable`, *optional*):
1228
+ A function that calls at the end of each denoising steps during the inference. The function is called
1229
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
1230
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
1231
+ `callback_on_step_end_tensor_inputs`.
1232
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
1233
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
1234
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
1235
+ `._callback_tensor_inputs` attribute of your pipeline class.
1236
+ Examples:
1237
+ Returns:
1238
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
1239
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
1240
+ otherwise a `tuple` is returned containing the output images.
1241
+ """
1242
+
1243
+ callback = kwargs.pop("callback", None)
1244
+ callback_steps = kwargs.pop("callback_steps", None)
1245
+
1246
+ if callback is not None:
1247
+ deprecate(
1248
+ "callback",
1249
+ "1.0.0",
1250
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
1251
+ )
1252
+ if callback_steps is not None:
1253
+ deprecate(
1254
+ "callback_steps",
1255
+ "1.0.0",
1256
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
1257
+ )
1258
+
1259
+ aggregator = self.aggregator._orig_mod if is_compiled_module(self.aggregator) else self.aggregator
1260
+ if not isinstance(ip_adapter_image, list):
1261
+ ip_adapter_image = [ip_adapter_image] if ip_adapter_image is not None else [image]
1262
+
1263
+ # 1. Check inputs. Raise error if not correct
1264
+ self.check_inputs(
1265
+ prompt,
1266
+ prompt_2,
1267
+ image,
1268
+ callback_steps,
1269
+ negative_prompt,
1270
+ negative_prompt_2,
1271
+ prompt_embeds,
1272
+ negative_prompt_embeds,
1273
+ pooled_prompt_embeds,
1274
+ ip_adapter_image,
1275
+ ip_adapter_image_embeds,
1276
+ negative_pooled_prompt_embeds,
1277
+ controlnet_conditioning_scale,
1278
+ control_guidance_start,
1279
+ control_guidance_end,
1280
+ callback_on_step_end_tensor_inputs,
1281
+ )
1282
+
1283
+ self._guidance_scale = guidance_scale
1284
+ self._guidance_rescale = guidance_rescale
1285
+ self._clip_skip = clip_skip
1286
+ self._cross_attention_kwargs = cross_attention_kwargs
1287
+ self._denoising_end = denoising_end
1288
+
1289
+ # 2. Define call parameters
1290
+ if prompt is not None and isinstance(prompt, str):
1291
+ if not isinstance(image, PIL.Image.Image):
1292
+ batch_size = len(image)
1293
+ else:
1294
+ batch_size = 1
1295
+ prompt = [prompt] * batch_size
1296
+ elif prompt is not None and isinstance(prompt, list):
1297
+ batch_size = len(prompt)
1298
+ assert batch_size == len(image) or (isinstance(image, PIL.Image.Image) or len(image) == 1)
1299
+ else:
1300
+ batch_size = prompt_embeds.shape[0]
1301
+ assert batch_size == len(image) or (isinstance(image, PIL.Image.Image) or len(image) == 1)
1302
+
1303
+ device = self._execution_device
1304
+
1305
+ # 3.1 Encode input prompt
1306
+ text_encoder_lora_scale = (
1307
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
1308
+ )
1309
+ (
1310
+ prompt_embeds,
1311
+ negative_prompt_embeds,
1312
+ pooled_prompt_embeds,
1313
+ negative_pooled_prompt_embeds,
1314
+ ) = self.encode_prompt(
1315
+ prompt=prompt,
1316
+ prompt_2=prompt_2,
1317
+ device=device,
1318
+ num_images_per_prompt=num_images_per_prompt,
1319
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1320
+ negative_prompt=negative_prompt,
1321
+ negative_prompt_2=negative_prompt_2,
1322
+ prompt_embeds=prompt_embeds,
1323
+ negative_prompt_embeds=negative_prompt_embeds,
1324
+ pooled_prompt_embeds=pooled_prompt_embeds,
1325
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
1326
+ lora_scale=text_encoder_lora_scale,
1327
+ clip_skip=self.clip_skip,
1328
+ )
1329
+
1330
+ # 3.2 Encode ip_adapter_image
1331
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1332
+ image_embeds = self.prepare_ip_adapter_image_embeds(
1333
+ ip_adapter_image,
1334
+ ip_adapter_image_embeds,
1335
+ device,
1336
+ batch_size * num_images_per_prompt,
1337
+ self.do_classifier_free_guidance,
1338
+ )
1339
+
1340
+ # 4. Prepare image
1341
+ image = self.prepare_image(
1342
+ image=image,
1343
+ width=width,
1344
+ height=height,
1345
+ batch_size=batch_size * num_images_per_prompt,
1346
+ num_images_per_prompt=num_images_per_prompt,
1347
+ device=device,
1348
+ dtype=aggregator.dtype,
1349
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1350
+ )
1351
+ height, width = image.shape[-2:]
1352
+ if image.shape[1] != 4:
1353
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
1354
+ if needs_upcasting:
1355
+ image = image.float()
1356
+ self.vae.to(dtype=torch.float32)
1357
+ image = self.vae.encode(image).latent_dist.sample()
1358
+ image = image * self.vae.config.scaling_factor
1359
+ if needs_upcasting:
1360
+ self.vae.to(dtype=torch.float16)
1361
+ image = image.to(dtype=torch.float16)
1362
+ else:
1363
+ height = int(height * self.vae_scale_factor)
1364
+ width = int(width * self.vae_scale_factor)
1365
+
1366
+ # 5. Prepare timesteps
1367
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
1368
+
1369
+ # 6. Prepare latent variables
1370
+ if init_latents_with_lq:
1371
+ latents = self.init_latents(image, generator, timesteps[0])
1372
+ else:
1373
+ num_channels_latents = self.unet.config.in_channels
1374
+ latents = self.prepare_latents(
1375
+ batch_size * num_images_per_prompt,
1376
+ num_channels_latents,
1377
+ height,
1378
+ width,
1379
+ prompt_embeds.dtype,
1380
+ device,
1381
+ generator,
1382
+ latents,
1383
+ )
1384
+
1385
+ # 6.5 Optionally get Guidance Scale Embedding
1386
+ timestep_cond = None
1387
+ if self.unet.config.time_cond_proj_dim is not None:
1388
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
1389
+ timestep_cond = self.get_guidance_scale_embedding(
1390
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
1391
+ ).to(device=device, dtype=latents.dtype)
1392
+
1393
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1394
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1395
+
1396
+ # 7.1 Create tensor stating which controlnets to keep
1397
+ controlnet_keep = []
1398
+ previewing = []
1399
+ for i in range(len(timesteps)):
1400
+ keeps = 1.0 - float(i / len(timesteps) < control_guidance_start or (i + 1) / len(timesteps) > control_guidance_end)
1401
+ controlnet_keep.append(keeps)
1402
+ use_preview = 1.0 - float(i / len(timesteps) < preview_start or (i + 1) / len(timesteps) > preview_end)
1403
+ previewing.append(use_preview)
1404
+ if isinstance(controlnet_conditioning_scale, list):
1405
+ assert len(controlnet_conditioning_scale) == len(timesteps), f"{len(controlnet_conditioning_scale)} controlnet scales do not match number of sampling steps {len(timesteps)}"
1406
+ else:
1407
+ controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet_keep)
1408
+
1409
+ # 7.2 Prepare added time ids & embeddings
1410
+ original_size = original_size or (height, width)
1411
+ target_size = target_size or (height, width)
1412
+
1413
+ add_text_embeds = pooled_prompt_embeds
1414
+ if self.text_encoder_2 is None:
1415
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
1416
+ else:
1417
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
1418
+
1419
+ add_time_ids = self._get_add_time_ids(
1420
+ original_size,
1421
+ crops_coords_top_left,
1422
+ target_size,
1423
+ dtype=prompt_embeds.dtype,
1424
+ text_encoder_projection_dim=text_encoder_projection_dim,
1425
+ )
1426
+
1427
+ if negative_original_size is not None and negative_target_size is not None:
1428
+ negative_add_time_ids = self._get_add_time_ids(
1429
+ negative_original_size,
1430
+ negative_crops_coords_top_left,
1431
+ negative_target_size,
1432
+ dtype=prompt_embeds.dtype,
1433
+ text_encoder_projection_dim=text_encoder_projection_dim,
1434
+ )
1435
+ else:
1436
+ negative_add_time_ids = add_time_ids
1437
+
1438
+ if self.do_classifier_free_guidance:
1439
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
1440
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
1441
+ add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
1442
+ image = torch.cat([image] * 2, dim=0)
1443
+
1444
+ prompt_embeds = prompt_embeds.to(device)
1445
+ add_text_embeds = add_text_embeds.to(device)
1446
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
1447
+
1448
+ # 8. Denoising loop
1449
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
1450
+
1451
+ # 8.1 Apply denoising_end
1452
+ if (
1453
+ self.denoising_end is not None
1454
+ and isinstance(self.denoising_end, float)
1455
+ and self.denoising_end > 0
1456
+ and self.denoising_end < 1
1457
+ ):
1458
+ discrete_timestep_cutoff = int(
1459
+ round(
1460
+ self.scheduler.config.num_train_timesteps
1461
+ - (self.denoising_end * self.scheduler.config.num_train_timesteps)
1462
+ )
1463
+ )
1464
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
1465
+ timesteps = timesteps[:num_inference_steps]
1466
+
1467
+ is_unet_compiled = is_compiled_module(self.unet)
1468
+ is_aggregator_compiled = is_compiled_module(self.aggregator)
1469
+ is_torch_higher_equal_2_1 = is_torch_version(">=", "2.1")
1470
+ previewer_mean = torch.zeros_like(latents)
1471
+ unet_mean = torch.zeros_like(latents)
1472
+ preview_factor = torch.ones(
1473
+ (latents.shape[0], *((1,) * (len(latents.shape) - 1))), dtype=latents.dtype, device=latents.device
1474
+ )
1475
+
1476
+ self._num_timesteps = len(timesteps)
1477
+ preview_row = []
1478
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1479
+ for i, t in enumerate(timesteps):
1480
+ # Relevant thread:
1481
+ # https://dev-discuss.pytorch.org/t/cudagraphs-in-pytorch-2-0/1428
1482
+ if (is_unet_compiled and is_aggregator_compiled) and is_torch_higher_equal_2_1:
1483
+ torch._inductor.cudagraph_mark_step_begin()
1484
+ # expand the latents if we are doing classifier free guidance
1485
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1486
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1487
+ prev_t = t
1488
+ unet_model_input = latent_model_input
1489
+
1490
+ added_cond_kwargs = {
1491
+ "text_embeds": add_text_embeds,
1492
+ "time_ids": add_time_ids,
1493
+ "image_embeds": image_embeds
1494
+ }
1495
+ aggregator_added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
1496
+
1497
+ # prepare time_embeds in advance as adapter input
1498
+ cross_attention_t_emb = self.unet.get_time_embed(sample=latent_model_input, timestep=t)
1499
+ cross_attention_emb = self.unet.time_embedding(cross_attention_t_emb, timestep_cond)
1500
+ cross_attention_aug_emb = None
1501
+
1502
+ cross_attention_aug_emb = self.unet.get_aug_embed(
1503
+ emb=cross_attention_emb,
1504
+ encoder_hidden_states=prompt_embeds,
1505
+ added_cond_kwargs=added_cond_kwargs
1506
+ )
1507
+
1508
+ cross_attention_emb = cross_attention_emb + cross_attention_aug_emb if cross_attention_aug_emb is not None else cross_attention_emb
1509
+
1510
+ if self.unet.time_embed_act is not None:
1511
+ cross_attention_emb = self.unet.time_embed_act(cross_attention_emb)
1512
+
1513
+ current_cross_attention_kwargs = {"temb": cross_attention_emb}
1514
+ if cross_attention_kwargs is not None:
1515
+ for k,v in cross_attention_kwargs.items():
1516
+ current_cross_attention_kwargs[k] = v
1517
+ self._cross_attention_kwargs = current_cross_attention_kwargs
1518
+
1519
+ # adaptive restoration factors
1520
+ adaRes_scale = preview_factor.to(latent_model_input.dtype).clamp(0.0, controlnet_conditioning_scale[i])
1521
+ cond_scale = adaRes_scale * controlnet_keep[i]
1522
+ cond_scale = torch.cat([cond_scale] * 2) if self.do_classifier_free_guidance else cond_scale
1523
+
1524
+ if (cond_scale>0.1).sum().item() > 0:
1525
+ if previewing[i] > 0:
1526
+ # preview with LCM
1527
+ self.unet.enable_adapters()
1528
+ preview_noise = self.unet(
1529
+ latent_model_input,
1530
+ t,
1531
+ encoder_hidden_states=prompt_embeds,
1532
+ timestep_cond=timestep_cond,
1533
+ cross_attention_kwargs=self.cross_attention_kwargs,
1534
+ added_cond_kwargs=added_cond_kwargs,
1535
+ return_dict=False,
1536
+ )[0]
1537
+ preview_latent = previewer_scheduler.step(
1538
+ preview_noise,
1539
+ t.to(dtype=torch.int64),
1540
+ # torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents,
1541
+ latent_model_input, # scaled latents here for compatibility
1542
+ return_dict=False
1543
+ )[0]
1544
+ self.unet.disable_adapters()
1545
+
1546
+ if self.do_classifier_free_guidance:
1547
+ preview_row.append(preview_latent.chunk(2)[1].to('cpu'))
1548
+ else:
1549
+ preview_row.append(preview_latent.to('cpu'))
1550
+ # Prepare 2nd order step.
1551
+ if multistep_restore and i+1 < len(timesteps):
1552
+ noise_preview = preview_noise.chunk(2)[1] if self.do_classifier_free_guidance else preview_noise
1553
+ first_step = self.scheduler.step(
1554
+ noise_preview, t, latents,
1555
+ **extra_step_kwargs, return_dict=True, step_forward=False
1556
+ )
1557
+ prev_t = timesteps[i + 1]
1558
+ unet_model_input = torch.cat([first_step.prev_sample] * 2) if self.do_classifier_free_guidance else first_step.prev_sample
1559
+ unet_model_input = self.scheduler.scale_model_input(unet_model_input, prev_t, heun_step=True)
1560
+
1561
+ elif reference_latents is not None:
1562
+ preview_latent = torch.cat([reference_latents] * 2) if self.do_classifier_free_guidance else reference_latents
1563
+ else:
1564
+ preview_latent = image
1565
+
1566
+ # Add fresh noise
1567
+ # preview_noise = torch.randn_like(preview_latent)
1568
+ # preview_latent = self.scheduler.add_noise(preview_latent, preview_noise, t)
1569
+
1570
+ preview_latent=preview_latent.to(dtype=next(aggregator.parameters()).dtype)
1571
+
1572
+ # Aggregator inference
1573
+ down_block_res_samples, mid_block_res_sample = aggregator(
1574
+ image,
1575
+ prev_t,
1576
+ encoder_hidden_states=prompt_embeds,
1577
+ controlnet_cond=preview_latent,
1578
+ # conditioning_scale=cond_scale,
1579
+ added_cond_kwargs=aggregator_added_cond_kwargs,
1580
+ return_dict=False,
1581
+ )
1582
+
1583
+ # aggregator features scaling
1584
+ down_block_res_samples = [sample*cond_scale for sample in down_block_res_samples]
1585
+ mid_block_res_sample = mid_block_res_sample*cond_scale
1586
+
1587
+ # predict the noise residual
1588
+ noise_pred = self.unet(
1589
+ unet_model_input,
1590
+ prev_t,
1591
+ encoder_hidden_states=prompt_embeds,
1592
+ timestep_cond=timestep_cond,
1593
+ cross_attention_kwargs=self.cross_attention_kwargs,
1594
+ down_block_additional_residuals=down_block_res_samples,
1595
+ mid_block_additional_residual=mid_block_res_sample,
1596
+ added_cond_kwargs=added_cond_kwargs,
1597
+ return_dict=False,
1598
+ )[0]
1599
+
1600
+ # perform guidance
1601
+ if self.do_classifier_free_guidance:
1602
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1603
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1604
+
1605
+ if self.do_classifier_free_guidance and self.guidance_rescale > 0.0:
1606
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1607
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale)
1608
+
1609
+ # compute the previous noisy sample x_t -> x_t-1
1610
+ latents_dtype = latents.dtype
1611
+ unet_step = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=True)
1612
+ latents = unet_step.prev_sample
1613
+
1614
+ # Update adaRes factors
1615
+ unet_pred_latent = unet_step.pred_original_sample
1616
+
1617
+ # Adaptive restoration.
1618
+ if adastep_restore:
1619
+ pred_x0_l2 = ((preview_latent[latents.shape[0]:].float()-unet_pred_latent.float())).pow(2).sum(dim=(1,2,3))
1620
+ previewer_l2 = ((preview_latent[latents.shape[0]:].float()-previewer_mean.float())).pow(2).sum(dim=(1,2,3))
1621
+ # unet_l2 = ((unet_pred_latent.float()-unet_mean.float())).pow(2).sum(dim=(1,2,3)).sqrt()
1622
+ # l2_error = (((preview_latent[latents.shape[0]:]-previewer_mean) - (unet_pred_latent-unet_mean))).pow(2).mean(dim=(1,2,3))
1623
+ # preview_error = torch.nn.functional.cosine_similarity(preview_latent[latents.shape[0]:].reshape(latents.shape[0], -1), unet_pred_latent.reshape(latents.shape[0],-1))
1624
+ previewer_mean = preview_latent[latents.shape[0]:]
1625
+ unet_mean = unet_pred_latent
1626
+ preview_factor = (pred_x0_l2 / previewer_l2).reshape(-1, 1, 1, 1)
1627
+
1628
+ if latents.dtype != latents_dtype:
1629
+ if torch.backends.mps.is_available():
1630
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1631
+ latents = latents.to(latents_dtype)
1632
+
1633
+ if callback_on_step_end is not None:
1634
+ callback_kwargs = {}
1635
+ for k in callback_on_step_end_tensor_inputs:
1636
+ callback_kwargs[k] = locals()[k]
1637
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1638
+
1639
+ latents = callback_outputs.pop("latents", latents)
1640
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1641
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1642
+
1643
+ # call the callback, if provided
1644
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1645
+ progress_bar.update()
1646
+ if callback is not None and i % callback_steps == 0:
1647
+ step_idx = i // getattr(self.scheduler, "order", 1)
1648
+ callback(step_idx, t, latents)
1649
+
1650
+ if not output_type == "latent":
1651
+ # make sure the VAE is in float32 mode, as it overflows in float16
1652
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
1653
+
1654
+ if needs_upcasting:
1655
+ self.upcast_vae()
1656
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1657
+
1658
+ # unscale/denormalize the latents
1659
+ # denormalize with the mean and std if available and not None
1660
+ has_latents_mean = hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None
1661
+ has_latents_std = hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None
1662
+ if has_latents_mean and has_latents_std:
1663
+ latents_mean = (
1664
+ torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1665
+ )
1666
+ latents_std = (
1667
+ torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1668
+ )
1669
+ latents = latents * latents_std / self.vae.config.scaling_factor + latents_mean
1670
+ else:
1671
+ latents = latents / self.vae.config.scaling_factor
1672
+
1673
+ image = self.vae.decode(latents, return_dict=False)[0]
1674
+
1675
+ # cast back to fp16 if needed
1676
+ if needs_upcasting:
1677
+ self.vae.to(dtype=torch.float16)
1678
+ else:
1679
+ image = latents
1680
+
1681
+ if not output_type == "latent":
1682
+ # apply watermark if available
1683
+ if self.watermark is not None:
1684
+ image = self.watermark.apply_watermark(image)
1685
+
1686
+ image = self.image_processor.postprocess(image, output_type=output_type)
1687
+
1688
+ if save_preview_row:
1689
+ preview_image_row = []
1690
+ if needs_upcasting:
1691
+ self.upcast_vae()
1692
+ for preview_latents in preview_row:
1693
+ preview_latents = preview_latents.to(device=self.device, dtype=next(iter(self.vae.post_quant_conv.parameters())).dtype)
1694
+ if has_latents_mean and has_latents_std:
1695
+ latents_mean = (
1696
+ torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1).to(preview_latents.device, preview_latents.dtype)
1697
+ )
1698
+ latents_std = (
1699
+ torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1).to(preview_latents.device, preview_latents.dtype)
1700
+ )
1701
+ preview_latents = preview_latents * latents_std / self.vae.config.scaling_factor + latents_mean
1702
+ else:
1703
+ preview_latents = preview_latents / self.vae.config.scaling_factor
1704
+
1705
+ preview_image = self.vae.decode(preview_latents, return_dict=False)[0]
1706
+ preview_image = self.image_processor.postprocess(preview_image, output_type=output_type)
1707
+ preview_image_row.append(preview_image)
1708
+
1709
+ # cast back to fp16 if needed
1710
+ if needs_upcasting:
1711
+ self.vae.to(dtype=torch.float16)
1712
+
1713
+ # Offload all models
1714
+ self.maybe_free_model_hooks()
1715
+
1716
+ if not return_dict:
1717
+ if save_preview_row:
1718
+ return (image, preview_image_row)
1719
+ return (image,)
1720
+
1721
+ return StableDiffusionXLPipelineOutput(images=image)