zhiweili commited on
Commit
8fda951
1 Parent(s): 7386f72

add realvxl_adapter

Browse files
app_base.py CHANGED
@@ -7,7 +7,6 @@ import numpy as np
7
  import cv2
8
 
9
  from PIL import Image
10
- from inversion_run_base import run as base_run
11
  from segment_utils import(
12
  segment_image,
13
  restore_result,
@@ -25,6 +24,7 @@ DEFAULT_CATEGORY = "face"
25
  device = "cuda" if torch.cuda.is_available() else "cpu"
26
 
27
  def create_demo() -> gr.Blocks:
 
28
  model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=32, upscale=4, act_type='prelu')
29
  model_path = 'realesr-general-x4v3.pth'
30
  half = True if torch.cuda.is_available() else False
 
7
  import cv2
8
 
9
  from PIL import Image
 
10
  from segment_utils import(
11
  segment_image,
12
  restore_result,
 
24
  device = "cuda" if torch.cuda.is_available() else "cpu"
25
 
26
  def create_demo() -> gr.Blocks:
27
+ from inversion_run_base import run as base_run
28
  model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=32, upscale=4, act_type='prelu')
29
  model_path = 'realesr-general-x4v3.pth'
30
  half = True if torch.cuda.is_available() else False
app_haircolor.py CHANGED
@@ -2,12 +2,10 @@ import spaces
2
  import gradio as gr
3
  import time
4
  import torch
5
- import os
6
  import numpy as np
7
  import cv2
8
 
9
  from PIL import Image
10
- from inversion_run_base import run as base_run
11
  from segment_utils import(
12
  segment_image,
13
  restore_result,
@@ -25,6 +23,7 @@ DEFAULT_CATEGORY = "hair"
25
  device = "cuda" if torch.cuda.is_available() else "cpu"
26
 
27
  def create_demo() -> gr.Blocks:
 
28
  model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=32, upscale=4, act_type='prelu')
29
  model_path = 'realesr-general-x4v3.pth'
30
  half = True if torch.cuda.is_available() else False
@@ -47,7 +46,7 @@ def create_demo() -> gr.Blocks:
47
  run_task_time = 0
48
  time_cost_str = ''
49
  run_task_time, time_cost_str = get_time_cost(run_task_time, time_cost_str)
50
- run_model = base_run
51
  res_image = run_model(
52
  input_image,
53
  input_image_prompt,
@@ -107,7 +106,7 @@ def create_demo() -> gr.Blocks:
107
  generate_size = gr.Number(label="Generate Size", value=512)
108
  mask_expansion = gr.Number(label="Mask Expansion", value=10, visible=True)
109
  mask_dilation = gr.Slider(minimum=0, maximum=10, value=2, step=1, label="Mask Dilation")
110
- adapter_weights = gr.Slider(minimum=0, maximum=1, value=0.5, step=0.1, label="Adapter Weights", visible=False)
111
  with gr.Column():
112
  seed = gr.Number(label="Seed", value=8)
113
  w1 = gr.Number(label="W1", value=2)
 
2
  import gradio as gr
3
  import time
4
  import torch
 
5
  import numpy as np
6
  import cv2
7
 
8
  from PIL import Image
 
9
  from segment_utils import(
10
  segment_image,
11
  restore_result,
 
23
  device = "cuda" if torch.cuda.is_available() else "cpu"
24
 
25
  def create_demo() -> gr.Blocks:
26
+ from inversion_run_realvxl_adapter import run as realvxl_run
27
  model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=32, upscale=4, act_type='prelu')
28
  model_path = 'realesr-general-x4v3.pth'
29
  half = True if torch.cuda.is_available() else False
 
46
  run_task_time = 0
47
  time_cost_str = ''
48
  run_task_time, time_cost_str = get_time_cost(run_task_time, time_cost_str)
49
+ run_model = realvxl_run
50
  res_image = run_model(
51
  input_image,
52
  input_image_prompt,
 
106
  generate_size = gr.Number(label="Generate Size", value=512)
107
  mask_expansion = gr.Number(label="Mask Expansion", value=10, visible=True)
108
  mask_dilation = gr.Slider(minimum=0, maximum=10, value=2, step=1, label="Mask Dilation")
109
+ adapter_weights = gr.Slider(minimum=0, maximum=1, value=0.5, step=0.1, label="Adapter Weights", visible=True)
110
  with gr.Column():
111
  seed = gr.Number(label="Seed", value=8)
112
  w1 = gr.Number(label="W1", value=2)
inversion_run_realvxl_adapter.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import os
3
+
4
+ from diffusers import (
5
+ DDPMScheduler,
6
+ DiffusionPipeline,
7
+ T2IAdapter,
8
+ MultiAdapter,
9
+ )
10
+ from controlnet_aux import (
11
+ CannyDetector,
12
+ )
13
+ from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl_img2img import retrieve_timesteps, retrieve_latents
14
+ from PIL import Image
15
+ from inversion_utils import get_ddpm_inversion_scheduler, create_xts
16
+ from config import get_config, get_num_steps_actual
17
+ from functools import partial
18
+ from compel import Compel, ReturnedEmbeddingsType
19
+
20
+ os.system("pip freeze")
21
+ if not os.path.exists('GFPGANv1.4.pth'):
22
+ os.system("wget https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth -P .")
23
+ if not os.path.exists('realesr-general-x4v3.pth'):
24
+ os.system("wget https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.pth -P .")
25
+
26
+ os.makedirs('output', exist_ok=True)
27
+
28
+ class Object(object):
29
+ pass
30
+
31
+ args = Object()
32
+ args.images_paths = None
33
+ args.images_folder = None
34
+ args.force_use_cpu = False
35
+ args.folder_name = 'test_measure_time'
36
+ args.config_from_file = 'run_configs/noise_shift_guidance_1_5.yaml'
37
+ args.save_intermediate_results = False
38
+ args.batch_size = None
39
+ args.skip_p_to_p = True
40
+ args.only_p_to_p = False
41
+ args.fp16 = False
42
+ args.prompts_file = 'dataset_measure_time/dataset.json'
43
+ args.images_in_prompts_file = None
44
+ args.seed = 986
45
+ args.time_measure_n = 1
46
+
47
+
48
+ assert (
49
+ args.batch_size is None or args.save_intermediate_results is False
50
+ ), "save_intermediate_results is not implemented for batch_size > 1"
51
+
52
+ generator = None
53
+ device = "cuda" if torch.cuda.is_available() else "cpu"
54
+
55
+ # BASE_MODEL = "stabilityai/stable-diffusion-xl-base-1.0"
56
+ BASE_MODEL = "SG161222/RealVisXL_V5.0_Lightning"
57
+
58
+ canndy_detector = CannyDetector()
59
+
60
+ adapter = T2IAdapter.from_pretrained(
61
+ "TencentARC/t2i-adapter-canny-sdxl-1.0",
62
+ torch_dtype=torch.float16,
63
+ varient="fp16",
64
+ ),
65
+
66
+ pipeline = DiffusionPipeline.from_pretrained(
67
+ BASE_MODEL,
68
+ torch_dtype=torch.float16,
69
+ variant="fp16",
70
+ use_safetensors=True,
71
+ adapter=adapter,
72
+ custom_pipeline="./pipelines/pipeline_sdxl_adapter_inpaint.py",
73
+ )
74
+ pipeline = pipeline.to(device)
75
+
76
+ pipeline.scheduler = DDPMScheduler.from_pretrained(
77
+ BASE_MODEL,
78
+ subfolder="scheduler",
79
+ )
80
+
81
+ config = get_config(args)
82
+
83
+ compel_proc = Compel(
84
+ tokenizer=[pipeline.tokenizer, pipeline.tokenizer_2] ,
85
+ text_encoder=[pipeline.text_encoder, pipeline.text_encoder_2],
86
+ returned_embeddings_type=ReturnedEmbeddingsType.PENULTIMATE_HIDDEN_STATES_NON_NORMALIZED,
87
+ requires_pooled=[False, True]
88
+ )
89
+
90
+ def run(
91
+ input_image:Image,
92
+ src_prompt:str,
93
+ tgt_prompt:str,
94
+ generate_size:int,
95
+ seed:int,
96
+ w1:float,
97
+ w2:float,
98
+ num_steps:int,
99
+ start_step:int,
100
+ guidance_scale:float,
101
+ adapter_weights:float,
102
+ ):
103
+ generator = torch.Generator().manual_seed(seed)
104
+
105
+ config.num_steps_inversion = num_steps
106
+ config.step_start = start_step
107
+ num_steps_actual = get_num_steps_actual(config)
108
+
109
+
110
+ num_steps_inversion = config.num_steps_inversion
111
+ denoising_start = (num_steps_inversion - num_steps_actual) / num_steps_inversion
112
+ print(f"-------->num_steps_inversion: {num_steps_inversion} num_steps_actual: {num_steps_actual} denoising_start: {denoising_start}")
113
+
114
+ timesteps, num_inference_steps = retrieve_timesteps(
115
+ pipeline.scheduler, num_steps_inversion, device, None
116
+ )
117
+ timesteps, num_inference_steps = pipeline.get_timesteps(
118
+ num_inference_steps=num_inference_steps,
119
+ denoising_start=denoising_start,
120
+ strength=0,
121
+ device=device,
122
+ )
123
+ timesteps = timesteps.type(torch.int64)
124
+
125
+ timesteps = [torch.tensor(t) for t in timesteps.tolist()]
126
+ timesteps_len = len(timesteps)
127
+ config.step_start = start_step + num_steps_actual - timesteps_len
128
+ num_steps_actual = timesteps_len
129
+ config.max_norm_zs = [-1] * (num_steps_actual - 1) + [15.5]
130
+ print(f"-------->num_steps_inversion: {num_steps_inversion} num_steps_actual: {num_steps_actual} step_start: {config.step_start}")
131
+ print(f"-------->timesteps len: {len(timesteps)} max_norm_zs len: {len(config.max_norm_zs)}")
132
+ pipeline.__call__ = partial(
133
+ pipeline.__call__,
134
+ num_inference_steps=num_steps_inversion,
135
+ guidance_scale=guidance_scale,
136
+ generator=generator,
137
+ denoising_start=denoising_start,
138
+ strength=0,
139
+ )
140
+
141
+ x_0_image = input_image
142
+ x_0 = encode_image(x_0_image, pipeline)
143
+ x_ts = create_xts(1, None, 0, generator, pipeline.scheduler, timesteps, x_0, no_add_noise=False)
144
+ x_ts = [xt.to(dtype=torch.float16) for xt in x_ts]
145
+ latents = [x_ts[0]]
146
+ x_ts_c_hat = [None]
147
+ config.ws1 = [w1] * num_steps_actual
148
+ config.ws2 = [w2] * num_steps_actual
149
+ pipeline.scheduler = get_ddpm_inversion_scheduler(
150
+ pipeline.scheduler,
151
+ config.step_function,
152
+ config,
153
+ timesteps,
154
+ config.save_timesteps,
155
+ latents,
156
+ x_ts,
157
+ x_ts_c_hat,
158
+ args.save_intermediate_results,
159
+ pipeline,
160
+ x_0,
161
+ v1s_images := [],
162
+ v2s_images := [],
163
+ deltas_images := [],
164
+ v1_x0s := [],
165
+ v2_x0s := [],
166
+ deltas_x0s := [],
167
+ "res12",
168
+ image_name="im_name",
169
+ time_measure_n=args.time_measure_n,
170
+ )
171
+ latent = latents[0].expand(3, -1, -1, -1)
172
+ prompt = [src_prompt, src_prompt, tgt_prompt]
173
+ conditioning, pooled = compel_proc(prompt)
174
+ canny_image = canndy_detector(input_image, 384, generate_size)
175
+ image = pipeline.__call__(
176
+ image=latent,
177
+ prompt_embeds=conditioning,
178
+ pooled_prompt_embeds=pooled,
179
+ eta=1,
180
+ adapter_image=canny_image,
181
+ adapter_conditioning_scale=adapter_weights,
182
+ ).images
183
+ return image[2]
184
+
185
+ def encode_image(image, pipe):
186
+ image = pipe.image_processor.preprocess(image)
187
+ originDtype = pipe.dtype
188
+ image = image.to(device=device, dtype=originDtype)
189
+
190
+ if pipe.vae.config.force_upcast:
191
+ image = image.float()
192
+ pipe.vae.to(dtype=torch.float32)
193
+
194
+ if isinstance(generator, list):
195
+ init_latents = [
196
+ retrieve_latents(pipe.vae.encode(image[i : i + 1]), generator=generator[i])
197
+ for i in range(1)
198
+ ]
199
+ init_latents = torch.cat(init_latents, dim=0)
200
+ else:
201
+ init_latents = retrieve_latents(pipe.vae.encode(image), generator=generator)
202
+
203
+ if pipe.vae.config.force_upcast:
204
+ pipe.vae.to(originDtype)
205
+
206
+ init_latents = init_latents.to(originDtype)
207
+ init_latents = pipe.vae.config.scaling_factor * init_latents
208
+
209
+ return init_latents.to(dtype=torch.float16)
210
+
211
+ def get_timesteps(pipe, num_inference_steps, strength, device, denoising_start=None):
212
+ # get the original timestep using init_timestep
213
+ if denoising_start is None:
214
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
215
+ t_start = max(num_inference_steps - init_timestep, 0)
216
+ else:
217
+ t_start = 0
218
+
219
+ timesteps = pipe.scheduler.timesteps[t_start * pipe.scheduler.order :]
220
+
221
+ # Strength is irrelevant if we directly request a timestep to start at;
222
+ # that is, strength is determined by the denoising_start instead.
223
+ if denoising_start is not None:
224
+ discrete_timestep_cutoff = int(
225
+ round(
226
+ pipe.scheduler.config.num_train_timesteps
227
+ - (denoising_start * pipe.scheduler.config.num_train_timesteps)
228
+ )
229
+ )
230
+
231
+ num_inference_steps = (timesteps < discrete_timestep_cutoff).sum().item()
232
+ if pipe.scheduler.order == 2 and num_inference_steps % 2 == 0:
233
+ # if the scheduler is a 2nd order scheduler we might have to do +1
234
+ # because `num_inference_steps` might be even given that every timestep
235
+ # (except the highest one) is duplicated. If `num_inference_steps` is even it would
236
+ # mean that we cut the timesteps in the middle of the denoising step
237
+ # (between 1st and 2nd derivative) which leads to incorrect results. By adding 1
238
+ # we ensure that the denoising process always ends after the 2nd derivate step of the scheduler
239
+ num_inference_steps = num_inference_steps + 1
240
+
241
+ # because t_n+1 >= t_n, we slice the timesteps starting from the end
242
+ timesteps = timesteps[-num_inference_steps:]
243
+ return timesteps, num_inference_steps
244
+
245
+ return timesteps, num_inference_steps - t_start
pipelines/pipeline_sdxl_adapter_img2img.py ADDED
@@ -0,0 +1,1672 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
17
+
18
+ import numpy as np
19
+ import PIL.Image
20
+ import torch
21
+ from transformers import (
22
+ CLIPImageProcessor,
23
+ CLIPTextModel,
24
+ CLIPTextModelWithProjection,
25
+ CLIPTokenizer,
26
+ CLIPVisionModelWithProjection,
27
+ )
28
+
29
+ from diffusers.callbacks import (
30
+ MultiPipelineCallbacks,
31
+ PipelineCallback,
32
+ )
33
+
34
+ from diffusers.image_processor import (
35
+ PipelineImageInput,
36
+ VaeImageProcessor,
37
+ )
38
+
39
+ from diffusers.loaders import (
40
+ FromSingleFileMixin,
41
+ IPAdapterMixin,
42
+ StableDiffusionXLLoraLoaderMixin,
43
+ TextualInversionLoaderMixin,
44
+ )
45
+
46
+ from diffusers.models import (
47
+ AutoencoderKL,
48
+ ImageProjection,
49
+ MultiAdapter,
50
+ T2IAdapter,
51
+ UNet2DConditionModel,
52
+ )
53
+
54
+ from diffusers.models.attention_processor import (
55
+ AttnProcessor2_0,
56
+ XFormersAttnProcessor,
57
+ )
58
+
59
+ from diffusers.models.lora import (
60
+ adjust_lora_scale_text_encoder,
61
+ )
62
+
63
+ from diffusers.schedulers import (
64
+ KarrasDiffusionSchedulers,
65
+ )
66
+
67
+ from diffusers.utils import (
68
+ PIL_INTERPOLATION,
69
+ USE_PEFT_BACKEND,
70
+ deprecate,
71
+ is_invisible_watermark_available,
72
+ is_torch_xla_available,
73
+ logging,
74
+ replace_example_docstring,
75
+ scale_lora_layers,
76
+ unscale_lora_layers,
77
+ )
78
+
79
+ from diffusers.utils.torch_utils import (
80
+ randn_tensor,
81
+ )
82
+
83
+ from diffusers.pipelines.pipeline_utils import (
84
+ DiffusionPipeline,
85
+ StableDiffusionMixin,
86
+ )
87
+
88
+ from diffusers.pipelines.stable_diffusion_xl.pipeline_output import (
89
+ StableDiffusionXLPipelineOutput,
90
+ )
91
+
92
+
93
+ if is_invisible_watermark_available():
94
+ from diffusers.pipelines.stable_diffusion_xl.watermark import (
95
+ StableDiffusionXLWatermarker,
96
+ )
97
+
98
+ if is_torch_xla_available():
99
+ import torch_xla.core.xla_model as xm
100
+
101
+ XLA_AVAILABLE = True
102
+ else:
103
+ XLA_AVAILABLE = False
104
+
105
+
106
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
107
+
108
+ EXAMPLE_DOC_STRING = """
109
+ Examples:
110
+ ```py
111
+ >>> import torch
112
+ >>> from diffusers import StableDiffusionXLImg2ImgPipeline
113
+ >>> from diffusers.utils import load_image
114
+
115
+ >>> pipe = StableDiffusionXLImg2ImgPipeline.from_pretrained(
116
+ ... "stabilityai/stable-diffusion-xl-refiner-1.0", torch_dtype=torch.float16
117
+ ... )
118
+ >>> pipe = pipe.to("cuda")
119
+ >>> url = "https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/aa_xl/000000009.png"
120
+
121
+ >>> init_image = load_image(url).convert("RGB")
122
+ >>> prompt = "a photo of an astronaut riding a horse on mars"
123
+ >>> image = pipe(prompt, image=init_image).images[0]
124
+ ```
125
+ """
126
+
127
+
128
+ def _preprocess_adapter_image(image, height, width):
129
+ if isinstance(image, torch.Tensor):
130
+ return image
131
+ elif isinstance(image, PIL.Image.Image):
132
+ image = [image]
133
+
134
+ if isinstance(image[0], PIL.Image.Image):
135
+ image = [np.array(i.resize((width, height), resample=PIL_INTERPOLATION["lanczos"])) for i in image]
136
+ image = [
137
+ i[None, ..., None] if i.ndim == 2 else i[None, ...] for i in image
138
+ ] # expand [h, w] or [h, w, c] to [b, h, w, c]
139
+ image = np.concatenate(image, axis=0)
140
+ image = np.array(image).astype(np.float32) / 255.0
141
+ image = image.transpose(0, 3, 1, 2)
142
+ image = torch.from_numpy(image)
143
+ elif isinstance(image[0], torch.Tensor):
144
+ if image[0].ndim == 3:
145
+ image = torch.stack(image, dim=0)
146
+ elif image[0].ndim == 4:
147
+ image = torch.cat(image, dim=0)
148
+ else:
149
+ raise ValueError(
150
+ f"Invalid image tensor! Expecting image tensor with 3 or 4 dimension, but recive: {image[0].ndim}"
151
+ )
152
+ return image
153
+
154
+
155
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
156
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
157
+ """
158
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
159
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
160
+ """
161
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
162
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
163
+ # rescale the results from guidance (fixes overexposure)
164
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
165
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
166
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
167
+ return noise_cfg
168
+
169
+
170
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
171
+ def retrieve_latents(
172
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
173
+ ):
174
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
175
+ return encoder_output.latent_dist.sample(generator)
176
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
177
+ return encoder_output.latent_dist.mode()
178
+ elif hasattr(encoder_output, "latents"):
179
+ return encoder_output.latents
180
+ else:
181
+ raise AttributeError("Could not access latents of provided encoder_output")
182
+
183
+
184
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
185
+ def retrieve_timesteps(
186
+ scheduler,
187
+ num_inference_steps: Optional[int] = None,
188
+ device: Optional[Union[str, torch.device]] = None,
189
+ timesteps: Optional[List[int]] = None,
190
+ sigmas: Optional[List[float]] = None,
191
+ **kwargs,
192
+ ):
193
+ """
194
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
195
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
196
+
197
+ Args:
198
+ scheduler (`SchedulerMixin`):
199
+ The scheduler to get timesteps from.
200
+ num_inference_steps (`int`):
201
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
202
+ must be `None`.
203
+ device (`str` or `torch.device`, *optional*):
204
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
205
+ timesteps (`List[int]`, *optional*):
206
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
207
+ `num_inference_steps` and `sigmas` must be `None`.
208
+ sigmas (`List[float]`, *optional*):
209
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
210
+ `num_inference_steps` and `timesteps` must be `None`.
211
+
212
+ Returns:
213
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
214
+ second element is the number of inference steps.
215
+ """
216
+ if timesteps is not None and sigmas is not None:
217
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
218
+ if timesteps is not None:
219
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
220
+ if not accepts_timesteps:
221
+ raise ValueError(
222
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
223
+ f" timestep schedules. Please check whether you are using the correct scheduler."
224
+ )
225
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
226
+ timesteps = scheduler.timesteps
227
+ num_inference_steps = len(timesteps)
228
+ elif sigmas is not None:
229
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
230
+ if not accept_sigmas:
231
+ raise ValueError(
232
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
233
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
234
+ )
235
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
236
+ timesteps = scheduler.timesteps
237
+ num_inference_steps = len(timesteps)
238
+ else:
239
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
240
+ timesteps = scheduler.timesteps
241
+ return timesteps, num_inference_steps
242
+
243
+
244
+ class StableDiffusionXLImg2ImgPipeline(
245
+ DiffusionPipeline,
246
+ StableDiffusionMixin,
247
+ TextualInversionLoaderMixin,
248
+ FromSingleFileMixin,
249
+ StableDiffusionXLLoraLoaderMixin,
250
+ IPAdapterMixin,
251
+ ):
252
+ r"""
253
+ Pipeline for text-to-image generation using Stable Diffusion XL.
254
+
255
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
256
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
257
+
258
+ The pipeline also inherits the following loading methods:
259
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
260
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
261
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
262
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
263
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
264
+
265
+ Args:
266
+ vae ([`AutoencoderKL`]):
267
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
268
+ text_encoder ([`CLIPTextModel`]):
269
+ Frozen text-encoder. Stable Diffusion XL uses the text portion of
270
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
271
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
272
+ text_encoder_2 ([` CLIPTextModelWithProjection`]):
273
+ Second frozen text-encoder. Stable Diffusion XL uses the text and pool portion of
274
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
275
+ specifically the
276
+ [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)
277
+ variant.
278
+ tokenizer (`CLIPTokenizer`):
279
+ Tokenizer of class
280
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
281
+ tokenizer_2 (`CLIPTokenizer`):
282
+ Second Tokenizer of class
283
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
284
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
285
+ scheduler ([`SchedulerMixin`]):
286
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
287
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
288
+ requires_aesthetics_score (`bool`, *optional*, defaults to `"False"`):
289
+ Whether the `unet` requires an `aesthetic_score` condition to be passed during inference. Also see the
290
+ config of `stabilityai/stable-diffusion-xl-refiner-1-0`.
291
+ force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"True"`):
292
+ Whether the negative prompt embeddings shall be forced to always be set to 0. Also see the config of
293
+ `stabilityai/stable-diffusion-xl-base-1-0`.
294
+ add_watermarker (`bool`, *optional*):
295
+ Whether to use the [invisible_watermark library](https://github.com/ShieldMnt/invisible-watermark/) to
296
+ watermark output images. If not defined, it will default to True if the package is installed, otherwise no
297
+ watermarker will be used.
298
+ """
299
+
300
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->image_encoder->unet->vae"
301
+ _optional_components = [
302
+ "tokenizer",
303
+ "tokenizer_2",
304
+ "text_encoder",
305
+ "text_encoder_2",
306
+ "image_encoder",
307
+ "feature_extractor",
308
+ ]
309
+ _callback_tensor_inputs = [
310
+ "latents",
311
+ "prompt_embeds",
312
+ "negative_prompt_embeds",
313
+ "add_text_embeds",
314
+ "add_time_ids",
315
+ "negative_pooled_prompt_embeds",
316
+ "add_neg_time_ids",
317
+ ]
318
+
319
+ def __init__(
320
+ self,
321
+ vae: AutoencoderKL,
322
+ text_encoder: CLIPTextModel,
323
+ text_encoder_2: CLIPTextModelWithProjection,
324
+ tokenizer: CLIPTokenizer,
325
+ tokenizer_2: CLIPTokenizer,
326
+ unet: UNet2DConditionModel,
327
+ adapter: Union[T2IAdapter, MultiAdapter, List[T2IAdapter]],
328
+ scheduler: KarrasDiffusionSchedulers,
329
+ image_encoder: CLIPVisionModelWithProjection = None,
330
+ feature_extractor: CLIPImageProcessor = None,
331
+ requires_aesthetics_score: bool = False,
332
+ force_zeros_for_empty_prompt: bool = True,
333
+ add_watermarker: Optional[bool] = None,
334
+ ):
335
+ super().__init__()
336
+
337
+ self.register_modules(
338
+ vae=vae,
339
+ text_encoder=text_encoder,
340
+ text_encoder_2=text_encoder_2,
341
+ tokenizer=tokenizer,
342
+ tokenizer_2=tokenizer_2,
343
+ unet=unet,
344
+ adapter=adapter,
345
+ image_encoder=image_encoder,
346
+ feature_extractor=feature_extractor,
347
+ scheduler=scheduler,
348
+ )
349
+ self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
350
+ self.register_to_config(requires_aesthetics_score=requires_aesthetics_score)
351
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
352
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
353
+
354
+ add_watermarker = add_watermarker if add_watermarker is not None else is_invisible_watermark_available()
355
+
356
+ if add_watermarker:
357
+ self.watermark = StableDiffusionXLWatermarker()
358
+ else:
359
+ self.watermark = None
360
+
361
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.encode_prompt
362
+ def encode_prompt(
363
+ self,
364
+ prompt: str,
365
+ prompt_2: Optional[str] = None,
366
+ device: Optional[torch.device] = None,
367
+ num_images_per_prompt: int = 1,
368
+ do_classifier_free_guidance: bool = True,
369
+ negative_prompt: Optional[str] = None,
370
+ negative_prompt_2: Optional[str] = None,
371
+ prompt_embeds: Optional[torch.Tensor] = None,
372
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
373
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
374
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
375
+ lora_scale: Optional[float] = None,
376
+ clip_skip: Optional[int] = None,
377
+ ):
378
+ r"""
379
+ Encodes the prompt into text encoder hidden states.
380
+
381
+ Args:
382
+ prompt (`str` or `List[str]`, *optional*):
383
+ prompt to be encoded
384
+ prompt_2 (`str` or `List[str]`, *optional*):
385
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
386
+ used in both text-encoders
387
+ device: (`torch.device`):
388
+ torch device
389
+ num_images_per_prompt (`int`):
390
+ number of images that should be generated per prompt
391
+ do_classifier_free_guidance (`bool`):
392
+ whether to use classifier free guidance or not
393
+ negative_prompt (`str` or `List[str]`, *optional*):
394
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
395
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
396
+ less than `1`).
397
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
398
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
399
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
400
+ prompt_embeds (`torch.Tensor`, *optional*):
401
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
402
+ provided, text embeddings will be generated from `prompt` input argument.
403
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
404
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
405
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
406
+ argument.
407
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
408
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
409
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
410
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
411
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
412
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
413
+ input argument.
414
+ lora_scale (`float`, *optional*):
415
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
416
+ clip_skip (`int`, *optional*):
417
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
418
+ the output of the pre-final layer will be used for computing the prompt embeddings.
419
+ """
420
+ device = device or self._execution_device
421
+
422
+ # set lora scale so that monkey patched LoRA
423
+ # function of text encoder can correctly access it
424
+ if lora_scale is not None and isinstance(self, StableDiffusionXLLoraLoaderMixin):
425
+ self._lora_scale = lora_scale
426
+
427
+ # dynamically adjust the LoRA scale
428
+ if self.text_encoder is not None:
429
+ if not USE_PEFT_BACKEND:
430
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
431
+ else:
432
+ scale_lora_layers(self.text_encoder, lora_scale)
433
+
434
+ if self.text_encoder_2 is not None:
435
+ if not USE_PEFT_BACKEND:
436
+ adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
437
+ else:
438
+ scale_lora_layers(self.text_encoder_2, lora_scale)
439
+
440
+ prompt = [prompt] if isinstance(prompt, str) else prompt
441
+
442
+ if prompt is not None:
443
+ batch_size = len(prompt)
444
+ else:
445
+ batch_size = prompt_embeds.shape[0]
446
+
447
+ # Define tokenizers and text encoders
448
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
449
+ text_encoders = (
450
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
451
+ )
452
+
453
+ if prompt_embeds is None:
454
+ prompt_2 = prompt_2 or prompt
455
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
456
+
457
+ # textual inversion: process multi-vector tokens if necessary
458
+ prompt_embeds_list = []
459
+ prompts = [prompt, prompt_2]
460
+ for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
461
+ if isinstance(self, TextualInversionLoaderMixin):
462
+ prompt = self.maybe_convert_prompt(prompt, tokenizer)
463
+
464
+ text_inputs = tokenizer(
465
+ prompt,
466
+ padding="max_length",
467
+ max_length=tokenizer.model_max_length,
468
+ truncation=True,
469
+ return_tensors="pt",
470
+ )
471
+
472
+ text_input_ids = text_inputs.input_ids
473
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
474
+
475
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
476
+ text_input_ids, untruncated_ids
477
+ ):
478
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
479
+ logger.warning(
480
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
481
+ f" {tokenizer.model_max_length} tokens: {removed_text}"
482
+ )
483
+
484
+ prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=True)
485
+
486
+ # We are only ALWAYS interested in the pooled output of the final text encoder
487
+ pooled_prompt_embeds = prompt_embeds[0]
488
+ if clip_skip is None:
489
+ prompt_embeds = prompt_embeds.hidden_states[-2]
490
+ else:
491
+ # "2" because SDXL always indexes from the penultimate layer.
492
+ prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
493
+
494
+ prompt_embeds_list.append(prompt_embeds)
495
+
496
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
497
+
498
+ # get unconditional embeddings for classifier free guidance
499
+ zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
500
+ if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
501
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
502
+ negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
503
+ elif do_classifier_free_guidance and negative_prompt_embeds is None:
504
+ negative_prompt = negative_prompt or ""
505
+ negative_prompt_2 = negative_prompt_2 or negative_prompt
506
+
507
+ # normalize str to list
508
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
509
+ negative_prompt_2 = (
510
+ batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
511
+ )
512
+
513
+ uncond_tokens: List[str]
514
+ if prompt is not None and type(prompt) is not type(negative_prompt):
515
+ raise TypeError(
516
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
517
+ f" {type(prompt)}."
518
+ )
519
+ elif batch_size != len(negative_prompt):
520
+ raise ValueError(
521
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
522
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
523
+ " the batch size of `prompt`."
524
+ )
525
+ else:
526
+ uncond_tokens = [negative_prompt, negative_prompt_2]
527
+
528
+ negative_prompt_embeds_list = []
529
+ for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
530
+ if isinstance(self, TextualInversionLoaderMixin):
531
+ negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
532
+
533
+ max_length = prompt_embeds.shape[1]
534
+ uncond_input = tokenizer(
535
+ negative_prompt,
536
+ padding="max_length",
537
+ max_length=max_length,
538
+ truncation=True,
539
+ return_tensors="pt",
540
+ )
541
+
542
+ negative_prompt_embeds = text_encoder(
543
+ uncond_input.input_ids.to(device),
544
+ output_hidden_states=True,
545
+ )
546
+ # We are only ALWAYS interested in the pooled output of the final text encoder
547
+ negative_pooled_prompt_embeds = negative_prompt_embeds[0]
548
+ negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
549
+
550
+ negative_prompt_embeds_list.append(negative_prompt_embeds)
551
+
552
+ negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
553
+
554
+ if self.text_encoder_2 is not None:
555
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
556
+ else:
557
+ prompt_embeds = prompt_embeds.to(dtype=self.unet.dtype, device=device)
558
+
559
+ bs_embed, seq_len, _ = prompt_embeds.shape
560
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
561
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
562
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
563
+
564
+ if do_classifier_free_guidance:
565
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
566
+ seq_len = negative_prompt_embeds.shape[1]
567
+
568
+ if self.text_encoder_2 is not None:
569
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
570
+ else:
571
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.unet.dtype, device=device)
572
+
573
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
574
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
575
+
576
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
577
+ bs_embed * num_images_per_prompt, -1
578
+ )
579
+ if do_classifier_free_guidance:
580
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
581
+ bs_embed * num_images_per_prompt, -1
582
+ )
583
+
584
+ if self.text_encoder is not None:
585
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
586
+ # Retrieve the original scale by scaling back the LoRA layers
587
+ unscale_lora_layers(self.text_encoder, lora_scale)
588
+
589
+ if self.text_encoder_2 is not None:
590
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
591
+ # Retrieve the original scale by scaling back the LoRA layers
592
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
593
+
594
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
595
+
596
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
597
+ def prepare_ip_adapter_image_embeds(
598
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
599
+ ):
600
+ image_embeds = []
601
+ if do_classifier_free_guidance:
602
+ negative_image_embeds = []
603
+ if ip_adapter_image_embeds is None:
604
+ if not isinstance(ip_adapter_image, list):
605
+ ip_adapter_image = [ip_adapter_image]
606
+
607
+ if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
608
+ raise ValueError(
609
+ 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."
610
+ )
611
+
612
+ for single_ip_adapter_image, image_proj_layer in zip(
613
+ ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
614
+ ):
615
+ output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
616
+ single_image_embeds, single_negative_image_embeds = self.encode_image(
617
+ single_ip_adapter_image, device, 1, output_hidden_state
618
+ )
619
+
620
+ image_embeds.append(single_image_embeds[None, :])
621
+ if do_classifier_free_guidance:
622
+ negative_image_embeds.append(single_negative_image_embeds[None, :])
623
+ else:
624
+ for single_image_embeds in ip_adapter_image_embeds:
625
+ if do_classifier_free_guidance:
626
+ single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
627
+ negative_image_embeds.append(single_negative_image_embeds)
628
+ image_embeds.append(single_image_embeds)
629
+
630
+ ip_adapter_image_embeds = []
631
+ for i, single_image_embeds in enumerate(image_embeds):
632
+ single_image_embeds = torch.cat([single_image_embeds] * num_images_per_prompt, dim=0)
633
+ if do_classifier_free_guidance:
634
+ single_negative_image_embeds = torch.cat([negative_image_embeds[i]] * num_images_per_prompt, dim=0)
635
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds], dim=0)
636
+
637
+ single_image_embeds = single_image_embeds.to(device=device)
638
+ ip_adapter_image_embeds.append(single_image_embeds)
639
+
640
+ return ip_adapter_image_embeds
641
+
642
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
643
+ def prepare_extra_step_kwargs(self, generator, eta):
644
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
645
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
646
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
647
+ # and should be between [0, 1]
648
+
649
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
650
+ extra_step_kwargs = {}
651
+ if accepts_eta:
652
+ extra_step_kwargs["eta"] = eta
653
+
654
+ # check if the scheduler accepts generator
655
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
656
+ if accepts_generator:
657
+ extra_step_kwargs["generator"] = generator
658
+ return extra_step_kwargs
659
+
660
+ def check_inputs(
661
+ self,
662
+ prompt,
663
+ prompt_2,
664
+ strength,
665
+ num_inference_steps,
666
+ callback_steps,
667
+ negative_prompt=None,
668
+ negative_prompt_2=None,
669
+ prompt_embeds=None,
670
+ negative_prompt_embeds=None,
671
+ ip_adapter_image=None,
672
+ ip_adapter_image_embeds=None,
673
+ callback_on_step_end_tensor_inputs=None,
674
+ ):
675
+ if strength < 0 or strength > 1:
676
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
677
+ if num_inference_steps is None:
678
+ raise ValueError("`num_inference_steps` cannot be None.")
679
+ elif not isinstance(num_inference_steps, int) or num_inference_steps <= 0:
680
+ raise ValueError(
681
+ f"`num_inference_steps` has to be a positive integer but is {num_inference_steps} of type"
682
+ f" {type(num_inference_steps)}."
683
+ )
684
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
685
+ raise ValueError(
686
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
687
+ f" {type(callback_steps)}."
688
+ )
689
+
690
+ if callback_on_step_end_tensor_inputs is not None and not all(
691
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
692
+ ):
693
+ raise ValueError(
694
+ 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]}"
695
+ )
696
+
697
+ if prompt is not None and prompt_embeds is not None:
698
+ raise ValueError(
699
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
700
+ " only forward one of the two."
701
+ )
702
+ elif prompt_2 is not None and prompt_embeds is not None:
703
+ raise ValueError(
704
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
705
+ " only forward one of the two."
706
+ )
707
+ elif prompt is None and prompt_embeds is None:
708
+ raise ValueError(
709
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
710
+ )
711
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
712
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
713
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
714
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
715
+
716
+ if negative_prompt is not None and negative_prompt_embeds is not None:
717
+ raise ValueError(
718
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
719
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
720
+ )
721
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
722
+ raise ValueError(
723
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
724
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
725
+ )
726
+
727
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
728
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
729
+ raise ValueError(
730
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
731
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
732
+ f" {negative_prompt_embeds.shape}."
733
+ )
734
+
735
+ if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
736
+ raise ValueError(
737
+ "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
738
+ )
739
+
740
+ if ip_adapter_image_embeds is not None:
741
+ if not isinstance(ip_adapter_image_embeds, list):
742
+ raise ValueError(
743
+ f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
744
+ )
745
+ elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
746
+ raise ValueError(
747
+ f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
748
+ )
749
+
750
+ def get_timesteps(self, num_inference_steps, strength, device, denoising_start=None):
751
+ # get the original timestep using init_timestep
752
+ if denoising_start is None:
753
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
754
+ t_start = max(num_inference_steps - init_timestep, 0)
755
+ else:
756
+ t_start = 0
757
+
758
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
759
+
760
+ # Strength is irrelevant if we directly request a timestep to start at;
761
+ # that is, strength is determined by the denoising_start instead.
762
+ if denoising_start is not None:
763
+ discrete_timestep_cutoff = int(
764
+ round(
765
+ self.scheduler.config.num_train_timesteps
766
+ - (denoising_start * self.scheduler.config.num_train_timesteps)
767
+ )
768
+ )
769
+
770
+ num_inference_steps = (timesteps < discrete_timestep_cutoff).sum().item()
771
+ if self.scheduler.order == 2 and num_inference_steps % 2 == 0:
772
+ # if the scheduler is a 2nd order scheduler we might have to do +1
773
+ # because `num_inference_steps` might be even given that every timestep
774
+ # (except the highest one) is duplicated. If `num_inference_steps` is even it would
775
+ # mean that we cut the timesteps in the middle of the denoising step
776
+ # (between 1st and 2nd derivative) which leads to incorrect results. By adding 1
777
+ # we ensure that the denoising process always ends after the 2nd derivate step of the scheduler
778
+ num_inference_steps = num_inference_steps + 1
779
+
780
+ # because t_n+1 >= t_n, we slice the timesteps starting from the end
781
+ timesteps = timesteps[-num_inference_steps:]
782
+ return timesteps, num_inference_steps
783
+
784
+ return timesteps, num_inference_steps - t_start
785
+
786
+ def prepare_latents(
787
+ self, image, timestep, batch_size, num_images_per_prompt, dtype, device, generator=None, add_noise=True
788
+ ):
789
+ if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
790
+ raise ValueError(
791
+ f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
792
+ )
793
+
794
+ latents_mean = latents_std = None
795
+ if hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None:
796
+ latents_mean = torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1)
797
+ if hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None:
798
+ latents_std = torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1)
799
+
800
+ # Offload text encoder if `enable_model_cpu_offload` was enabled
801
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
802
+ self.text_encoder_2.to("cpu")
803
+ torch.cuda.empty_cache()
804
+
805
+ image = image.to(device=device, dtype=dtype)
806
+
807
+ batch_size = batch_size * num_images_per_prompt
808
+
809
+ if image.shape[1] == 4:
810
+ init_latents = image
811
+
812
+ else:
813
+ # make sure the VAE is in float32 mode, as it overflows in float16
814
+ if self.vae.config.force_upcast:
815
+ image = image.float()
816
+ self.vae.to(dtype=torch.float32)
817
+
818
+ if isinstance(generator, list) and len(generator) != batch_size:
819
+ raise ValueError(
820
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
821
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
822
+ )
823
+
824
+ elif isinstance(generator, list):
825
+ if image.shape[0] < batch_size and batch_size % image.shape[0] == 0:
826
+ image = torch.cat([image] * (batch_size // image.shape[0]), dim=0)
827
+ elif image.shape[0] < batch_size and batch_size % image.shape[0] != 0:
828
+ raise ValueError(
829
+ f"Cannot duplicate `image` of batch size {image.shape[0]} to effective batch_size {batch_size} "
830
+ )
831
+
832
+ init_latents = [
833
+ retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i])
834
+ for i in range(batch_size)
835
+ ]
836
+ init_latents = torch.cat(init_latents, dim=0)
837
+ else:
838
+ init_latents = retrieve_latents(self.vae.encode(image), generator=generator)
839
+
840
+ if self.vae.config.force_upcast:
841
+ self.vae.to(dtype)
842
+
843
+ init_latents = init_latents.to(dtype)
844
+ if latents_mean is not None and latents_std is not None:
845
+ latents_mean = latents_mean.to(device=device, dtype=dtype)
846
+ latents_std = latents_std.to(device=device, dtype=dtype)
847
+ init_latents = (init_latents - latents_mean) * self.vae.config.scaling_factor / latents_std
848
+ else:
849
+ init_latents = self.vae.config.scaling_factor * init_latents
850
+
851
+ if batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] == 0:
852
+ # expand init_latents for batch_size
853
+ additional_image_per_prompt = batch_size // init_latents.shape[0]
854
+ init_latents = torch.cat([init_latents] * additional_image_per_prompt, dim=0)
855
+ elif batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] != 0:
856
+ raise ValueError(
857
+ f"Cannot duplicate `image` of batch size {init_latents.shape[0]} to {batch_size} text prompts."
858
+ )
859
+ else:
860
+ init_latents = torch.cat([init_latents], dim=0)
861
+
862
+ if add_noise:
863
+ shape = init_latents.shape
864
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
865
+ # get latents
866
+ init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
867
+
868
+ latents = init_latents
869
+
870
+ return latents
871
+
872
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
873
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
874
+ dtype = next(self.image_encoder.parameters()).dtype
875
+
876
+ if not isinstance(image, torch.Tensor):
877
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
878
+
879
+ image = image.to(device=device, dtype=dtype)
880
+ if output_hidden_states:
881
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
882
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
883
+ uncond_image_enc_hidden_states = self.image_encoder(
884
+ torch.zeros_like(image), output_hidden_states=True
885
+ ).hidden_states[-2]
886
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
887
+ num_images_per_prompt, dim=0
888
+ )
889
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
890
+ else:
891
+ image_embeds = self.image_encoder(image).image_embeds
892
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
893
+ uncond_image_embeds = torch.zeros_like(image_embeds)
894
+
895
+ return image_embeds, uncond_image_embeds
896
+
897
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
898
+ def prepare_ip_adapter_image_embeds(
899
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
900
+ ):
901
+ image_embeds = []
902
+ if do_classifier_free_guidance:
903
+ negative_image_embeds = []
904
+ if ip_adapter_image_embeds is None:
905
+ if not isinstance(ip_adapter_image, list):
906
+ ip_adapter_image = [ip_adapter_image]
907
+
908
+ if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
909
+ raise ValueError(
910
+ 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."
911
+ )
912
+
913
+ for single_ip_adapter_image, image_proj_layer in zip(
914
+ ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
915
+ ):
916
+ output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
917
+ single_image_embeds, single_negative_image_embeds = self.encode_image(
918
+ single_ip_adapter_image, device, 1, output_hidden_state
919
+ )
920
+
921
+ image_embeds.append(single_image_embeds[None, :])
922
+ if do_classifier_free_guidance:
923
+ negative_image_embeds.append(single_negative_image_embeds[None, :])
924
+ else:
925
+ for single_image_embeds in ip_adapter_image_embeds:
926
+ if do_classifier_free_guidance:
927
+ single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
928
+ negative_image_embeds.append(single_negative_image_embeds)
929
+ image_embeds.append(single_image_embeds)
930
+
931
+ ip_adapter_image_embeds = []
932
+ for i, single_image_embeds in enumerate(image_embeds):
933
+ single_image_embeds = torch.cat([single_image_embeds] * num_images_per_prompt, dim=0)
934
+ if do_classifier_free_guidance:
935
+ single_negative_image_embeds = torch.cat([negative_image_embeds[i]] * num_images_per_prompt, dim=0)
936
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds], dim=0)
937
+
938
+ single_image_embeds = single_image_embeds.to(device=device)
939
+ ip_adapter_image_embeds.append(single_image_embeds)
940
+
941
+ return ip_adapter_image_embeds
942
+
943
+ def _get_add_time_ids(
944
+ self,
945
+ original_size,
946
+ crops_coords_top_left,
947
+ target_size,
948
+ aesthetic_score,
949
+ negative_aesthetic_score,
950
+ negative_original_size,
951
+ negative_crops_coords_top_left,
952
+ negative_target_size,
953
+ dtype,
954
+ text_encoder_projection_dim=None,
955
+ ):
956
+ if self.config.requires_aesthetics_score:
957
+ add_time_ids = list(original_size + crops_coords_top_left + (aesthetic_score,))
958
+ add_neg_time_ids = list(
959
+ negative_original_size + negative_crops_coords_top_left + (negative_aesthetic_score,)
960
+ )
961
+ else:
962
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
963
+ add_neg_time_ids = list(negative_original_size + crops_coords_top_left + negative_target_size)
964
+
965
+ passed_add_embed_dim = (
966
+ self.unet.config.addition_time_embed_dim * len(add_time_ids) + text_encoder_projection_dim
967
+ )
968
+ expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
969
+
970
+ if (
971
+ expected_add_embed_dim > passed_add_embed_dim
972
+ and (expected_add_embed_dim - passed_add_embed_dim) == self.unet.config.addition_time_embed_dim
973
+ ):
974
+ raise ValueError(
975
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. Please make sure to enable `requires_aesthetics_score` with `pipe.register_to_config(requires_aesthetics_score=True)` to make sure `aesthetic_score` {aesthetic_score} and `negative_aesthetic_score` {negative_aesthetic_score} is correctly used by the model."
976
+ )
977
+ elif (
978
+ expected_add_embed_dim < passed_add_embed_dim
979
+ and (passed_add_embed_dim - expected_add_embed_dim) == self.unet.config.addition_time_embed_dim
980
+ ):
981
+ raise ValueError(
982
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. Please make sure to disable `requires_aesthetics_score` with `pipe.register_to_config(requires_aesthetics_score=False)` to make sure `target_size` {target_size} is correctly used by the model."
983
+ )
984
+ elif expected_add_embed_dim != passed_add_embed_dim:
985
+ raise ValueError(
986
+ 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`."
987
+ )
988
+
989
+ add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
990
+ add_neg_time_ids = torch.tensor([add_neg_time_ids], dtype=dtype)
991
+
992
+ return add_time_ids, add_neg_time_ids
993
+
994
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.StableDiffusionUpscalePipeline.upcast_vae
995
+ def upcast_vae(self):
996
+ dtype = self.vae.dtype
997
+ self.vae.to(dtype=torch.float32)
998
+ use_torch_2_0_or_xformers = isinstance(
999
+ self.vae.decoder.mid_block.attentions[0].processor,
1000
+ (
1001
+ AttnProcessor2_0,
1002
+ XFormersAttnProcessor,
1003
+ ),
1004
+ )
1005
+ # if xformers or torch_2_0 is used attention block does not need
1006
+ # to be in float32 which can save lots of memory
1007
+ if use_torch_2_0_or_xformers:
1008
+ self.vae.post_quant_conv.to(dtype)
1009
+ self.vae.decoder.conv_in.to(dtype)
1010
+ self.vae.decoder.mid_block.to(dtype)
1011
+
1012
+ # Copied from diffusers.pipelines.t2i_adapter.pipeline_stable_diffusion_adapter.StableDiffusionAdapterPipeline._default_height_width
1013
+ def _default_height_width(self, height, width, image):
1014
+ # NOTE: It is possible that a list of images have different
1015
+ # dimensions for each image, so just checking the first image
1016
+ # is not _exactly_ correct, but it is simple.
1017
+ while isinstance(image, list):
1018
+ image = image[0]
1019
+
1020
+ if height is None:
1021
+ if isinstance(image, PIL.Image.Image):
1022
+ height = image.height
1023
+ elif isinstance(image, torch.Tensor):
1024
+ height = image.shape[-2]
1025
+
1026
+ # round down to nearest multiple of `self.adapter.downscale_factor`
1027
+ height = (height // self.adapter.downscale_factor) * self.adapter.downscale_factor
1028
+
1029
+ if width is None:
1030
+ if isinstance(image, PIL.Image.Image):
1031
+ width = image.width
1032
+ elif isinstance(image, torch.Tensor):
1033
+ width = image.shape[-1]
1034
+
1035
+ # round down to nearest multiple of `self.adapter.downscale_factor`
1036
+ width = (width // self.adapter.downscale_factor) * self.adapter.downscale_factor
1037
+
1038
+ return height, width
1039
+
1040
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
1041
+ def get_guidance_scale_embedding(
1042
+ self, w: torch.Tensor, embedding_dim: int = 512, dtype: torch.dtype = torch.float32
1043
+ ) -> torch.Tensor:
1044
+ """
1045
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
1046
+
1047
+ Args:
1048
+ w (`torch.Tensor`):
1049
+ Generate embedding vectors with a specified guidance scale to subsequently enrich timestep embeddings.
1050
+ embedding_dim (`int`, *optional*, defaults to 512):
1051
+ Dimension of the embeddings to generate.
1052
+ dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
1053
+ Data type of the generated embeddings.
1054
+
1055
+ Returns:
1056
+ `torch.Tensor`: Embedding vectors with shape `(len(w), embedding_dim)`.
1057
+ """
1058
+ assert len(w.shape) == 1
1059
+ w = w * 1000.0
1060
+
1061
+ half_dim = embedding_dim // 2
1062
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
1063
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
1064
+ emb = w.to(dtype)[:, None] * emb[None, :]
1065
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
1066
+ if embedding_dim % 2 == 1: # zero pad
1067
+ emb = torch.nn.functional.pad(emb, (0, 1))
1068
+ assert emb.shape == (w.shape[0], embedding_dim)
1069
+ return emb
1070
+
1071
+ @property
1072
+ def guidance_scale(self):
1073
+ return self._guidance_scale
1074
+
1075
+ @property
1076
+ def guidance_rescale(self):
1077
+ return self._guidance_rescale
1078
+
1079
+ @property
1080
+ def clip_skip(self):
1081
+ return self._clip_skip
1082
+
1083
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
1084
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
1085
+ # corresponds to doing no classifier free guidance.
1086
+ @property
1087
+ def do_classifier_free_guidance(self):
1088
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
1089
+
1090
+ @property
1091
+ def cross_attention_kwargs(self):
1092
+ return self._cross_attention_kwargs
1093
+
1094
+ @property
1095
+ def denoising_end(self):
1096
+ return self._denoising_end
1097
+
1098
+ @property
1099
+ def denoising_start(self):
1100
+ return self._denoising_start
1101
+
1102
+ @property
1103
+ def num_timesteps(self):
1104
+ return self._num_timesteps
1105
+
1106
+ @property
1107
+ def interrupt(self):
1108
+ return self._interrupt
1109
+
1110
+ @torch.no_grad()
1111
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
1112
+ def __call__(
1113
+ self,
1114
+ prompt: Union[str, List[str]] = None,
1115
+ prompt_2: Optional[Union[str, List[str]]] = None,
1116
+ image: PipelineImageInput = None,
1117
+ height: Optional[int] = None,
1118
+ width: Optional[int] = None,
1119
+ adapter_image: PipelineImageInput = None,
1120
+ strength: float = 0.3,
1121
+ num_inference_steps: int = 50,
1122
+ timesteps: List[int] = None,
1123
+ sigmas: List[float] = None,
1124
+ denoising_start: Optional[float] = None,
1125
+ denoising_end: Optional[float] = None,
1126
+ guidance_scale: float = 5.0,
1127
+ negative_prompt: Optional[Union[str, List[str]]] = None,
1128
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
1129
+ num_images_per_prompt: Optional[int] = 1,
1130
+ eta: float = 0.0,
1131
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
1132
+ latents: Optional[torch.Tensor] = None,
1133
+ prompt_embeds: Optional[torch.Tensor] = None,
1134
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
1135
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
1136
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
1137
+ ip_adapter_image: Optional[PipelineImageInput] = None,
1138
+ ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
1139
+ output_type: Optional[str] = "pil",
1140
+ return_dict: bool = True,
1141
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1142
+ guidance_rescale: float = 0.0,
1143
+ original_size: Tuple[int, int] = None,
1144
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
1145
+ target_size: Tuple[int, int] = None,
1146
+ negative_original_size: Optional[Tuple[int, int]] = None,
1147
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
1148
+ negative_target_size: Optional[Tuple[int, int]] = None,
1149
+ aesthetic_score: float = 6.0,
1150
+ negative_aesthetic_score: float = 2.5,
1151
+ adapter_conditioning_scale: Union[float, List[float]] = 1.0,
1152
+ adapter_conditioning_factor: float = 1.0,
1153
+ clip_skip: Optional[int] = None,
1154
+ callback_on_step_end: Optional[
1155
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
1156
+ ] = None,
1157
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
1158
+ **kwargs,
1159
+ ):
1160
+ r"""
1161
+ Function invoked when calling the pipeline for generation.
1162
+
1163
+ Args:
1164
+ prompt (`str` or `List[str]`, *optional*):
1165
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
1166
+ instead.
1167
+ prompt_2 (`str` or `List[str]`, *optional*):
1168
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
1169
+ used in both text-encoders
1170
+ image (`torch.Tensor` or `PIL.Image.Image` or `np.ndarray` or `List[torch.Tensor]` or `List[PIL.Image.Image]` or `List[np.ndarray]`):
1171
+ The image(s) to modify with the pipeline.
1172
+ strength (`float`, *optional*, defaults to 0.3):
1173
+ Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1. `image`
1174
+ will be used as a starting point, adding more noise to it the larger the `strength`. The number of
1175
+ denoising steps depends on the amount of noise initially added. When `strength` is 1, added noise will
1176
+ be maximum and the denoising process will run for the full number of iterations specified in
1177
+ `num_inference_steps`. A value of 1, therefore, essentially ignores `image`. Note that in the case of
1178
+ `denoising_start` being declared as an integer, the value of `strength` will be ignored.
1179
+ num_inference_steps (`int`, *optional*, defaults to 50):
1180
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
1181
+ expense of slower inference.
1182
+ timesteps (`List[int]`, *optional*):
1183
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
1184
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
1185
+ passed will be used. Must be in descending order.
1186
+ sigmas (`List[float]`, *optional*):
1187
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
1188
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
1189
+ will be used.
1190
+ denoising_start (`float`, *optional*):
1191
+ When specified, indicates the fraction (between 0.0 and 1.0) of the total denoising process to be
1192
+ bypassed before it is initiated. Consequently, the initial part of the denoising process is skipped and
1193
+ it is assumed that the passed `image` is a partly denoised image. Note that when this is specified,
1194
+ strength will be ignored. The `denoising_start` parameter is particularly beneficial when this pipeline
1195
+ is integrated into a "Mixture of Denoisers" multi-pipeline setup, as detailed in [**Refine Image
1196
+ Quality**](https://huggingface.co/docs/diffusers/using-diffusers/sdxl#refine-image-quality).
1197
+ denoising_end (`float`, *optional*):
1198
+ When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
1199
+ completed before it is intentionally prematurely terminated. As a result, the returned sample will
1200
+ still retain a substantial amount of noise (ca. final 20% of timesteps still needed) and should be
1201
+ denoised by a successor pipeline that has `denoising_start` set to 0.8 so that it only denoises the
1202
+ final 20% of the scheduler. The denoising_end parameter should ideally be utilized when this pipeline
1203
+ forms a part of a "Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refine Image
1204
+ Quality**](https://huggingface.co/docs/diffusers/using-diffusers/sdxl#refine-image-quality).
1205
+ guidance_scale (`float`, *optional*, defaults to 7.5):
1206
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
1207
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
1208
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
1209
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
1210
+ usually at the expense of lower image quality.
1211
+ negative_prompt (`str` or `List[str]`, *optional*):
1212
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
1213
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
1214
+ less than `1`).
1215
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
1216
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
1217
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
1218
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1219
+ The number of images to generate per prompt.
1220
+ eta (`float`, *optional*, defaults to 0.0):
1221
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
1222
+ [`schedulers.DDIMScheduler`], will be ignored for others.
1223
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
1224
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
1225
+ to make generation deterministic.
1226
+ latents (`torch.Tensor`, *optional*):
1227
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
1228
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
1229
+ tensor will ge generated by sampling using the supplied random `generator`.
1230
+ prompt_embeds (`torch.Tensor`, *optional*):
1231
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
1232
+ provided, text embeddings will be generated from `prompt` input argument.
1233
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
1234
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
1235
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
1236
+ argument.
1237
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
1238
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
1239
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
1240
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
1241
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
1242
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
1243
+ input argument.
1244
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
1245
+ ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
1246
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
1247
+ IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should
1248
+ contain the negative image embedding if `do_classifier_free_guidance` is set to `True`. If not
1249
+ provided, embeddings are computed from the `ip_adapter_image` input argument.
1250
+ output_type (`str`, *optional*, defaults to `"pil"`):
1251
+ The output format of the generate image. Choose between
1252
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
1253
+ return_dict (`bool`, *optional*, defaults to `True`):
1254
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] instead of a
1255
+ plain tuple.
1256
+ cross_attention_kwargs (`dict`, *optional*):
1257
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
1258
+ `self.processor` in
1259
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1260
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
1261
+ Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
1262
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
1263
+ [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
1264
+ Guidance rescale factor should fix overexposure when using zero terminal SNR.
1265
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1266
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
1267
+ `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
1268
+ explained in section 2.2 of
1269
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1270
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
1271
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
1272
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
1273
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
1274
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1275
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1276
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
1277
+ not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
1278
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1279
+ negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1280
+ To negatively condition the generation process based on a specific image resolution. Part of SDXL's
1281
+ micro-conditioning as explained in section 2.2 of
1282
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1283
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1284
+ negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
1285
+ To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
1286
+ micro-conditioning as explained in section 2.2 of
1287
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1288
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1289
+ negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1290
+ To negatively condition the generation process based on a target image resolution. It should be as same
1291
+ as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
1292
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1293
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1294
+ aesthetic_score (`float`, *optional*, defaults to 6.0):
1295
+ Used to simulate an aesthetic score of the generated image by influencing the positive text condition.
1296
+ 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
+ negative_aesthetic_score (`float`, *optional*, defaults to 2.5):
1299
+ Part of SDXL's micro-conditioning as explained in section 2.2 of
1300
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). Can be used to
1301
+ simulate an aesthetic score of the generated image by influencing the negative text condition.
1302
+ clip_skip (`int`, *optional*):
1303
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
1304
+ the output of the pre-final layer will be used for computing the prompt embeddings.
1305
+ callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
1306
+ A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
1307
+ each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
1308
+ DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
1309
+ list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
1310
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
1311
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
1312
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
1313
+ `._callback_tensor_inputs` attribute of your pipeline class.
1314
+
1315
+ Examples:
1316
+
1317
+ Returns:
1318
+ [`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] or `tuple`:
1319
+ [`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
1320
+ `tuple. When returning a tuple, the first element is a list with the generated images.
1321
+ """
1322
+ height, width = self._default_height_width(height, width, adapter_image)
1323
+ device = self._execution_device
1324
+
1325
+ if isinstance(self.adapter, MultiAdapter):
1326
+ adapter_input = []
1327
+
1328
+ for one_image in adapter_image:
1329
+ one_image = _preprocess_adapter_image(one_image, height, width)
1330
+ one_image = one_image.to(device=device, dtype=self.adapter.dtype)
1331
+ adapter_input.append(one_image)
1332
+ else:
1333
+ adapter_input = _preprocess_adapter_image(adapter_image, height, width)
1334
+ adapter_input = adapter_input.to(device=device, dtype=self.adapter.dtype)
1335
+
1336
+ callback = kwargs.pop("callback", None)
1337
+ callback_steps = kwargs.pop("callback_steps", None)
1338
+
1339
+ if callback is not None:
1340
+ deprecate(
1341
+ "callback",
1342
+ "1.0.0",
1343
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
1344
+ )
1345
+ if callback_steps is not None:
1346
+ deprecate(
1347
+ "callback_steps",
1348
+ "1.0.0",
1349
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
1350
+ )
1351
+
1352
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
1353
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
1354
+
1355
+ # 1. Check inputs. Raise error if not correct
1356
+ self.check_inputs(
1357
+ prompt,
1358
+ prompt_2,
1359
+ strength,
1360
+ num_inference_steps,
1361
+ callback_steps,
1362
+ negative_prompt,
1363
+ negative_prompt_2,
1364
+ prompt_embeds,
1365
+ negative_prompt_embeds,
1366
+ ip_adapter_image,
1367
+ ip_adapter_image_embeds,
1368
+ callback_on_step_end_tensor_inputs,
1369
+ )
1370
+
1371
+ self._guidance_scale = guidance_scale
1372
+ self._guidance_rescale = guidance_rescale
1373
+ self._clip_skip = clip_skip
1374
+ self._cross_attention_kwargs = cross_attention_kwargs
1375
+ self._denoising_end = denoising_end
1376
+ self._denoising_start = denoising_start
1377
+ self._interrupt = False
1378
+
1379
+ # 2. Define call parameters
1380
+ if prompt is not None and isinstance(prompt, str):
1381
+ batch_size = 1
1382
+ elif prompt is not None and isinstance(prompt, list):
1383
+ batch_size = len(prompt)
1384
+ else:
1385
+ batch_size = prompt_embeds.shape[0]
1386
+
1387
+ device = self._execution_device
1388
+
1389
+ # 3. Encode input prompt
1390
+ text_encoder_lora_scale = (
1391
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
1392
+ )
1393
+ (
1394
+ prompt_embeds,
1395
+ negative_prompt_embeds,
1396
+ pooled_prompt_embeds,
1397
+ negative_pooled_prompt_embeds,
1398
+ ) = self.encode_prompt(
1399
+ prompt=prompt,
1400
+ prompt_2=prompt_2,
1401
+ device=device,
1402
+ num_images_per_prompt=num_images_per_prompt,
1403
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1404
+ negative_prompt=negative_prompt,
1405
+ negative_prompt_2=negative_prompt_2,
1406
+ prompt_embeds=prompt_embeds,
1407
+ negative_prompt_embeds=negative_prompt_embeds,
1408
+ pooled_prompt_embeds=pooled_prompt_embeds,
1409
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
1410
+ lora_scale=text_encoder_lora_scale,
1411
+ clip_skip=self.clip_skip,
1412
+ )
1413
+
1414
+ # 4. Preprocess image
1415
+ image = self.image_processor.preprocess(image)
1416
+
1417
+ # 5. Prepare timesteps
1418
+ def denoising_value_valid(dnv):
1419
+ return isinstance(dnv, float) and 0 < dnv < 1
1420
+
1421
+ timesteps, num_inference_steps = retrieve_timesteps(
1422
+ self.scheduler, num_inference_steps, device, timesteps, sigmas
1423
+ )
1424
+ timesteps, num_inference_steps = self.get_timesteps(
1425
+ num_inference_steps,
1426
+ strength,
1427
+ device,
1428
+ denoising_start=self.denoising_start if denoising_value_valid(self.denoising_start) else None,
1429
+ )
1430
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
1431
+
1432
+ add_noise = True if self.denoising_start is None else False
1433
+
1434
+ # 6. Prepare latent variables
1435
+ if latents is None:
1436
+ latents = self.prepare_latents(
1437
+ image,
1438
+ latent_timestep,
1439
+ batch_size,
1440
+ num_images_per_prompt,
1441
+ prompt_embeds.dtype,
1442
+ device,
1443
+ generator,
1444
+ add_noise,
1445
+ )
1446
+ # 7. Prepare extra step kwargs.
1447
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1448
+
1449
+ height, width = latents.shape[-2:]
1450
+ height = height * self.vae_scale_factor
1451
+ width = width * self.vae_scale_factor
1452
+
1453
+ original_size = original_size or (height, width)
1454
+ target_size = target_size or (height, width)
1455
+
1456
+ # 8. Prepare added time ids & embeddings
1457
+ # adapter_input = adapter_input.type(latents.dtype)
1458
+ if isinstance(self.adapter, MultiAdapter):
1459
+ adapter_state = self.adapter(adapter_input, adapter_conditioning_scale)
1460
+ for k, v in enumerate(adapter_state):
1461
+ adapter_state[k] = v
1462
+ else:
1463
+ adapter_state = self.adapter(adapter_input)
1464
+ for k, v in enumerate(adapter_state):
1465
+ adapter_state[k] = v * adapter_conditioning_scale
1466
+ if num_images_per_prompt > 1:
1467
+ for k, v in enumerate(adapter_state):
1468
+ adapter_state[k] = v.repeat(num_images_per_prompt, 1, 1, 1)
1469
+ if self.do_classifier_free_guidance:
1470
+ for k, v in enumerate(adapter_state):
1471
+ adapter_state[k] = torch.cat([v] * 2, dim=0)
1472
+
1473
+ if negative_original_size is None:
1474
+ negative_original_size = original_size
1475
+ if negative_target_size is None:
1476
+ negative_target_size = target_size
1477
+
1478
+ add_text_embeds = pooled_prompt_embeds
1479
+ if self.text_encoder_2 is None:
1480
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
1481
+ else:
1482
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
1483
+
1484
+ add_time_ids, add_neg_time_ids = self._get_add_time_ids(
1485
+ original_size,
1486
+ crops_coords_top_left,
1487
+ target_size,
1488
+ aesthetic_score,
1489
+ negative_aesthetic_score,
1490
+ negative_original_size,
1491
+ negative_crops_coords_top_left,
1492
+ negative_target_size,
1493
+ dtype=prompt_embeds.dtype,
1494
+ text_encoder_projection_dim=text_encoder_projection_dim,
1495
+ )
1496
+ add_time_ids = add_time_ids.repeat(batch_size * num_images_per_prompt, 1)
1497
+
1498
+ if self.do_classifier_free_guidance:
1499
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
1500
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
1501
+ add_neg_time_ids = add_neg_time_ids.repeat(batch_size * num_images_per_prompt, 1)
1502
+ add_time_ids = torch.cat([add_neg_time_ids, add_time_ids], dim=0)
1503
+
1504
+ prompt_embeds = prompt_embeds.to(device)
1505
+ add_text_embeds = add_text_embeds.to(device)
1506
+ add_time_ids = add_time_ids.to(device)
1507
+
1508
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1509
+ image_embeds = self.prepare_ip_adapter_image_embeds(
1510
+ ip_adapter_image,
1511
+ ip_adapter_image_embeds,
1512
+ device,
1513
+ batch_size * num_images_per_prompt,
1514
+ self.do_classifier_free_guidance,
1515
+ )
1516
+
1517
+ # 9. Denoising loop
1518
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
1519
+
1520
+ # 9.1 Apply denoising_end
1521
+ if (
1522
+ self.denoising_end is not None
1523
+ and self.denoising_start is not None
1524
+ and denoising_value_valid(self.denoising_end)
1525
+ and denoising_value_valid(self.denoising_start)
1526
+ and self.denoising_start >= self.denoising_end
1527
+ ):
1528
+ raise ValueError(
1529
+ f"`denoising_start`: {self.denoising_start} cannot be larger than or equal to `denoising_end`: "
1530
+ + f" {self.denoising_end} when using type float."
1531
+ )
1532
+ elif self.denoising_end is not None and denoising_value_valid(self.denoising_end):
1533
+ discrete_timestep_cutoff = int(
1534
+ round(
1535
+ self.scheduler.config.num_train_timesteps
1536
+ - (self.denoising_end * self.scheduler.config.num_train_timesteps)
1537
+ )
1538
+ )
1539
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
1540
+ timesteps = timesteps[:num_inference_steps]
1541
+
1542
+ # 9.2 Optionally get Guidance Scale Embedding
1543
+ timestep_cond = None
1544
+ if self.unet.config.time_cond_proj_dim is not None:
1545
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
1546
+ timestep_cond = self.get_guidance_scale_embedding(
1547
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
1548
+ ).to(device=device, dtype=latents.dtype)
1549
+
1550
+ self._num_timesteps = len(timesteps)
1551
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1552
+ for i, t in enumerate(timesteps):
1553
+ if self.interrupt:
1554
+ continue
1555
+
1556
+ # expand the latents if we are doing classifier free guidance
1557
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1558
+
1559
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1560
+
1561
+ # predict the noise residual
1562
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
1563
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1564
+ added_cond_kwargs["image_embeds"] = image_embeds
1565
+
1566
+ if i < int(num_inference_steps * adapter_conditioning_factor):
1567
+ down_intrablock_additional_residuals = [state.clone() for state in adapter_state]
1568
+ else:
1569
+ down_intrablock_additional_residuals = None
1570
+
1571
+ noise_pred = self.unet(
1572
+ latent_model_input,
1573
+ t,
1574
+ encoder_hidden_states=prompt_embeds,
1575
+ timestep_cond=timestep_cond,
1576
+ cross_attention_kwargs=self.cross_attention_kwargs,
1577
+ added_cond_kwargs=added_cond_kwargs,
1578
+ return_dict=False,
1579
+ down_intrablock_additional_residuals=down_intrablock_additional_residuals,
1580
+ )[0]
1581
+
1582
+ # perform guidance
1583
+ if self.do_classifier_free_guidance:
1584
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1585
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
1586
+
1587
+ if self.do_classifier_free_guidance and self.guidance_rescale > 0.0:
1588
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1589
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale)
1590
+
1591
+ # compute the previous noisy sample x_t -> x_t-1
1592
+ latents_dtype = latents.dtype
1593
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1594
+ if latents.dtype != latents_dtype:
1595
+ if torch.backends.mps.is_available():
1596
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1597
+ latents = latents.to(latents_dtype)
1598
+
1599
+ if callback_on_step_end is not None:
1600
+ callback_kwargs = {}
1601
+ for k in callback_on_step_end_tensor_inputs:
1602
+ callback_kwargs[k] = locals()[k]
1603
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1604
+
1605
+ latents = callback_outputs.pop("latents", latents)
1606
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1607
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1608
+ add_text_embeds = callback_outputs.pop("add_text_embeds", add_text_embeds)
1609
+ negative_pooled_prompt_embeds = callback_outputs.pop(
1610
+ "negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
1611
+ )
1612
+ add_time_ids = callback_outputs.pop("add_time_ids", add_time_ids)
1613
+ add_neg_time_ids = callback_outputs.pop("add_neg_time_ids", add_neg_time_ids)
1614
+
1615
+ # call the callback, if provided
1616
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1617
+ progress_bar.update()
1618
+ if callback is not None and i % callback_steps == 0:
1619
+ step_idx = i // getattr(self.scheduler, "order", 1)
1620
+ callback(step_idx, t, latents)
1621
+
1622
+ if XLA_AVAILABLE:
1623
+ xm.mark_step()
1624
+
1625
+ if not output_type == "latent":
1626
+ # make sure the VAE is in float32 mode, as it overflows in float16
1627
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
1628
+
1629
+ if needs_upcasting:
1630
+ self.upcast_vae()
1631
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1632
+ elif latents.dtype != self.vae.dtype:
1633
+ if torch.backends.mps.is_available():
1634
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1635
+ self.vae = self.vae.to(latents.dtype)
1636
+
1637
+ # unscale/denormalize the latents
1638
+ # denormalize with the mean and std if available and not None
1639
+ has_latents_mean = hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None
1640
+ has_latents_std = hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None
1641
+ if has_latents_mean and has_latents_std:
1642
+ latents_mean = (
1643
+ torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1644
+ )
1645
+ latents_std = (
1646
+ torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1647
+ )
1648
+ latents = latents * latents_std / self.vae.config.scaling_factor + latents_mean
1649
+ else:
1650
+ latents = latents / self.vae.config.scaling_factor
1651
+
1652
+ image = self.vae.decode(latents, return_dict=False)[0]
1653
+
1654
+ # cast back to fp16 if needed
1655
+ if needs_upcasting:
1656
+ self.vae.to(dtype=torch.float16)
1657
+ else:
1658
+ image = latents
1659
+
1660
+ # apply watermark if available
1661
+ if self.watermark is not None:
1662
+ image = self.watermark.apply_watermark(image)
1663
+
1664
+ image = self.image_processor.postprocess(image, output_type=output_type)
1665
+
1666
+ # Offload all models
1667
+ self.maybe_free_model_hooks()
1668
+
1669
+ if not return_dict:
1670
+ return (image,)
1671
+
1672
+ return StableDiffusionXLPipelineOutput(images=image)
pipelines/pipeline_sdxl_adapter_inpaint.py ADDED
@@ -0,0 +1,1863 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
17
+
18
+ import numpy as np
19
+ import PIL.Image
20
+ import torch
21
+ from transformers import (
22
+ CLIPImageProcessor,
23
+ CLIPTextModel,
24
+ CLIPTextModelWithProjection,
25
+ CLIPTokenizer,
26
+ CLIPVisionModelWithProjection,
27
+ )
28
+
29
+ from diffusers.callbacks import (
30
+ MultiPipelineCallbacks,
31
+ PipelineCallback,
32
+ )
33
+
34
+ from diffusers.image_processor import (
35
+ PipelineImageInput,
36
+ VaeImageProcessor,
37
+ )
38
+
39
+ from diffusers.loaders import (
40
+ FromSingleFileMixin,
41
+ IPAdapterMixin,
42
+ StableDiffusionXLLoraLoaderMixin,
43
+ TextualInversionLoaderMixin,
44
+ )
45
+
46
+ from diffusers.models import (
47
+ AutoencoderKL,
48
+ ImageProjection,
49
+ MultiAdapter,
50
+ T2IAdapter,
51
+ UNet2DConditionModel,
52
+ )
53
+
54
+ from diffusers.models.attention_processor import (
55
+ AttnProcessor2_0,
56
+ XFormersAttnProcessor,
57
+ )
58
+
59
+ from diffusers.models.lora import (
60
+ adjust_lora_scale_text_encoder,
61
+ )
62
+
63
+ from diffusers.schedulers import (
64
+ KarrasDiffusionSchedulers,
65
+ )
66
+
67
+ from diffusers.utils import (
68
+ PIL_INTERPOLATION,
69
+ USE_PEFT_BACKEND,
70
+ deprecate,
71
+ is_invisible_watermark_available,
72
+ is_torch_xla_available,
73
+ logging,
74
+ replace_example_docstring,
75
+ scale_lora_layers,
76
+ unscale_lora_layers,
77
+ )
78
+
79
+ from diffusers.utils.torch_utils import (
80
+ randn_tensor,
81
+ )
82
+
83
+ from diffusers.pipelines.pipeline_utils import (
84
+ DiffusionPipeline,
85
+ StableDiffusionMixin,
86
+ )
87
+
88
+ from diffusers.pipelines.stable_diffusion_xl.pipeline_output import (
89
+ StableDiffusionXLPipelineOutput,
90
+ )
91
+
92
+ if is_invisible_watermark_available():
93
+ from diffusers.pipelines.stable_diffusion_xl.watermark import (
94
+ StableDiffusionXLWatermarker,
95
+ )
96
+
97
+ if is_torch_xla_available():
98
+ import torch_xla.core.xla_model as xm
99
+
100
+ XLA_AVAILABLE = True
101
+ else:
102
+ XLA_AVAILABLE = False
103
+
104
+
105
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
106
+
107
+
108
+ EXAMPLE_DOC_STRING = """
109
+ Examples:
110
+ ```py
111
+ >>> import torch
112
+ >>> from diffusers import StableDiffusionXLInpaintPipeline
113
+ >>> from diffusers.utils import load_image
114
+
115
+ >>> pipe = StableDiffusionXLInpaintPipeline.from_pretrained(
116
+ ... "stabilityai/stable-diffusion-xl-base-1.0",
117
+ ... torch_dtype=torch.float16,
118
+ ... variant="fp16",
119
+ ... use_safetensors=True,
120
+ ... )
121
+ >>> pipe.to("cuda")
122
+
123
+ >>> img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
124
+ >>> mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
125
+
126
+ >>> init_image = load_image(img_url).convert("RGB")
127
+ >>> mask_image = load_image(mask_url).convert("RGB")
128
+
129
+ >>> prompt = "A majestic tiger sitting on a bench"
130
+ >>> image = pipe(
131
+ ... prompt=prompt, image=init_image, mask_image=mask_image, num_inference_steps=50, strength=0.80
132
+ ... ).images[0]
133
+ ```
134
+ """
135
+
136
+
137
+ def _preprocess_adapter_image(image, height, width):
138
+ if isinstance(image, torch.Tensor):
139
+ return image
140
+ elif isinstance(image, PIL.Image.Image):
141
+ image = [image]
142
+
143
+ if isinstance(image[0], PIL.Image.Image):
144
+ image = [np.array(i.resize((width, height), resample=PIL_INTERPOLATION["lanczos"])) for i in image]
145
+ image = [
146
+ i[None, ..., None] if i.ndim == 2 else i[None, ...] for i in image
147
+ ] # expand [h, w] or [h, w, c] to [b, h, w, c]
148
+ image = np.concatenate(image, axis=0)
149
+ image = np.array(image).astype(np.float32) / 255.0
150
+ image = image.transpose(0, 3, 1, 2)
151
+ image = torch.from_numpy(image)
152
+ elif isinstance(image[0], torch.Tensor):
153
+ if image[0].ndim == 3:
154
+ image = torch.stack(image, dim=0)
155
+ elif image[0].ndim == 4:
156
+ image = torch.cat(image, dim=0)
157
+ else:
158
+ raise ValueError(
159
+ f"Invalid image tensor! Expecting image tensor with 3 or 4 dimension, but recive: {image[0].ndim}"
160
+ )
161
+ return image
162
+
163
+
164
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
165
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
166
+ """
167
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
168
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
169
+ """
170
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
171
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
172
+ # rescale the results from guidance (fixes overexposure)
173
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
174
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
175
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
176
+ return noise_cfg
177
+
178
+
179
+ def mask_pil_to_torch(mask, height, width):
180
+ # preprocess mask
181
+ if isinstance(mask, (PIL.Image.Image, np.ndarray)):
182
+ mask = [mask]
183
+
184
+ if isinstance(mask, list) and isinstance(mask[0], PIL.Image.Image):
185
+ mask = [i.resize((width, height), resample=PIL.Image.LANCZOS) for i in mask]
186
+ mask = np.concatenate([np.array(m.convert("L"))[None, None, :] for m in mask], axis=0)
187
+ mask = mask.astype(np.float32) / 255.0
188
+ elif isinstance(mask, list) and isinstance(mask[0], np.ndarray):
189
+ mask = np.concatenate([m[None, None, :] for m in mask], axis=0)
190
+
191
+ mask = torch.from_numpy(mask)
192
+ return mask
193
+
194
+
195
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
196
+ def retrieve_latents(
197
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
198
+ ):
199
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
200
+ return encoder_output.latent_dist.sample(generator)
201
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
202
+ return encoder_output.latent_dist.mode()
203
+ elif hasattr(encoder_output, "latents"):
204
+ return encoder_output.latents
205
+ else:
206
+ raise AttributeError("Could not access latents of provided encoder_output")
207
+
208
+
209
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
210
+ def retrieve_timesteps(
211
+ scheduler,
212
+ num_inference_steps: Optional[int] = None,
213
+ device: Optional[Union[str, torch.device]] = None,
214
+ timesteps: Optional[List[int]] = None,
215
+ sigmas: Optional[List[float]] = None,
216
+ **kwargs,
217
+ ):
218
+ """
219
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
220
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
221
+
222
+ Args:
223
+ scheduler (`SchedulerMixin`):
224
+ The scheduler to get timesteps from.
225
+ num_inference_steps (`int`):
226
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
227
+ must be `None`.
228
+ device (`str` or `torch.device`, *optional*):
229
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
230
+ timesteps (`List[int]`, *optional*):
231
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
232
+ `num_inference_steps` and `sigmas` must be `None`.
233
+ sigmas (`List[float]`, *optional*):
234
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
235
+ `num_inference_steps` and `timesteps` must be `None`.
236
+
237
+ Returns:
238
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
239
+ second element is the number of inference steps.
240
+ """
241
+ if timesteps is not None and sigmas is not None:
242
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
243
+ if timesteps is not None:
244
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
245
+ if not accepts_timesteps:
246
+ raise ValueError(
247
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
248
+ f" timestep schedules. Please check whether you are using the correct scheduler."
249
+ )
250
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
251
+ timesteps = scheduler.timesteps
252
+ num_inference_steps = len(timesteps)
253
+ elif sigmas is not None:
254
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
255
+ if not accept_sigmas:
256
+ raise ValueError(
257
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
258
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
259
+ )
260
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
261
+ timesteps = scheduler.timesteps
262
+ num_inference_steps = len(timesteps)
263
+ else:
264
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
265
+ timesteps = scheduler.timesteps
266
+ return timesteps, num_inference_steps
267
+
268
+
269
+ class StableDiffusionXLInpaintPipeline(
270
+ DiffusionPipeline,
271
+ StableDiffusionMixin,
272
+ TextualInversionLoaderMixin,
273
+ StableDiffusionXLLoraLoaderMixin,
274
+ FromSingleFileMixin,
275
+ IPAdapterMixin,
276
+ ):
277
+ r"""
278
+ Pipeline for text-to-image generation using Stable Diffusion XL.
279
+
280
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
281
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
282
+
283
+ The pipeline also inherits the following loading methods:
284
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
285
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
286
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
287
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
288
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
289
+
290
+ Args:
291
+ vae ([`AutoencoderKL`]):
292
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
293
+ text_encoder ([`CLIPTextModel`]):
294
+ Frozen text-encoder. Stable Diffusion XL uses the text portion of
295
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
296
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
297
+ text_encoder_2 ([` CLIPTextModelWithProjection`]):
298
+ Second frozen text-encoder. Stable Diffusion XL uses the text and pool portion of
299
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
300
+ specifically the
301
+ [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)
302
+ variant.
303
+ tokenizer (`CLIPTokenizer`):
304
+ Tokenizer of class
305
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
306
+ tokenizer_2 (`CLIPTokenizer`):
307
+ Second Tokenizer of class
308
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
309
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
310
+ scheduler ([`SchedulerMixin`]):
311
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
312
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
313
+ requires_aesthetics_score (`bool`, *optional*, defaults to `"False"`):
314
+ Whether the `unet` requires a aesthetic_score condition to be passed during inference. Also see the config
315
+ of `stabilityai/stable-diffusion-xl-refiner-1-0`.
316
+ force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"True"`):
317
+ Whether the negative prompt embeddings shall be forced to always be set to 0. Also see the config of
318
+ `stabilityai/stable-diffusion-xl-base-1-0`.
319
+ add_watermarker (`bool`, *optional*):
320
+ Whether to use the [invisible_watermark library](https://github.com/ShieldMnt/invisible-watermark/) to
321
+ watermark output images. If not defined, it will default to True if the package is installed, otherwise no
322
+ watermarker will be used.
323
+ """
324
+
325
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->image_encoder->unet->vae"
326
+
327
+ _optional_components = [
328
+ "tokenizer",
329
+ "tokenizer_2",
330
+ "text_encoder",
331
+ "text_encoder_2",
332
+ "image_encoder",
333
+ "feature_extractor",
334
+ ]
335
+ _callback_tensor_inputs = [
336
+ "latents",
337
+ "prompt_embeds",
338
+ "negative_prompt_embeds",
339
+ "add_text_embeds",
340
+ "add_time_ids",
341
+ "negative_pooled_prompt_embeds",
342
+ "add_neg_time_ids",
343
+ "mask",
344
+ "masked_image_latents",
345
+ ]
346
+
347
+ def __init__(
348
+ self,
349
+ vae: AutoencoderKL,
350
+ text_encoder: CLIPTextModel,
351
+ text_encoder_2: CLIPTextModelWithProjection,
352
+ tokenizer: CLIPTokenizer,
353
+ tokenizer_2: CLIPTokenizer,
354
+ unet: UNet2DConditionModel,
355
+ adapter: Union[T2IAdapter, MultiAdapter, List[T2IAdapter]],
356
+ scheduler: KarrasDiffusionSchedulers,
357
+ image_encoder: CLIPVisionModelWithProjection = None,
358
+ feature_extractor: CLIPImageProcessor = None,
359
+ requires_aesthetics_score: bool = False,
360
+ force_zeros_for_empty_prompt: bool = True,
361
+ add_watermarker: Optional[bool] = None,
362
+ ):
363
+ super().__init__()
364
+
365
+ self.register_modules(
366
+ vae=vae,
367
+ text_encoder=text_encoder,
368
+ text_encoder_2=text_encoder_2,
369
+ tokenizer=tokenizer,
370
+ tokenizer_2=tokenizer_2,
371
+ unet=unet,
372
+ adapter=adapter,
373
+ image_encoder=image_encoder,
374
+ feature_extractor=feature_extractor,
375
+ scheduler=scheduler,
376
+ )
377
+ self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
378
+ self.register_to_config(requires_aesthetics_score=requires_aesthetics_score)
379
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
380
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
381
+ self.mask_processor = VaeImageProcessor(
382
+ vae_scale_factor=self.vae_scale_factor, do_normalize=False, do_binarize=True, do_convert_grayscale=True
383
+ )
384
+
385
+ add_watermarker = add_watermarker if add_watermarker is not None else is_invisible_watermark_available()
386
+
387
+ if add_watermarker:
388
+ self.watermark = StableDiffusionXLWatermarker()
389
+ else:
390
+ self.watermark = None
391
+
392
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
393
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
394
+ dtype = next(self.image_encoder.parameters()).dtype
395
+
396
+ if not isinstance(image, torch.Tensor):
397
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
398
+
399
+ image = image.to(device=device, dtype=dtype)
400
+ if output_hidden_states:
401
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
402
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
403
+ uncond_image_enc_hidden_states = self.image_encoder(
404
+ torch.zeros_like(image), output_hidden_states=True
405
+ ).hidden_states[-2]
406
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
407
+ num_images_per_prompt, dim=0
408
+ )
409
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
410
+ else:
411
+ image_embeds = self.image_encoder(image).image_embeds
412
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
413
+ uncond_image_embeds = torch.zeros_like(image_embeds)
414
+
415
+ return image_embeds, uncond_image_embeds
416
+
417
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
418
+ def prepare_ip_adapter_image_embeds(
419
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
420
+ ):
421
+ image_embeds = []
422
+ if do_classifier_free_guidance:
423
+ negative_image_embeds = []
424
+ if ip_adapter_image_embeds is None:
425
+ if not isinstance(ip_adapter_image, list):
426
+ ip_adapter_image = [ip_adapter_image]
427
+
428
+ if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
429
+ raise ValueError(
430
+ 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."
431
+ )
432
+
433
+ for single_ip_adapter_image, image_proj_layer in zip(
434
+ ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
435
+ ):
436
+ output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
437
+ single_image_embeds, single_negative_image_embeds = self.encode_image(
438
+ single_ip_adapter_image, device, 1, output_hidden_state
439
+ )
440
+
441
+ image_embeds.append(single_image_embeds[None, :])
442
+ if do_classifier_free_guidance:
443
+ negative_image_embeds.append(single_negative_image_embeds[None, :])
444
+ else:
445
+ for single_image_embeds in ip_adapter_image_embeds:
446
+ if do_classifier_free_guidance:
447
+ single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
448
+ negative_image_embeds.append(single_negative_image_embeds)
449
+ image_embeds.append(single_image_embeds)
450
+
451
+ ip_adapter_image_embeds = []
452
+ for i, single_image_embeds in enumerate(image_embeds):
453
+ single_image_embeds = torch.cat([single_image_embeds] * num_images_per_prompt, dim=0)
454
+ if do_classifier_free_guidance:
455
+ single_negative_image_embeds = torch.cat([negative_image_embeds[i]] * num_images_per_prompt, dim=0)
456
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds], dim=0)
457
+
458
+ single_image_embeds = single_image_embeds.to(device=device)
459
+ ip_adapter_image_embeds.append(single_image_embeds)
460
+
461
+ return ip_adapter_image_embeds
462
+
463
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.encode_prompt
464
+ def encode_prompt(
465
+ self,
466
+ prompt: str,
467
+ prompt_2: Optional[str] = None,
468
+ device: Optional[torch.device] = None,
469
+ num_images_per_prompt: int = 1,
470
+ do_classifier_free_guidance: bool = True,
471
+ negative_prompt: Optional[str] = None,
472
+ negative_prompt_2: Optional[str] = None,
473
+ prompt_embeds: Optional[torch.Tensor] = None,
474
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
475
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
476
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
477
+ lora_scale: Optional[float] = None,
478
+ clip_skip: Optional[int] = None,
479
+ ):
480
+ r"""
481
+ Encodes the prompt into text encoder hidden states.
482
+
483
+ Args:
484
+ prompt (`str` or `List[str]`, *optional*):
485
+ prompt to be encoded
486
+ prompt_2 (`str` or `List[str]`, *optional*):
487
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
488
+ used in both text-encoders
489
+ device: (`torch.device`):
490
+ torch device
491
+ num_images_per_prompt (`int`):
492
+ number of images that should be generated per prompt
493
+ do_classifier_free_guidance (`bool`):
494
+ whether to use classifier free guidance or not
495
+ negative_prompt (`str` or `List[str]`, *optional*):
496
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
497
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
498
+ less than `1`).
499
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
500
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
501
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
502
+ prompt_embeds (`torch.Tensor`, *optional*):
503
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
504
+ provided, text embeddings will be generated from `prompt` input argument.
505
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
506
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
507
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
508
+ argument.
509
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
510
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
511
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
512
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
513
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
514
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
515
+ input argument.
516
+ lora_scale (`float`, *optional*):
517
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
518
+ clip_skip (`int`, *optional*):
519
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
520
+ the output of the pre-final layer will be used for computing the prompt embeddings.
521
+ """
522
+ device = device or self._execution_device
523
+
524
+ # set lora scale so that monkey patched LoRA
525
+ # function of text encoder can correctly access it
526
+ if lora_scale is not None and isinstance(self, StableDiffusionXLLoraLoaderMixin):
527
+ self._lora_scale = lora_scale
528
+
529
+ # dynamically adjust the LoRA scale
530
+ if self.text_encoder is not None:
531
+ if not USE_PEFT_BACKEND:
532
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
533
+ else:
534
+ scale_lora_layers(self.text_encoder, lora_scale)
535
+
536
+ if self.text_encoder_2 is not None:
537
+ if not USE_PEFT_BACKEND:
538
+ adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
539
+ else:
540
+ scale_lora_layers(self.text_encoder_2, lora_scale)
541
+
542
+ prompt = [prompt] if isinstance(prompt, str) else prompt
543
+
544
+ if prompt is not None:
545
+ batch_size = len(prompt)
546
+ else:
547
+ batch_size = prompt_embeds.shape[0]
548
+
549
+ # Define tokenizers and text encoders
550
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
551
+ text_encoders = (
552
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
553
+ )
554
+
555
+ if prompt_embeds is None:
556
+ prompt_2 = prompt_2 or prompt
557
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
558
+
559
+ # textual inversion: process multi-vector tokens if necessary
560
+ prompt_embeds_list = []
561
+ prompts = [prompt, prompt_2]
562
+ for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
563
+ if isinstance(self, TextualInversionLoaderMixin):
564
+ prompt = self.maybe_convert_prompt(prompt, tokenizer)
565
+
566
+ text_inputs = tokenizer(
567
+ prompt,
568
+ padding="max_length",
569
+ max_length=tokenizer.model_max_length,
570
+ truncation=True,
571
+ return_tensors="pt",
572
+ )
573
+
574
+ text_input_ids = text_inputs.input_ids
575
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
576
+
577
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
578
+ text_input_ids, untruncated_ids
579
+ ):
580
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
581
+ logger.warning(
582
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
583
+ f" {tokenizer.model_max_length} tokens: {removed_text}"
584
+ )
585
+
586
+ prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=True)
587
+
588
+ # We are only ALWAYS interested in the pooled output of the final text encoder
589
+ pooled_prompt_embeds = prompt_embeds[0]
590
+ if clip_skip is None:
591
+ prompt_embeds = prompt_embeds.hidden_states[-2]
592
+ else:
593
+ # "2" because SDXL always indexes from the penultimate layer.
594
+ prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
595
+
596
+ prompt_embeds_list.append(prompt_embeds)
597
+
598
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
599
+
600
+ # get unconditional embeddings for classifier free guidance
601
+ zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
602
+ if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
603
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
604
+ negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
605
+ elif do_classifier_free_guidance and negative_prompt_embeds is None:
606
+ negative_prompt = negative_prompt or ""
607
+ negative_prompt_2 = negative_prompt_2 or negative_prompt
608
+
609
+ # normalize str to list
610
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
611
+ negative_prompt_2 = (
612
+ batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
613
+ )
614
+
615
+ uncond_tokens: List[str]
616
+ if prompt is not None and type(prompt) is not type(negative_prompt):
617
+ raise TypeError(
618
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
619
+ f" {type(prompt)}."
620
+ )
621
+ elif batch_size != len(negative_prompt):
622
+ raise ValueError(
623
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
624
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
625
+ " the batch size of `prompt`."
626
+ )
627
+ else:
628
+ uncond_tokens = [negative_prompt, negative_prompt_2]
629
+
630
+ negative_prompt_embeds_list = []
631
+ for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
632
+ if isinstance(self, TextualInversionLoaderMixin):
633
+ negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
634
+
635
+ max_length = prompt_embeds.shape[1]
636
+ uncond_input = tokenizer(
637
+ negative_prompt,
638
+ padding="max_length",
639
+ max_length=max_length,
640
+ truncation=True,
641
+ return_tensors="pt",
642
+ )
643
+
644
+ negative_prompt_embeds = text_encoder(
645
+ uncond_input.input_ids.to(device),
646
+ output_hidden_states=True,
647
+ )
648
+ # We are only ALWAYS interested in the pooled output of the final text encoder
649
+ negative_pooled_prompt_embeds = negative_prompt_embeds[0]
650
+ negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
651
+
652
+ negative_prompt_embeds_list.append(negative_prompt_embeds)
653
+
654
+ negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
655
+
656
+ if self.text_encoder_2 is not None:
657
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
658
+ else:
659
+ prompt_embeds = prompt_embeds.to(dtype=self.unet.dtype, device=device)
660
+
661
+ bs_embed, seq_len, _ = prompt_embeds.shape
662
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
663
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
664
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
665
+
666
+ if do_classifier_free_guidance:
667
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
668
+ seq_len = negative_prompt_embeds.shape[1]
669
+
670
+ if self.text_encoder_2 is not None:
671
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
672
+ else:
673
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.unet.dtype, device=device)
674
+
675
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
676
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
677
+
678
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
679
+ bs_embed * num_images_per_prompt, -1
680
+ )
681
+ if do_classifier_free_guidance:
682
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
683
+ bs_embed * num_images_per_prompt, -1
684
+ )
685
+
686
+ if self.text_encoder is not None:
687
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
688
+ # Retrieve the original scale by scaling back the LoRA layers
689
+ unscale_lora_layers(self.text_encoder, lora_scale)
690
+
691
+ if self.text_encoder_2 is not None:
692
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
693
+ # Retrieve the original scale by scaling back the LoRA layers
694
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
695
+
696
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
697
+
698
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
699
+ def prepare_extra_step_kwargs(self, generator, eta):
700
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
701
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
702
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
703
+ # and should be between [0, 1]
704
+
705
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
706
+ extra_step_kwargs = {}
707
+ if accepts_eta:
708
+ extra_step_kwargs["eta"] = eta
709
+
710
+ # check if the scheduler accepts generator
711
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
712
+ if accepts_generator:
713
+ extra_step_kwargs["generator"] = generator
714
+ return extra_step_kwargs
715
+
716
+ def check_inputs(
717
+ self,
718
+ prompt,
719
+ prompt_2,
720
+ image,
721
+ mask_image,
722
+ height,
723
+ width,
724
+ strength,
725
+ callback_steps,
726
+ output_type,
727
+ negative_prompt=None,
728
+ negative_prompt_2=None,
729
+ prompt_embeds=None,
730
+ negative_prompt_embeds=None,
731
+ ip_adapter_image=None,
732
+ ip_adapter_image_embeds=None,
733
+ callback_on_step_end_tensor_inputs=None,
734
+ padding_mask_crop=None,
735
+ ):
736
+ if strength < 0 or strength > 1:
737
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
738
+
739
+ if height % 8 != 0 or width % 8 != 0:
740
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
741
+
742
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
743
+ raise ValueError(
744
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
745
+ f" {type(callback_steps)}."
746
+ )
747
+
748
+ if callback_on_step_end_tensor_inputs is not None and not all(
749
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
750
+ ):
751
+ raise ValueError(
752
+ 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]}"
753
+ )
754
+
755
+ if prompt is not None and prompt_embeds is not None:
756
+ raise ValueError(
757
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
758
+ " only forward one of the two."
759
+ )
760
+ elif prompt_2 is not None and prompt_embeds is not None:
761
+ raise ValueError(
762
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
763
+ " only forward one of the two."
764
+ )
765
+ elif prompt is None and prompt_embeds is None:
766
+ raise ValueError(
767
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
768
+ )
769
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
770
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
771
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
772
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
773
+
774
+ if negative_prompt is not None and negative_prompt_embeds is not None:
775
+ raise ValueError(
776
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
777
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
778
+ )
779
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
780
+ raise ValueError(
781
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
782
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
783
+ )
784
+
785
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
786
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
787
+ raise ValueError(
788
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
789
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
790
+ f" {negative_prompt_embeds.shape}."
791
+ )
792
+ if padding_mask_crop is not None:
793
+ if not isinstance(image, PIL.Image.Image):
794
+ raise ValueError(
795
+ f"The image should be a PIL image when inpainting mask crop, but is of type" f" {type(image)}."
796
+ )
797
+ if not isinstance(mask_image, PIL.Image.Image):
798
+ raise ValueError(
799
+ f"The mask image should be a PIL image when inpainting mask crop, but is of type"
800
+ f" {type(mask_image)}."
801
+ )
802
+ if output_type != "pil":
803
+ raise ValueError(f"The output type should be PIL when inpainting mask crop, but is" f" {output_type}.")
804
+
805
+ if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
806
+ raise ValueError(
807
+ "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
808
+ )
809
+
810
+ if ip_adapter_image_embeds is not None:
811
+ if not isinstance(ip_adapter_image_embeds, list):
812
+ raise ValueError(
813
+ f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
814
+ )
815
+ elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
816
+ raise ValueError(
817
+ f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
818
+ )
819
+
820
+ def prepare_latents(
821
+ self,
822
+ batch_size,
823
+ num_channels_latents,
824
+ height,
825
+ width,
826
+ dtype,
827
+ device,
828
+ generator,
829
+ latents=None,
830
+ image=None,
831
+ timestep=None,
832
+ is_strength_max=True,
833
+ add_noise=True,
834
+ return_noise=False,
835
+ return_image_latents=False,
836
+ ):
837
+ shape = (
838
+ batch_size,
839
+ num_channels_latents,
840
+ int(height) // self.vae_scale_factor,
841
+ int(width) // self.vae_scale_factor,
842
+ )
843
+ if isinstance(generator, list) and len(generator) != batch_size:
844
+ raise ValueError(
845
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
846
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
847
+ )
848
+
849
+ if (image is None or timestep is None) and not is_strength_max:
850
+ raise ValueError(
851
+ "Since strength < 1. initial latents are to be initialised as a combination of Image + Noise."
852
+ "However, either the image or the noise timestep has not been provided."
853
+ )
854
+
855
+ if image.shape[1] == 4:
856
+ image_latents = image.to(device=device, dtype=dtype)
857
+ image_latents = image_latents.repeat(batch_size // image_latents.shape[0], 1, 1, 1)
858
+ elif return_image_latents or (latents is None and not is_strength_max):
859
+ image = image.to(device=device, dtype=dtype)
860
+ image_latents = self._encode_vae_image(image=image, generator=generator)
861
+ image_latents = image_latents.repeat(batch_size // image_latents.shape[0], 1, 1, 1)
862
+
863
+ if latents is None and add_noise:
864
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
865
+ # if strength is 1. then initialise the latents to noise, else initial to image + noise
866
+ latents = noise if is_strength_max else self.scheduler.add_noise(image_latents, noise, timestep)
867
+ # if pure noise then scale the initial latents by the Scheduler's init sigma
868
+ latents = latents * self.scheduler.init_noise_sigma if is_strength_max else latents
869
+ elif add_noise:
870
+ noise = latents.to(device)
871
+ latents = noise * self.scheduler.init_noise_sigma
872
+ else:
873
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
874
+ latents = image_latents.to(device)
875
+
876
+ outputs = (latents,)
877
+
878
+ if return_noise:
879
+ outputs += (noise,)
880
+
881
+ if return_image_latents:
882
+ outputs += (image_latents,)
883
+
884
+ return outputs
885
+
886
+ def _encode_vae_image(self, image: torch.Tensor, generator: torch.Generator):
887
+ dtype = image.dtype
888
+ if self.vae.config.force_upcast:
889
+ image = image.float()
890
+ self.vae.to(dtype=torch.float32)
891
+
892
+ if isinstance(generator, list):
893
+ image_latents = [
894
+ retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i])
895
+ for i in range(image.shape[0])
896
+ ]
897
+ image_latents = torch.cat(image_latents, dim=0)
898
+ else:
899
+ image_latents = retrieve_latents(self.vae.encode(image), generator=generator)
900
+
901
+ if self.vae.config.force_upcast:
902
+ self.vae.to(dtype)
903
+
904
+ image_latents = image_latents.to(dtype)
905
+ image_latents = self.vae.config.scaling_factor * image_latents
906
+
907
+ return image_latents
908
+
909
+ def prepare_mask_latents(
910
+ self, mask, masked_image, batch_size, height, width, dtype, device, generator, do_classifier_free_guidance
911
+ ):
912
+ # resize the mask to latents shape as we concatenate the mask to the latents
913
+ # we do that before converting to dtype to avoid breaking in case we're using cpu_offload
914
+ # and half precision
915
+ mask = torch.nn.functional.interpolate(
916
+ mask, size=(height // self.vae_scale_factor, width // self.vae_scale_factor)
917
+ )
918
+ mask = mask.to(device=device, dtype=dtype)
919
+
920
+ # duplicate mask and masked_image_latents for each generation per prompt, using mps friendly method
921
+ if mask.shape[0] < batch_size:
922
+ if not batch_size % mask.shape[0] == 0:
923
+ raise ValueError(
924
+ "The passed mask and the required batch size don't match. Masks are supposed to be duplicated to"
925
+ f" a total batch size of {batch_size}, but {mask.shape[0]} masks were passed. Make sure the number"
926
+ " of masks that you pass is divisible by the total requested batch size."
927
+ )
928
+ mask = mask.repeat(batch_size // mask.shape[0], 1, 1, 1)
929
+
930
+ mask = torch.cat([mask] * 2) if do_classifier_free_guidance else mask
931
+
932
+ if masked_image is not None and masked_image.shape[1] == 4:
933
+ masked_image_latents = masked_image
934
+ else:
935
+ masked_image_latents = None
936
+
937
+ if masked_image is not None:
938
+ if masked_image_latents is None:
939
+ masked_image = masked_image.to(device=device, dtype=dtype)
940
+ masked_image_latents = self._encode_vae_image(masked_image, generator=generator)
941
+
942
+ if masked_image_latents.shape[0] < batch_size:
943
+ if not batch_size % masked_image_latents.shape[0] == 0:
944
+ raise ValueError(
945
+ "The passed images and the required batch size don't match. Images are supposed to be duplicated"
946
+ f" to a total batch size of {batch_size}, but {masked_image_latents.shape[0]} images were passed."
947
+ " Make sure the number of images that you pass is divisible by the total requested batch size."
948
+ )
949
+ masked_image_latents = masked_image_latents.repeat(
950
+ batch_size // masked_image_latents.shape[0], 1, 1, 1
951
+ )
952
+
953
+ masked_image_latents = (
954
+ torch.cat([masked_image_latents] * 2) if do_classifier_free_guidance else masked_image_latents
955
+ )
956
+
957
+ # aligning device to prevent device errors when concating it with the latent model input
958
+ masked_image_latents = masked_image_latents.to(device=device, dtype=dtype)
959
+
960
+ return mask, masked_image_latents
961
+
962
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl_img2img.StableDiffusionXLImg2ImgPipeline.get_timesteps
963
+ def get_timesteps(self, num_inference_steps, strength, device, denoising_start=None):
964
+ # get the original timestep using init_timestep
965
+ if denoising_start is None:
966
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
967
+ t_start = max(num_inference_steps - init_timestep, 0)
968
+
969
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
970
+ if hasattr(self.scheduler, "set_begin_index"):
971
+ self.scheduler.set_begin_index(t_start * self.scheduler.order)
972
+
973
+ return timesteps, num_inference_steps - t_start
974
+
975
+ else:
976
+ # Strength is irrelevant if we directly request a timestep to start at;
977
+ # that is, strength is determined by the denoising_start instead.
978
+ discrete_timestep_cutoff = int(
979
+ round(
980
+ self.scheduler.config.num_train_timesteps
981
+ - (denoising_start * self.scheduler.config.num_train_timesteps)
982
+ )
983
+ )
984
+
985
+ num_inference_steps = (self.scheduler.timesteps < discrete_timestep_cutoff).sum().item()
986
+ if self.scheduler.order == 2 and num_inference_steps % 2 == 0:
987
+ # if the scheduler is a 2nd order scheduler we might have to do +1
988
+ # because `num_inference_steps` might be even given that every timestep
989
+ # (except the highest one) is duplicated. If `num_inference_steps` is even it would
990
+ # mean that we cut the timesteps in the middle of the denoising step
991
+ # (between 1st and 2nd derivative) which leads to incorrect results. By adding 1
992
+ # we ensure that the denoising process always ends after the 2nd derivate step of the scheduler
993
+ num_inference_steps = num_inference_steps + 1
994
+
995
+ # because t_n+1 >= t_n, we slice the timesteps starting from the end
996
+ t_start = len(self.scheduler.timesteps) - num_inference_steps
997
+ timesteps = self.scheduler.timesteps[t_start:]
998
+ if hasattr(self.scheduler, "set_begin_index"):
999
+ self.scheduler.set_begin_index(t_start)
1000
+ return timesteps, num_inference_steps
1001
+
1002
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl_img2img.StableDiffusionXLImg2ImgPipeline._get_add_time_ids
1003
+ def _get_add_time_ids(
1004
+ self,
1005
+ original_size,
1006
+ crops_coords_top_left,
1007
+ target_size,
1008
+ aesthetic_score,
1009
+ negative_aesthetic_score,
1010
+ negative_original_size,
1011
+ negative_crops_coords_top_left,
1012
+ negative_target_size,
1013
+ dtype,
1014
+ text_encoder_projection_dim=None,
1015
+ ):
1016
+ if self.config.requires_aesthetics_score:
1017
+ add_time_ids = list(original_size + crops_coords_top_left + (aesthetic_score,))
1018
+ add_neg_time_ids = list(
1019
+ negative_original_size + negative_crops_coords_top_left + (negative_aesthetic_score,)
1020
+ )
1021
+ else:
1022
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
1023
+ add_neg_time_ids = list(negative_original_size + crops_coords_top_left + negative_target_size)
1024
+
1025
+ passed_add_embed_dim = (
1026
+ self.unet.config.addition_time_embed_dim * len(add_time_ids) + text_encoder_projection_dim
1027
+ )
1028
+ expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
1029
+
1030
+ if (
1031
+ expected_add_embed_dim > passed_add_embed_dim
1032
+ and (expected_add_embed_dim - passed_add_embed_dim) == self.unet.config.addition_time_embed_dim
1033
+ ):
1034
+ raise ValueError(
1035
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. Please make sure to enable `requires_aesthetics_score` with `pipe.register_to_config(requires_aesthetics_score=True)` to make sure `aesthetic_score` {aesthetic_score} and `negative_aesthetic_score` {negative_aesthetic_score} is correctly used by the model."
1036
+ )
1037
+ elif (
1038
+ expected_add_embed_dim < passed_add_embed_dim
1039
+ and (passed_add_embed_dim - expected_add_embed_dim) == self.unet.config.addition_time_embed_dim
1040
+ ):
1041
+ raise ValueError(
1042
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. Please make sure to disable `requires_aesthetics_score` with `pipe.register_to_config(requires_aesthetics_score=False)` to make sure `target_size` {target_size} is correctly used by the model."
1043
+ )
1044
+ elif expected_add_embed_dim != passed_add_embed_dim:
1045
+ raise ValueError(
1046
+ 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`."
1047
+ )
1048
+
1049
+ add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
1050
+ add_neg_time_ids = torch.tensor([add_neg_time_ids], dtype=dtype)
1051
+
1052
+ return add_time_ids, add_neg_time_ids
1053
+
1054
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.StableDiffusionUpscalePipeline.upcast_vae
1055
+ def upcast_vae(self):
1056
+ dtype = self.vae.dtype
1057
+ self.vae.to(dtype=torch.float32)
1058
+ use_torch_2_0_or_xformers = isinstance(
1059
+ self.vae.decoder.mid_block.attentions[0].processor,
1060
+ (
1061
+ AttnProcessor2_0,
1062
+ XFormersAttnProcessor,
1063
+ ),
1064
+ )
1065
+ # if xformers or torch_2_0 is used attention block does not need
1066
+ # to be in float32 which can save lots of memory
1067
+ if use_torch_2_0_or_xformers:
1068
+ self.vae.post_quant_conv.to(dtype)
1069
+ self.vae.decoder.conv_in.to(dtype)
1070
+ self.vae.decoder.mid_block.to(dtype)
1071
+
1072
+ # Copied from diffusers.pipelines.t2i_adapter.pipeline_stable_diffusion_adapter.StableDiffusionAdapterPipeline._default_height_width
1073
+ def _default_height_width(self, height, width, image):
1074
+ # NOTE: It is possible that a list of images have different
1075
+ # dimensions for each image, so just checking the first image
1076
+ # is not _exactly_ correct, but it is simple.
1077
+ while isinstance(image, list):
1078
+ image = image[0]
1079
+
1080
+ if height is None:
1081
+ if isinstance(image, PIL.Image.Image):
1082
+ height = image.height
1083
+ elif isinstance(image, torch.Tensor):
1084
+ height = image.shape[-2]
1085
+
1086
+ # round down to nearest multiple of `self.adapter.downscale_factor`
1087
+ height = (height // self.adapter.downscale_factor) * self.adapter.downscale_factor
1088
+
1089
+ if width is None:
1090
+ if isinstance(image, PIL.Image.Image):
1091
+ width = image.width
1092
+ elif isinstance(image, torch.Tensor):
1093
+ width = image.shape[-1]
1094
+
1095
+ # round down to nearest multiple of `self.adapter.downscale_factor`
1096
+ width = (width // self.adapter.downscale_factor) * self.adapter.downscale_factor
1097
+
1098
+ return height, width
1099
+
1100
+
1101
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
1102
+ def get_guidance_scale_embedding(
1103
+ self, w: torch.Tensor, embedding_dim: int = 512, dtype: torch.dtype = torch.float32
1104
+ ) -> torch.Tensor:
1105
+ """
1106
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
1107
+
1108
+ Args:
1109
+ w (`torch.Tensor`):
1110
+ Generate embedding vectors with a specified guidance scale to subsequently enrich timestep embeddings.
1111
+ embedding_dim (`int`, *optional*, defaults to 512):
1112
+ Dimension of the embeddings to generate.
1113
+ dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
1114
+ Data type of the generated embeddings.
1115
+
1116
+ Returns:
1117
+ `torch.Tensor`: Embedding vectors with shape `(len(w), embedding_dim)`.
1118
+ """
1119
+ assert len(w.shape) == 1
1120
+ w = w * 1000.0
1121
+
1122
+ half_dim = embedding_dim // 2
1123
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
1124
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
1125
+ emb = w.to(dtype)[:, None] * emb[None, :]
1126
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
1127
+ if embedding_dim % 2 == 1: # zero pad
1128
+ emb = torch.nn.functional.pad(emb, (0, 1))
1129
+ assert emb.shape == (w.shape[0], embedding_dim)
1130
+ return emb
1131
+
1132
+ @property
1133
+ def guidance_scale(self):
1134
+ return self._guidance_scale
1135
+
1136
+ @property
1137
+ def guidance_rescale(self):
1138
+ return self._guidance_rescale
1139
+
1140
+ @property
1141
+ def clip_skip(self):
1142
+ return self._clip_skip
1143
+
1144
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
1145
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
1146
+ # corresponds to doing no classifier free guidance.
1147
+ @property
1148
+ def do_classifier_free_guidance(self):
1149
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
1150
+
1151
+ @property
1152
+ def cross_attention_kwargs(self):
1153
+ return self._cross_attention_kwargs
1154
+
1155
+ @property
1156
+ def denoising_end(self):
1157
+ return self._denoising_end
1158
+
1159
+ @property
1160
+ def denoising_start(self):
1161
+ return self._denoising_start
1162
+
1163
+ @property
1164
+ def num_timesteps(self):
1165
+ return self._num_timesteps
1166
+
1167
+ @property
1168
+ def interrupt(self):
1169
+ return self._interrupt
1170
+
1171
+ @torch.no_grad()
1172
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
1173
+ def __call__(
1174
+ self,
1175
+ prompt: Union[str, List[str]] = None,
1176
+ prompt_2: Optional[Union[str, List[str]]] = None,
1177
+ image: PipelineImageInput = None,
1178
+ mask_image: PipelineImageInput = None,
1179
+ masked_image_latents: torch.Tensor = None,
1180
+ height: Optional[int] = None,
1181
+ width: Optional[int] = None,
1182
+ adapter_image: PipelineImageInput = None,
1183
+ padding_mask_crop: Optional[int] = None,
1184
+ strength: float = 0.9999,
1185
+ num_inference_steps: int = 50,
1186
+ timesteps: List[int] = None,
1187
+ sigmas: List[float] = None,
1188
+ denoising_start: Optional[float] = None,
1189
+ denoising_end: Optional[float] = None,
1190
+ guidance_scale: float = 7.5,
1191
+ negative_prompt: Optional[Union[str, List[str]]] = None,
1192
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
1193
+ num_images_per_prompt: Optional[int] = 1,
1194
+ eta: float = 0.0,
1195
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
1196
+ latents: Optional[torch.Tensor] = None,
1197
+ prompt_embeds: Optional[torch.Tensor] = None,
1198
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
1199
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
1200
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
1201
+ ip_adapter_image: Optional[PipelineImageInput] = None,
1202
+ ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
1203
+ output_type: Optional[str] = "pil",
1204
+ return_dict: bool = True,
1205
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1206
+ guidance_rescale: float = 0.0,
1207
+ original_size: Tuple[int, int] = None,
1208
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
1209
+ target_size: Tuple[int, int] = None,
1210
+ negative_original_size: Optional[Tuple[int, int]] = None,
1211
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
1212
+ negative_target_size: Optional[Tuple[int, int]] = None,
1213
+ aesthetic_score: float = 6.0,
1214
+ negative_aesthetic_score: float = 2.5,
1215
+ adapter_conditioning_scale: Union[float, List[float]] = 1.0,
1216
+ adapter_conditioning_factor: float = 1.0,
1217
+ clip_skip: Optional[int] = None,
1218
+ callback_on_step_end: Optional[
1219
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
1220
+ ] = None,
1221
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
1222
+ **kwargs,
1223
+ ):
1224
+ r"""
1225
+ Function invoked when calling the pipeline for generation.
1226
+
1227
+ Args:
1228
+ prompt (`str` or `List[str]`, *optional*):
1229
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
1230
+ instead.
1231
+ prompt_2 (`str` or `List[str]`, *optional*):
1232
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
1233
+ used in both text-encoders
1234
+ image (`PIL.Image.Image`):
1235
+ `Image`, or tensor representing an image batch which will be inpainted, *i.e.* parts of the image will
1236
+ be masked out with `mask_image` and repainted according to `prompt`.
1237
+ mask_image (`PIL.Image.Image`):
1238
+ `Image`, or tensor representing an image batch, to mask `image`. White pixels in the mask will be
1239
+ repainted, while black pixels will be preserved. If `mask_image` is a PIL image, it will be converted
1240
+ to a single channel (luminance) before use. If it's a tensor, it should contain one color channel (L)
1241
+ instead of 3, so the expected shape would be `(B, H, W, 1)`.
1242
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
1243
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
1244
+ Anything below 512 pixels won't work well for
1245
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
1246
+ and checkpoints that are not specifically fine-tuned on low resolutions.
1247
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
1248
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
1249
+ Anything below 512 pixels won't work well for
1250
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
1251
+ and checkpoints that are not specifically fine-tuned on low resolutions.
1252
+ padding_mask_crop (`int`, *optional*, defaults to `None`):
1253
+ The size of margin in the crop to be applied to the image and masking. If `None`, no crop is applied to
1254
+ image and mask_image. If `padding_mask_crop` is not `None`, it will first find a rectangular region
1255
+ with the same aspect ration of the image and contains all masked area, and then expand that area based
1256
+ on `padding_mask_crop`. The image and mask_image will then be cropped based on the expanded area before
1257
+ resizing to the original image size for inpainting. This is useful when the masked area is small while
1258
+ the image is large and contain information irrelevant for inpainting, such as background.
1259
+ strength (`float`, *optional*, defaults to 0.9999):
1260
+ Conceptually, indicates how much to transform the masked portion of the reference `image`. Must be
1261
+ between 0 and 1. `image` will be used as a starting point, adding more noise to it the larger the
1262
+ `strength`. The number of denoising steps depends on the amount of noise initially added. When
1263
+ `strength` is 1, added noise will be maximum and the denoising process will run for the full number of
1264
+ iterations specified in `num_inference_steps`. A value of 1, therefore, essentially ignores the masked
1265
+ portion of the reference `image`. Note that in the case of `denoising_start` being declared as an
1266
+ integer, the value of `strength` will be ignored.
1267
+ num_inference_steps (`int`, *optional*, defaults to 50):
1268
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
1269
+ expense of slower inference.
1270
+ timesteps (`List[int]`, *optional*):
1271
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
1272
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
1273
+ passed will be used. Must be in descending order.
1274
+ sigmas (`List[float]`, *optional*):
1275
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
1276
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
1277
+ will be used.
1278
+ denoising_start (`float`, *optional*):
1279
+ When specified, indicates the fraction (between 0.0 and 1.0) of the total denoising process to be
1280
+ bypassed before it is initiated. Consequently, the initial part of the denoising process is skipped and
1281
+ it is assumed that the passed `image` is a partly denoised image. Note that when this is specified,
1282
+ strength will be ignored. The `denoising_start` parameter is particularly beneficial when this pipeline
1283
+ is integrated into a "Mixture of Denoisers" multi-pipeline setup, as detailed in [**Refining the Image
1284
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output).
1285
+ denoising_end (`float`, *optional*):
1286
+ When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
1287
+ completed before it is intentionally prematurely terminated. As a result, the returned sample will
1288
+ still retain a substantial amount of noise (ca. final 20% of timesteps still needed) and should be
1289
+ denoised by a successor pipeline that has `denoising_start` set to 0.8 so that it only denoises the
1290
+ final 20% of the scheduler. The denoising_end parameter should ideally be utilized when this pipeline
1291
+ forms a part of a "Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
1292
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output).
1293
+ guidance_scale (`float`, *optional*, defaults to 7.5):
1294
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
1295
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
1296
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
1297
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
1298
+ usually at the expense of lower image quality.
1299
+ negative_prompt (`str` or `List[str]`, *optional*):
1300
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
1301
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
1302
+ less than `1`).
1303
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
1304
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
1305
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
1306
+ prompt_embeds (`torch.Tensor`, *optional*):
1307
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
1308
+ provided, text embeddings will be generated from `prompt` input argument.
1309
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
1310
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
1311
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
1312
+ argument.
1313
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
1314
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
1315
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
1316
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
1317
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
1318
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
1319
+ input argument.
1320
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
1321
+ ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
1322
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
1323
+ IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should
1324
+ contain the negative image embedding if `do_classifier_free_guidance` is set to `True`. If not
1325
+ provided, embeddings are computed from the `ip_adapter_image` input argument.
1326
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1327
+ The number of images to generate per prompt.
1328
+ eta (`float`, *optional*, defaults to 0.0):
1329
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
1330
+ [`schedulers.DDIMScheduler`], will be ignored for others.
1331
+ generator (`torch.Generator`, *optional*):
1332
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
1333
+ to make generation deterministic.
1334
+ latents (`torch.Tensor`, *optional*):
1335
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
1336
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
1337
+ tensor will ge generated by sampling using the supplied random `generator`.
1338
+ output_type (`str`, *optional*, defaults to `"pil"`):
1339
+ The output format of the generate image. Choose between
1340
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
1341
+ return_dict (`bool`, *optional*, defaults to `True`):
1342
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
1343
+ plain tuple.
1344
+ cross_attention_kwargs (`dict`, *optional*):
1345
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
1346
+ `self.processor` in
1347
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1348
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1349
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
1350
+ `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
1351
+ explained in section 2.2 of
1352
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1353
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
1354
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
1355
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
1356
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
1357
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1358
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1359
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
1360
+ not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
1361
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1362
+ negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1363
+ To negatively condition the generation process based on a specific image resolution. Part of SDXL's
1364
+ micro-conditioning as explained in section 2.2 of
1365
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1366
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1367
+ negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
1368
+ To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
1369
+ micro-conditioning as explained in section 2.2 of
1370
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1371
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1372
+ negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1373
+ To negatively condition the generation process based on a target image resolution. It should be as same
1374
+ as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
1375
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1376
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1377
+ aesthetic_score (`float`, *optional*, defaults to 6.0):
1378
+ Used to simulate an aesthetic score of the generated image by influencing the positive text condition.
1379
+ Part of SDXL's micro-conditioning as explained in section 2.2 of
1380
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1381
+ negative_aesthetic_score (`float`, *optional*, defaults to 2.5):
1382
+ Part of SDXL's micro-conditioning as explained in section 2.2 of
1383
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). Can be used to
1384
+ simulate an aesthetic score of the generated image by influencing the negative text condition.
1385
+ clip_skip (`int`, *optional*):
1386
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
1387
+ the output of the pre-final layer will be used for computing the prompt embeddings.
1388
+ callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
1389
+ A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
1390
+ each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
1391
+ DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
1392
+ list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
1393
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
1394
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
1395
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
1396
+ `._callback_tensor_inputs` attribute of your pipeline class.
1397
+
1398
+ Examples:
1399
+
1400
+ Returns:
1401
+ [`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] or `tuple`:
1402
+ [`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
1403
+ `tuple. `tuple. When returning a tuple, the first element is a list with the generated images.
1404
+ """
1405
+ height, width = self._default_height_width(height, width, adapter_image)
1406
+ device = self._execution_device
1407
+
1408
+ if isinstance(self.adapter, MultiAdapter):
1409
+ adapter_input = []
1410
+
1411
+ for one_image in adapter_image:
1412
+ one_image = _preprocess_adapter_image(one_image, height, width)
1413
+ one_image = one_image.to(device=device, dtype=self.adapter.dtype)
1414
+ adapter_input.append(one_image)
1415
+ else:
1416
+ adapter_input = _preprocess_adapter_image(adapter_image, height, width)
1417
+ adapter_input = adapter_input.to(device=device, dtype=self.adapter.dtype)
1418
+
1419
+ callback = kwargs.pop("callback", None)
1420
+ callback_steps = kwargs.pop("callback_steps", None)
1421
+
1422
+ if callback is not None:
1423
+ deprecate(
1424
+ "callback",
1425
+ "1.0.0",
1426
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
1427
+ )
1428
+ if callback_steps is not None:
1429
+ deprecate(
1430
+ "callback_steps",
1431
+ "1.0.0",
1432
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
1433
+ )
1434
+
1435
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
1436
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
1437
+
1438
+ # 0. Default height and width to unet
1439
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
1440
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
1441
+
1442
+ # 1. Check inputs
1443
+ self.check_inputs(
1444
+ prompt,
1445
+ prompt_2,
1446
+ image,
1447
+ mask_image,
1448
+ height,
1449
+ width,
1450
+ strength,
1451
+ callback_steps,
1452
+ output_type,
1453
+ negative_prompt,
1454
+ negative_prompt_2,
1455
+ prompt_embeds,
1456
+ negative_prompt_embeds,
1457
+ ip_adapter_image,
1458
+ ip_adapter_image_embeds,
1459
+ callback_on_step_end_tensor_inputs,
1460
+ padding_mask_crop,
1461
+ )
1462
+
1463
+ self._guidance_scale = guidance_scale
1464
+ self._guidance_rescale = guidance_rescale
1465
+ self._clip_skip = clip_skip
1466
+ self._cross_attention_kwargs = cross_attention_kwargs
1467
+ self._denoising_end = denoising_end
1468
+ self._denoising_start = denoising_start
1469
+ self._interrupt = False
1470
+
1471
+ # 2. Define call parameters
1472
+ if prompt is not None and isinstance(prompt, str):
1473
+ batch_size = 1
1474
+ elif prompt is not None and isinstance(prompt, list):
1475
+ batch_size = len(prompt)
1476
+ else:
1477
+ batch_size = prompt_embeds.shape[0]
1478
+
1479
+ device = self._execution_device
1480
+
1481
+ # 3. Encode input prompt
1482
+ text_encoder_lora_scale = (
1483
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
1484
+ )
1485
+
1486
+ (
1487
+ prompt_embeds,
1488
+ negative_prompt_embeds,
1489
+ pooled_prompt_embeds,
1490
+ negative_pooled_prompt_embeds,
1491
+ ) = self.encode_prompt(
1492
+ prompt=prompt,
1493
+ prompt_2=prompt_2,
1494
+ device=device,
1495
+ num_images_per_prompt=num_images_per_prompt,
1496
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1497
+ negative_prompt=negative_prompt,
1498
+ negative_prompt_2=negative_prompt_2,
1499
+ prompt_embeds=prompt_embeds,
1500
+ negative_prompt_embeds=negative_prompt_embeds,
1501
+ pooled_prompt_embeds=pooled_prompt_embeds,
1502
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
1503
+ lora_scale=text_encoder_lora_scale,
1504
+ clip_skip=self.clip_skip,
1505
+ )
1506
+
1507
+ # 4. set timesteps
1508
+ def denoising_value_valid(dnv):
1509
+ return isinstance(dnv, float) and 0 < dnv < 1
1510
+
1511
+ timesteps, num_inference_steps = retrieve_timesteps(
1512
+ self.scheduler, num_inference_steps, device, timesteps, sigmas
1513
+ )
1514
+ timesteps, num_inference_steps = self.get_timesteps(
1515
+ num_inference_steps,
1516
+ strength,
1517
+ device,
1518
+ denoising_start=self.denoising_start if denoising_value_valid(self.denoising_start) else None,
1519
+ )
1520
+ # check that number of inference steps is not < 1 - as this doesn't make sense
1521
+ if num_inference_steps < 1:
1522
+ raise ValueError(
1523
+ f"After adjusting the num_inference_steps by strength parameter: {strength}, the number of pipeline"
1524
+ f"steps is {num_inference_steps} which is < 1 and not appropriate for this pipeline."
1525
+ )
1526
+ # at which timestep to set the initial noise (n.b. 50% if strength is 0.5)
1527
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
1528
+ # create a boolean to check if the strength is set to 1. if so then initialise the latents with pure noise
1529
+ is_strength_max = strength == 1.0
1530
+
1531
+ # 5. Preprocess mask and image
1532
+ if padding_mask_crop is not None:
1533
+ crops_coords = self.mask_processor.get_crop_region(mask_image, width, height, pad=padding_mask_crop)
1534
+ resize_mode = "fill"
1535
+ else:
1536
+ crops_coords = None
1537
+ resize_mode = "default"
1538
+
1539
+ original_image = image
1540
+ init_image = self.image_processor.preprocess(
1541
+ image, height=height, width=width, crops_coords=crops_coords, resize_mode=resize_mode
1542
+ )
1543
+ init_image = init_image.to(dtype=torch.float32)
1544
+
1545
+ mask = self.mask_processor.preprocess(
1546
+ mask_image, height=height, width=width, resize_mode=resize_mode, crops_coords=crops_coords
1547
+ )
1548
+
1549
+ if masked_image_latents is not None:
1550
+ masked_image = masked_image_latents
1551
+ elif init_image.shape[1] == 4:
1552
+ # if images are in latent space, we can't mask it
1553
+ masked_image = None
1554
+ else:
1555
+ masked_image = init_image * (mask < 0.5)
1556
+
1557
+ # 6. Prepare latent variables
1558
+ num_channels_latents = self.vae.config.latent_channels
1559
+ num_channels_unet = self.unet.config.in_channels
1560
+ return_image_latents = num_channels_unet == 4
1561
+
1562
+ add_noise = True if self.denoising_start is None else False
1563
+ latents_outputs = self.prepare_latents(
1564
+ batch_size * num_images_per_prompt,
1565
+ num_channels_latents,
1566
+ height,
1567
+ width,
1568
+ prompt_embeds.dtype,
1569
+ device,
1570
+ generator,
1571
+ latents,
1572
+ image=init_image,
1573
+ timestep=latent_timestep,
1574
+ is_strength_max=is_strength_max,
1575
+ add_noise=add_noise,
1576
+ return_noise=True,
1577
+ return_image_latents=return_image_latents,
1578
+ )
1579
+
1580
+ if return_image_latents:
1581
+ latents, noise, image_latents = latents_outputs
1582
+ else:
1583
+ latents, noise = latents_outputs
1584
+
1585
+ # 7. Prepare mask latent variables
1586
+ mask, masked_image_latents = self.prepare_mask_latents(
1587
+ mask,
1588
+ masked_image,
1589
+ batch_size * num_images_per_prompt,
1590
+ height,
1591
+ width,
1592
+ prompt_embeds.dtype,
1593
+ device,
1594
+ generator,
1595
+ self.do_classifier_free_guidance,
1596
+ )
1597
+
1598
+ # 8. Check that sizes of mask, masked image and latents match
1599
+ if num_channels_unet == 9:
1600
+ # default case for runwayml/stable-diffusion-inpainting
1601
+ num_channels_mask = mask.shape[1]
1602
+ num_channels_masked_image = masked_image_latents.shape[1]
1603
+ if num_channels_latents + num_channels_mask + num_channels_masked_image != self.unet.config.in_channels:
1604
+ raise ValueError(
1605
+ f"Incorrect configuration settings! The config of `pipeline.unet`: {self.unet.config} expects"
1606
+ f" {self.unet.config.in_channels} but received `num_channels_latents`: {num_channels_latents} +"
1607
+ f" `num_channels_mask`: {num_channels_mask} + `num_channels_masked_image`: {num_channels_masked_image}"
1608
+ f" = {num_channels_latents+num_channels_masked_image+num_channels_mask}. Please verify the config of"
1609
+ " `pipeline.unet` or your `mask_image` or `image` input."
1610
+ )
1611
+ elif num_channels_unet != 4:
1612
+ raise ValueError(
1613
+ f"The unet {self.unet.__class__} should have either 4 or 9 input channels, not {self.unet.config.in_channels}."
1614
+ )
1615
+ # 8.1 Prepare extra step kwargs.
1616
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1617
+
1618
+ # 9. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1619
+ height, width = latents.shape[-2:]
1620
+ height = height * self.vae_scale_factor
1621
+ width = width * self.vae_scale_factor
1622
+
1623
+ original_size = original_size or (height, width)
1624
+ target_size = target_size or (height, width)
1625
+
1626
+ # 10. Prepare added time ids & embeddings
1627
+ if isinstance(self.adapter, MultiAdapter):
1628
+ adapter_state = self.adapter(adapter_input, adapter_conditioning_scale)
1629
+ for k, v in enumerate(adapter_state):
1630
+ adapter_state[k] = v
1631
+ else:
1632
+ adapter_state = self.adapter(adapter_input)
1633
+ for k, v in enumerate(adapter_state):
1634
+ adapter_state[k] = v * adapter_conditioning_scale
1635
+ if num_images_per_prompt > 1:
1636
+ for k, v in enumerate(adapter_state):
1637
+ adapter_state[k] = v.repeat(num_images_per_prompt, 1, 1, 1)
1638
+ if self.do_classifier_free_guidance:
1639
+ for k, v in enumerate(adapter_state):
1640
+ adapter_state[k] = torch.cat([v] * 2, dim=0)
1641
+
1642
+ if negative_original_size is None:
1643
+ negative_original_size = original_size
1644
+ if negative_target_size is None:
1645
+ negative_target_size = target_size
1646
+
1647
+ add_text_embeds = pooled_prompt_embeds
1648
+ if self.text_encoder_2 is None:
1649
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
1650
+ else:
1651
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
1652
+
1653
+ add_time_ids, add_neg_time_ids = self._get_add_time_ids(
1654
+ original_size,
1655
+ crops_coords_top_left,
1656
+ target_size,
1657
+ aesthetic_score,
1658
+ negative_aesthetic_score,
1659
+ negative_original_size,
1660
+ negative_crops_coords_top_left,
1661
+ negative_target_size,
1662
+ dtype=prompt_embeds.dtype,
1663
+ text_encoder_projection_dim=text_encoder_projection_dim,
1664
+ )
1665
+ add_time_ids = add_time_ids.repeat(batch_size * num_images_per_prompt, 1)
1666
+
1667
+ if self.do_classifier_free_guidance:
1668
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
1669
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
1670
+ add_neg_time_ids = add_neg_time_ids.repeat(batch_size * num_images_per_prompt, 1)
1671
+ add_time_ids = torch.cat([add_neg_time_ids, add_time_ids], dim=0)
1672
+
1673
+ prompt_embeds = prompt_embeds.to(device)
1674
+ add_text_embeds = add_text_embeds.to(device)
1675
+ add_time_ids = add_time_ids.to(device)
1676
+
1677
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1678
+ image_embeds = self.prepare_ip_adapter_image_embeds(
1679
+ ip_adapter_image,
1680
+ ip_adapter_image_embeds,
1681
+ device,
1682
+ batch_size * num_images_per_prompt,
1683
+ self.do_classifier_free_guidance,
1684
+ )
1685
+
1686
+ # 11. Denoising loop
1687
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
1688
+
1689
+ if (
1690
+ self.denoising_end is not None
1691
+ and self.denoising_start is not None
1692
+ and denoising_value_valid(self.denoising_end)
1693
+ and denoising_value_valid(self.denoising_start)
1694
+ and self.denoising_start >= self.denoising_end
1695
+ ):
1696
+ raise ValueError(
1697
+ f"`denoising_start`: {self.denoising_start} cannot be larger than or equal to `denoising_end`: "
1698
+ + f" {self.denoising_end} when using type float."
1699
+ )
1700
+ elif self.denoising_end is not None and denoising_value_valid(self.denoising_end):
1701
+ discrete_timestep_cutoff = int(
1702
+ round(
1703
+ self.scheduler.config.num_train_timesteps
1704
+ - (self.denoising_end * self.scheduler.config.num_train_timesteps)
1705
+ )
1706
+ )
1707
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
1708
+ timesteps = timesteps[:num_inference_steps]
1709
+
1710
+ # 11.1 Optionally get Guidance Scale Embedding
1711
+ timestep_cond = None
1712
+ if self.unet.config.time_cond_proj_dim is not None:
1713
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
1714
+ timestep_cond = self.get_guidance_scale_embedding(
1715
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
1716
+ ).to(device=device, dtype=latents.dtype)
1717
+
1718
+ self._num_timesteps = len(timesteps)
1719
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1720
+ for i, t in enumerate(timesteps):
1721
+ if self.interrupt:
1722
+ continue
1723
+ # expand the latents if we are doing classifier free guidance
1724
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1725
+
1726
+ # concat latents, mask, masked_image_latents in the channel dimension
1727
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1728
+
1729
+ if num_channels_unet == 9:
1730
+ latent_model_input = torch.cat([latent_model_input, mask, masked_image_latents], dim=1)
1731
+
1732
+ # predict the noise residual
1733
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
1734
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1735
+ added_cond_kwargs["image_embeds"] = image_embeds
1736
+
1737
+ if i < int(num_inference_steps * adapter_conditioning_factor):
1738
+ down_intrablock_additional_residuals = [state.clone() for state in adapter_state]
1739
+ else:
1740
+ down_intrablock_additional_residuals = None
1741
+
1742
+ noise_pred = self.unet(
1743
+ latent_model_input,
1744
+ t,
1745
+ encoder_hidden_states=prompt_embeds,
1746
+ timestep_cond=timestep_cond,
1747
+ cross_attention_kwargs=self.cross_attention_kwargs,
1748
+ added_cond_kwargs=added_cond_kwargs,
1749
+ return_dict=False,
1750
+ down_intrablock_additional_residuals=down_intrablock_additional_residuals,
1751
+ )[0]
1752
+
1753
+ # perform guidance
1754
+ if self.do_classifier_free_guidance:
1755
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1756
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
1757
+
1758
+ if self.do_classifier_free_guidance and self.guidance_rescale > 0.0:
1759
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1760
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale)
1761
+
1762
+ # compute the previous noisy sample x_t -> x_t-1
1763
+ latents_dtype = latents.dtype
1764
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1765
+ if latents.dtype != latents_dtype:
1766
+ if torch.backends.mps.is_available():
1767
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1768
+ latents = latents.to(latents_dtype)
1769
+
1770
+ if num_channels_unet == 4:
1771
+ init_latents_proper = image_latents
1772
+ if self.do_classifier_free_guidance:
1773
+ init_mask, _ = mask.chunk(2)
1774
+ else:
1775
+ init_mask = mask
1776
+
1777
+ if i < len(timesteps) - 1:
1778
+ noise_timestep = timesteps[i + 1]
1779
+ init_latents_proper = self.scheduler.add_noise(
1780
+ init_latents_proper, noise, torch.tensor([noise_timestep])
1781
+ )
1782
+
1783
+ latents = (1 - init_mask) * init_latents_proper + init_mask * latents
1784
+
1785
+ if callback_on_step_end is not None:
1786
+ callback_kwargs = {}
1787
+ for k in callback_on_step_end_tensor_inputs:
1788
+ callback_kwargs[k] = locals()[k]
1789
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1790
+
1791
+ latents = callback_outputs.pop("latents", latents)
1792
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1793
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1794
+ add_text_embeds = callback_outputs.pop("add_text_embeds", add_text_embeds)
1795
+ negative_pooled_prompt_embeds = callback_outputs.pop(
1796
+ "negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
1797
+ )
1798
+ add_time_ids = callback_outputs.pop("add_time_ids", add_time_ids)
1799
+ add_neg_time_ids = callback_outputs.pop("add_neg_time_ids", add_neg_time_ids)
1800
+ mask = callback_outputs.pop("mask", mask)
1801
+ masked_image_latents = callback_outputs.pop("masked_image_latents", masked_image_latents)
1802
+
1803
+ # call the callback, if provided
1804
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1805
+ progress_bar.update()
1806
+ if callback is not None and i % callback_steps == 0:
1807
+ step_idx = i // getattr(self.scheduler, "order", 1)
1808
+ callback(step_idx, t, latents)
1809
+
1810
+ if XLA_AVAILABLE:
1811
+ xm.mark_step()
1812
+
1813
+ if not output_type == "latent":
1814
+ # make sure the VAE is in float32 mode, as it overflows in float16
1815
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
1816
+
1817
+ if needs_upcasting:
1818
+ self.upcast_vae()
1819
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1820
+ elif latents.dtype != self.vae.dtype:
1821
+ if torch.backends.mps.is_available():
1822
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1823
+ self.vae = self.vae.to(latents.dtype)
1824
+
1825
+ # unscale/denormalize the latents
1826
+ # denormalize with the mean and std if available and not None
1827
+ has_latents_mean = hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None
1828
+ has_latents_std = hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None
1829
+ if has_latents_mean and has_latents_std:
1830
+ latents_mean = (
1831
+ torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1832
+ )
1833
+ latents_std = (
1834
+ torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1835
+ )
1836
+ latents = latents * latents_std / self.vae.config.scaling_factor + latents_mean
1837
+ else:
1838
+ latents = latents / self.vae.config.scaling_factor
1839
+
1840
+ image = self.vae.decode(latents, return_dict=False)[0]
1841
+
1842
+ # cast back to fp16 if needed
1843
+ if needs_upcasting:
1844
+ self.vae.to(dtype=torch.float16)
1845
+ else:
1846
+ return StableDiffusionXLPipelineOutput(images=latents)
1847
+
1848
+ # apply watermark if available
1849
+ if self.watermark is not None:
1850
+ image = self.watermark.apply_watermark(image)
1851
+
1852
+ image = self.image_processor.postprocess(image, output_type=output_type)
1853
+
1854
+ if padding_mask_crop is not None:
1855
+ image = [self.image_processor.apply_overlay(mask_image, original_image, i, crops_coords) for i in image]
1856
+
1857
+ # Offload all models
1858
+ self.maybe_free_model_hooks()
1859
+
1860
+ if not return_dict:
1861
+ return (image,)
1862
+
1863
+ return StableDiffusionXLPipelineOutput(images=image)