zhiweili
commited on
Commit
•
5fbf40f
1
Parent(s):
bd5747f
add app makeup
Browse files- app.py +3 -0
- app_makeup.py +107 -0
- inversion_run_adapter.py +254 -0
- inversion_run_base.py +1 -3
- pipelines/pipeline_sdxl_adapter_img2img.py +1672 -0
- requirements.txt +3 -1
app.py
CHANGED
@@ -1,10 +1,13 @@
|
|
1 |
import gradio as gr
|
2 |
|
3 |
from app_base import create_demo as create_demo_face
|
|
|
4 |
|
5 |
with gr.Blocks(css="style.css") as demo:
|
6 |
with gr.Tabs():
|
7 |
with gr.Tab(label="Face"):
|
8 |
create_demo_face()
|
|
|
|
|
9 |
|
10 |
demo.launch()
|
|
|
1 |
import gradio as gr
|
2 |
|
3 |
from app_base import create_demo as create_demo_face
|
4 |
+
from app_makeup import create_demo as create_demo_makeup
|
5 |
|
6 |
with gr.Blocks(css="style.css") as demo:
|
7 |
with gr.Tabs():
|
8 |
with gr.Tab(label="Face"):
|
9 |
create_demo_face()
|
10 |
+
with gr.Tab(label="Makeup"):
|
11 |
+
create_demo_makeup()
|
12 |
|
13 |
demo.launch()
|
app_makeup.py
ADDED
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import spaces
|
2 |
+
import gradio as gr
|
3 |
+
import os
|
4 |
+
import torch
|
5 |
+
import uuid
|
6 |
+
|
7 |
+
from PIL import Image
|
8 |
+
from enhance_utils import enhance_image
|
9 |
+
|
10 |
+
|
11 |
+
DEFAULT_SRC_PROMPT = "a woman"
|
12 |
+
DEFAULT_EDIT_PROMPT = "a woman, with red lips, 8k, high quality"
|
13 |
+
|
14 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
15 |
+
|
16 |
+
def create_demo() -> gr.Blocks:
|
17 |
+
from inversion_run_adapter import run as adapter_run
|
18 |
+
|
19 |
+
@spaces.GPU(duration=15)
|
20 |
+
def image_to_image(
|
21 |
+
input_image_path: str,
|
22 |
+
input_image_prompt: str,
|
23 |
+
edit_prompt: str,
|
24 |
+
seed: int,
|
25 |
+
w1: float,
|
26 |
+
num_steps: int,
|
27 |
+
start_step: int,
|
28 |
+
guidance_scale: float,
|
29 |
+
generate_size: int,
|
30 |
+
lineart_scale: float,
|
31 |
+
canny_scale: float,
|
32 |
+
lineart_detect: float,
|
33 |
+
canny_detect: float,
|
34 |
+
):
|
35 |
+
w2 = 1.0
|
36 |
+
|
37 |
+
input_image = Image.open(input_image_path)
|
38 |
+
|
39 |
+
w2 = 1.0
|
40 |
+
run_model = adapter_run
|
41 |
+
generated_image = run_model(
|
42 |
+
input_image,
|
43 |
+
input_image_prompt,
|
44 |
+
edit_prompt,
|
45 |
+
generate_size,
|
46 |
+
seed,
|
47 |
+
w1,
|
48 |
+
w2,
|
49 |
+
num_steps,
|
50 |
+
start_step,
|
51 |
+
guidance_scale,
|
52 |
+
lineart_scale,
|
53 |
+
canny_scale,
|
54 |
+
lineart_detect,
|
55 |
+
canny_detect,
|
56 |
+
)
|
57 |
+
enhanced_image = enhance_image(generated_image, False)
|
58 |
+
|
59 |
+
tmpPrefix = "/tmp/gradio/"
|
60 |
+
|
61 |
+
extension = 'png'
|
62 |
+
if enhanced_image.mode == 'RGBA':
|
63 |
+
extension = 'png'
|
64 |
+
else:
|
65 |
+
extension = 'jpg'
|
66 |
+
|
67 |
+
targetDir = f"{tmpPrefix}output/"
|
68 |
+
if not os.path.exists(targetDir):
|
69 |
+
os.makedirs(targetDir)
|
70 |
+
|
71 |
+
enhanced_path = f"{targetDir}{uuid.uuid4()}.{extension}"
|
72 |
+
enhanced_image.save(enhanced_path, quality=100)
|
73 |
+
|
74 |
+
return enhanced_path
|
75 |
+
|
76 |
+
with gr.Blocks() as demo:
|
77 |
+
with gr.Row():
|
78 |
+
with gr.Column():
|
79 |
+
input_image_path = gr.File(label="Input Image")
|
80 |
+
with gr.Column():
|
81 |
+
generated_image_path = gr.File(label="Download the segment image", interactive=False)
|
82 |
+
with gr.Row():
|
83 |
+
with gr.Column():
|
84 |
+
input_image_prompt = gr.Textbox(lines=1, label="Input Image Prompt", value=DEFAULT_SRC_PROMPT)
|
85 |
+
edit_prompt = gr.Textbox(lines=1, label="Edit Prompt", value=DEFAULT_EDIT_PROMPT)
|
86 |
+
with gr.Accordion("Advanced Options", open=False):
|
87 |
+
guidance_scale = gr.Slider(minimum=0, maximum=20, value=0, step=0.5, label="Guidance Scale")
|
88 |
+
seed = gr.Number(label="Seed", value=8)
|
89 |
+
generate_size = gr.Number(label="Generate Size", value=1024)
|
90 |
+
lineart_scale = gr.Slider(minimum=0, maximum=5, value=0.8, step=0.1, label="Lineart Weights", visible=True)
|
91 |
+
canny_scale = gr.Slider(minimum=0, maximum=5, value=0.4, step=0.1, label="Canny Weights", visible=True)
|
92 |
+
lineart_detect = gr.Number(label="Lineart Detect", value=0.375, visible=True)
|
93 |
+
canny_detect = gr.Number(label="Canny Detect", value=0.375, visible=True)
|
94 |
+
with gr.Column():
|
95 |
+
num_steps = gr.Slider(minimum=1, maximum=100, value=20, step=1, label="Num Steps")
|
96 |
+
start_step = gr.Slider(minimum=1, maximum=100, value=15, step=1, label="Start Step")
|
97 |
+
w1 = gr.Number(label="W1", value=2)
|
98 |
+
g_btn = gr.Button("Edit Image")
|
99 |
+
|
100 |
+
|
101 |
+
g_btn.click(
|
102 |
+
fn=image_to_image,
|
103 |
+
inputs=[input_image_path, input_image_prompt, edit_prompt,seed,w1, num_steps, start_step, guidance_scale, generate_size, lineart_scale, canny_scale, lineart_detect, canny_detect],
|
104 |
+
outputs=[generated_image_path],
|
105 |
+
)
|
106 |
+
|
107 |
+
return demo
|
inversion_run_adapter.py
ADDED
@@ -0,0 +1,254 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
|
3 |
+
from diffusers import (
|
4 |
+
DDPMScheduler,
|
5 |
+
DiffusionPipeline,
|
6 |
+
T2IAdapter,
|
7 |
+
MultiAdapter,
|
8 |
+
)
|
9 |
+
from controlnet_aux import (
|
10 |
+
LineartDetector,
|
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 |
+
class Object(object):
|
21 |
+
pass
|
22 |
+
|
23 |
+
args = Object()
|
24 |
+
args.images_paths = None
|
25 |
+
args.images_folder = None
|
26 |
+
args.force_use_cpu = False
|
27 |
+
args.folder_name = 'test_measure_time'
|
28 |
+
args.config_from_file = 'run_configs/noise_shift_guidance_1_5.yaml'
|
29 |
+
args.save_intermediate_results = False
|
30 |
+
args.batch_size = None
|
31 |
+
args.skip_p_to_p = True
|
32 |
+
args.only_p_to_p = False
|
33 |
+
args.fp16 = False
|
34 |
+
args.prompts_file = 'dataset_measure_time/dataset.json'
|
35 |
+
args.images_in_prompts_file = None
|
36 |
+
args.seed = 986
|
37 |
+
args.time_measure_n = 1
|
38 |
+
|
39 |
+
|
40 |
+
assert (
|
41 |
+
args.batch_size is None or args.save_intermediate_results is False
|
42 |
+
), "save_intermediate_results is not implemented for batch_size > 1"
|
43 |
+
|
44 |
+
generator = None
|
45 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
46 |
+
|
47 |
+
BASE_MODEL = "stabilityai/sdxl-turbo"
|
48 |
+
|
49 |
+
lineart_detector = LineartDetector.from_pretrained("lllyasviel/Annotators")
|
50 |
+
lineart_detector = lineart_detector.to(device)
|
51 |
+
|
52 |
+
canndy_detector = CannyDetector()
|
53 |
+
|
54 |
+
adapters = MultiAdapter(
|
55 |
+
[
|
56 |
+
T2IAdapter.from_pretrained(
|
57 |
+
"TencentARC/t2i-adapter-lineart-sdxl-1.0",
|
58 |
+
torch_dtype=torch.float16,
|
59 |
+
varient="fp16",
|
60 |
+
),
|
61 |
+
T2IAdapter.from_pretrained(
|
62 |
+
"TencentARC/t2i-adapter-canny-sdxl-1.0",
|
63 |
+
torch_dtype=torch.float16,
|
64 |
+
varient="fp16",
|
65 |
+
),
|
66 |
+
]
|
67 |
+
)
|
68 |
+
adapters = adapters.to(torch.float16)
|
69 |
+
|
70 |
+
pipeline = DiffusionPipeline.from_pretrained(
|
71 |
+
BASE_MODEL,
|
72 |
+
torch_dtype=torch.float16,
|
73 |
+
variant="fp16",
|
74 |
+
use_safetensors=True,
|
75 |
+
adapter=adapters,
|
76 |
+
custom_pipeline="./pipelines/pipeline_sdxl_adapter_img2img.py",
|
77 |
+
)
|
78 |
+
pipeline = pipeline.to(device)
|
79 |
+
|
80 |
+
pipeline.scheduler = DDPMScheduler.from_pretrained(
|
81 |
+
BASE_MODEL,
|
82 |
+
subfolder="scheduler",
|
83 |
+
)
|
84 |
+
|
85 |
+
config = get_config(args)
|
86 |
+
|
87 |
+
compel_proc = Compel(
|
88 |
+
tokenizer=[pipeline.tokenizer, pipeline.tokenizer_2] ,
|
89 |
+
text_encoder=[pipeline.text_encoder, pipeline.text_encoder_2],
|
90 |
+
returned_embeddings_type=ReturnedEmbeddingsType.PENULTIMATE_HIDDEN_STATES_NON_NORMALIZED,
|
91 |
+
requires_pooled=[False, True]
|
92 |
+
)
|
93 |
+
|
94 |
+
def run(
|
95 |
+
input_image:Image,
|
96 |
+
src_prompt:str,
|
97 |
+
tgt_prompt:str,
|
98 |
+
generate_size:int,
|
99 |
+
seed:int,
|
100 |
+
w1:float,
|
101 |
+
w2:float,
|
102 |
+
num_steps:int,
|
103 |
+
start_step:int,
|
104 |
+
guidance_scale:float,
|
105 |
+
lineart_scale:float = 0.5,
|
106 |
+
canny_scale:float = 0.5,
|
107 |
+
lineart_detect:float = 0.375,
|
108 |
+
canny_detect:float = 0.375,
|
109 |
+
):
|
110 |
+
generator = torch.Generator().manual_seed(seed)
|
111 |
+
|
112 |
+
config.num_steps_inversion = num_steps
|
113 |
+
config.step_start = start_step
|
114 |
+
num_steps_actual = get_num_steps_actual(config)
|
115 |
+
|
116 |
+
|
117 |
+
num_steps_inversion = config.num_steps_inversion
|
118 |
+
denoising_start = (num_steps_inversion - num_steps_actual) / num_steps_inversion
|
119 |
+
|
120 |
+
timesteps, num_inference_steps = retrieve_timesteps(
|
121 |
+
pipeline.scheduler, num_steps_inversion, device, None
|
122 |
+
)
|
123 |
+
timesteps, num_inference_steps = pipeline.get_timesteps(
|
124 |
+
num_inference_steps=num_inference_steps,
|
125 |
+
denoising_start=denoising_start,
|
126 |
+
strength=0,
|
127 |
+
device=device,
|
128 |
+
)
|
129 |
+
timesteps = timesteps.type(torch.int64)
|
130 |
+
|
131 |
+
timesteps = [torch.tensor(t) for t in timesteps.tolist()]
|
132 |
+
timesteps_len = len(timesteps)
|
133 |
+
config.step_start = start_step + num_steps_actual - timesteps_len
|
134 |
+
num_steps_actual = timesteps_len
|
135 |
+
config.max_norm_zs = [-1] * (num_steps_actual - 1) + [15.5]
|
136 |
+
|
137 |
+
lineart_image = lineart_detector(input_image, detect_resolution=int(generate_size * lineart_detect), image_resolution=generate_size)
|
138 |
+
canny_image = canndy_detector(input_image, detect_resolution=int(generate_size * canny_detect), image_resolution=generate_size)
|
139 |
+
cond_image = [lineart_image, canny_image]
|
140 |
+
conditioning_scale = [lineart_scale, canny_scale]
|
141 |
+
pipeline.__call__ = partial(
|
142 |
+
pipeline.__call__,
|
143 |
+
num_inference_steps=num_steps_inversion,
|
144 |
+
guidance_scale=guidance_scale,
|
145 |
+
generator=generator,
|
146 |
+
denoising_start=denoising_start,
|
147 |
+
strength=0,
|
148 |
+
adapter_image=cond_image,
|
149 |
+
adapter_conditioning_scale=conditioning_scale,
|
150 |
+
)
|
151 |
+
|
152 |
+
x_0_image = input_image
|
153 |
+
x_0 = encode_image(x_0_image, pipeline)
|
154 |
+
x_ts = create_xts(1, None, 0, generator, pipeline.scheduler, timesteps, x_0, no_add_noise=False)
|
155 |
+
x_ts = [xt.to(dtype=torch.float16) for xt in x_ts]
|
156 |
+
latents = [x_ts[0]]
|
157 |
+
x_ts_c_hat = [None]
|
158 |
+
config.ws1 = [w1] * num_steps_actual
|
159 |
+
config.ws2 = [w2] * num_steps_actual
|
160 |
+
pipeline.scheduler = get_ddpm_inversion_scheduler(
|
161 |
+
pipeline.scheduler,
|
162 |
+
config.step_function,
|
163 |
+
config,
|
164 |
+
timesteps,
|
165 |
+
config.save_timesteps,
|
166 |
+
latents,
|
167 |
+
x_ts,
|
168 |
+
x_ts_c_hat,
|
169 |
+
args.save_intermediate_results,
|
170 |
+
pipeline,
|
171 |
+
x_0,
|
172 |
+
v1s_images := [],
|
173 |
+
v2s_images := [],
|
174 |
+
deltas_images := [],
|
175 |
+
v1_x0s := [],
|
176 |
+
v2_x0s := [],
|
177 |
+
deltas_x0s := [],
|
178 |
+
"res12",
|
179 |
+
image_name="im_name",
|
180 |
+
time_measure_n=args.time_measure_n,
|
181 |
+
)
|
182 |
+
latent = latents[0].expand(3, -1, -1, -1)
|
183 |
+
prompt = [src_prompt, src_prompt, tgt_prompt]
|
184 |
+
conditioning, pooled = compel_proc(prompt)
|
185 |
+
|
186 |
+
image = pipeline.__call__(
|
187 |
+
image=latent,
|
188 |
+
prompt_embeds=conditioning,
|
189 |
+
pooled_prompt_embeds=pooled,
|
190 |
+
eta=1,
|
191 |
+
).images
|
192 |
+
return image[2]
|
193 |
+
|
194 |
+
def encode_image(image, pipe):
|
195 |
+
image = pipe.image_processor.preprocess(image)
|
196 |
+
originDtype = pipe.dtype
|
197 |
+
image = image.to(device=device, dtype=originDtype)
|
198 |
+
|
199 |
+
if pipe.vae.config.force_upcast:
|
200 |
+
image = image.float()
|
201 |
+
pipe.vae.to(dtype=torch.float32)
|
202 |
+
|
203 |
+
if isinstance(generator, list):
|
204 |
+
init_latents = [
|
205 |
+
retrieve_latents(pipe.vae.encode(image[i : i + 1]), generator=generator[i])
|
206 |
+
for i in range(1)
|
207 |
+
]
|
208 |
+
init_latents = torch.cat(init_latents, dim=0)
|
209 |
+
else:
|
210 |
+
init_latents = retrieve_latents(pipe.vae.encode(image), generator=generator)
|
211 |
+
|
212 |
+
if pipe.vae.config.force_upcast:
|
213 |
+
pipe.vae.to(originDtype)
|
214 |
+
|
215 |
+
init_latents = init_latents.to(originDtype)
|
216 |
+
init_latents = pipe.vae.config.scaling_factor * init_latents
|
217 |
+
|
218 |
+
return init_latents.to(dtype=torch.float16)
|
219 |
+
|
220 |
+
def get_timesteps(pipe, num_inference_steps, strength, device, denoising_start=None):
|
221 |
+
# get the original timestep using init_timestep
|
222 |
+
if denoising_start is None:
|
223 |
+
init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
|
224 |
+
t_start = max(num_inference_steps - init_timestep, 0)
|
225 |
+
else:
|
226 |
+
t_start = 0
|
227 |
+
|
228 |
+
timesteps = pipe.scheduler.timesteps[t_start * pipe.scheduler.order :]
|
229 |
+
|
230 |
+
# Strength is irrelevant if we directly request a timestep to start at;
|
231 |
+
# that is, strength is determined by the denoising_start instead.
|
232 |
+
if denoising_start is not None:
|
233 |
+
discrete_timestep_cutoff = int(
|
234 |
+
round(
|
235 |
+
pipe.scheduler.config.num_train_timesteps
|
236 |
+
- (denoising_start * pipe.scheduler.config.num_train_timesteps)
|
237 |
+
)
|
238 |
+
)
|
239 |
+
|
240 |
+
num_inference_steps = (timesteps < discrete_timestep_cutoff).sum().item()
|
241 |
+
if pipe.scheduler.order == 2 and num_inference_steps % 2 == 0:
|
242 |
+
# if the scheduler is a 2nd order scheduler we might have to do +1
|
243 |
+
# because `num_inference_steps` might be even given that every timestep
|
244 |
+
# (except the highest one) is duplicated. If `num_inference_steps` is even it would
|
245 |
+
# mean that we cut the timesteps in the middle of the denoising step
|
246 |
+
# (between 1st and 2nd derivative) which leads to incorrect results. By adding 1
|
247 |
+
# we ensure that the denoising process always ends after the 2nd derivate step of the scheduler
|
248 |
+
num_inference_steps = num_inference_steps + 1
|
249 |
+
|
250 |
+
# because t_n+1 >= t_n, we slice the timesteps starting from the end
|
251 |
+
timesteps = timesteps[-num_inference_steps:]
|
252 |
+
return timesteps, num_inference_steps
|
253 |
+
|
254 |
+
return timesteps, num_inference_steps - t_start
|
inversion_run_base.py
CHANGED
@@ -84,7 +84,6 @@ def run(
|
|
84 |
|
85 |
num_steps_inversion = config.num_steps_inversion
|
86 |
denoising_start = (num_steps_inversion - num_steps_actual) / num_steps_inversion
|
87 |
-
print(f"-------->num_steps_inversion: {num_steps_inversion} num_steps_actual: {num_steps_actual} denoising_start: {denoising_start}")
|
88 |
|
89 |
timesteps, num_inference_steps = retrieve_timesteps(
|
90 |
pipeline.scheduler, num_steps_inversion, device, None
|
@@ -102,8 +101,7 @@ def run(
|
|
102 |
config.step_start = start_step + num_steps_actual - timesteps_len
|
103 |
num_steps_actual = timesteps_len
|
104 |
config.max_norm_zs = [-1] * (num_steps_actual - 1) + [15.5]
|
105 |
-
|
106 |
-
print(f"-------->timesteps len: {len(timesteps)} max_norm_zs len: {len(config.max_norm_zs)}")
|
107 |
pipeline.__call__ = partial(
|
108 |
pipeline.__call__,
|
109 |
num_inference_steps=num_steps_inversion,
|
|
|
84 |
|
85 |
num_steps_inversion = config.num_steps_inversion
|
86 |
denoising_start = (num_steps_inversion - num_steps_actual) / num_steps_inversion
|
|
|
87 |
|
88 |
timesteps, num_inference_steps = retrieve_timesteps(
|
89 |
pipeline.scheduler, num_steps_inversion, device, None
|
|
|
101 |
config.step_start = start_step + num_steps_actual - timesteps_len
|
102 |
num_steps_actual = timesteps_len
|
103 |
config.max_norm_zs = [-1] * (num_steps_actual - 1) + [15.5]
|
104 |
+
|
|
|
105 |
pipeline.__call__ = partial(
|
106 |
pipeline.__call__,
|
107 |
num_inference_steps=num_steps_inversion,
|
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)
|
requirements.txt
CHANGED
@@ -11,4 +11,6 @@ compel
|
|
11 |
gfpgan
|
12 |
git+https://github.com/XPixelGroup/BasicSR@master
|
13 |
facexlib
|
14 |
-
realesrgan
|
|
|
|
|
|
11 |
gfpgan
|
12 |
git+https://github.com/XPixelGroup/BasicSR@master
|
13 |
facexlib
|
14 |
+
realesrgan
|
15 |
+
controlnet_aux
|
16 |
+
peft
|