Spaces:
Runtime error
Runtime error
second
Browse files- .gitattributes +1 -0
- .gitignore +4 -0
- README.md +1 -1
- app.py +178 -0
- examples/cybetruck.jpeg +0 -0
- examples/jesus.png +3 -0
- examples/lara.jpeg +0 -0
- gradio_cached_examples/14/component 0/351a0bfafaaecc7814de/image.png +3 -0
- gradio_cached_examples/14/component 0/b34adaae151a4459167b/image.png +3 -0
- gradio_cached_examples/14/component 0/b3e9f831c3822912c747/image.png +3 -0
- gradio_cached_examples/14/component 0/b5498d7a96d85e965a9b/image.png +3 -0
- gradio_cached_examples/14/component 0/bdf0acf00cd9b1c85287/image.png +3 -0
- gradio_cached_examples/14/component 0/e06cb354ee474e562e51/image.png +3 -0
- gradio_cached_examples/14/component 1/3c86c69e7b46e996c594/img_bf8b5bfd-5769-445e-8b04-398fa66b36b1_1024.jpg +0 -0
- gradio_cached_examples/14/component 1/8df9754c0e60183ba8f8/img_bf8b5bfd-5769-445e-8b04-398fa66b36b1_1024.jpg +0 -0
- gradio_cached_examples/14/component 1/cdf61b32958e252f00b9/img_87222732-8f7b-4e26-bfa9-bd5842e2af61_2048.jpg +0 -0
- gradio_cached_examples/14/component 1/d20358db86db5687c4d3/img_87222732-8f7b-4e26-bfa9-bd5842e2af61_1024.jpg +0 -0
- gradio_cached_examples/14/component 1/d51a78500d54f78aef8f/img_2b3a159b-b19d-4810-8678-8dd6762db0c0_2048.jpg +0 -0
- gradio_cached_examples/14/component 1/e80581741e20de234eb8/img_bf8b5bfd-5769-445e-8b04-398fa66b36b1_2048.jpg +0 -0
- gradio_cached_examples/14/component 1/e96cc92c329d8c5f7b30/img_2b3a159b-b19d-4810-8678-8dd6762db0c0_1024.jpg +0 -0
- gradio_cached_examples/14/component 1/ec2cd95acdcb6c98d37e/img_2b3a159b-b19d-4810-8678-8dd6762db0c0_1024.jpg +0 -0
- gradio_cached_examples/14/component 1/ee84949074ae1250919e/img_87222732-8f7b-4e26-bfa9-bd5842e2af61_1024.jpg +0 -0
- gradio_cached_examples/14/log.csv +4 -0
- pipeline_demofusion_sdxl.py +1788 -0
- requirements.txt +13 -0
.gitattributes
CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
+
*.png filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
__pycache__/
|
2 |
+
venv/
|
3 |
+
public/
|
4 |
+
*.pem
|
README.md
CHANGED
@@ -4,7 +4,7 @@ emoji: 💻
|
|
4 |
colorFrom: blue
|
5 |
colorTo: red
|
6 |
sdk: gradio
|
7 |
-
sdk_version: 4.
|
8 |
app_file: app.py
|
9 |
pinned: false
|
10 |
---
|
|
|
4 |
colorFrom: blue
|
5 |
colorTo: red
|
6 |
sdk: gradio
|
7 |
+
sdk_version: 4.8.0
|
8 |
app_file: app.py
|
9 |
pinned: false
|
10 |
---
|
app.py
ADDED
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from gradio_imageslider import ImageSlider
|
3 |
+
import torch
|
4 |
+
from diffusers import DiffusionPipeline, AutoencoderKL
|
5 |
+
from PIL import Image
|
6 |
+
from torchvision import transforms
|
7 |
+
import numpy as np
|
8 |
+
import tempfile
|
9 |
+
import os
|
10 |
+
import uuid
|
11 |
+
|
12 |
+
TORCH_COMPILE = os.getenv("TORCH_COMPILE", "0") == "1"
|
13 |
+
|
14 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
15 |
+
dtype = torch.float16
|
16 |
+
|
17 |
+
vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=dtype)
|
18 |
+
pipe = DiffusionPipeline.from_pretrained(
|
19 |
+
"stabilityai/stable-diffusion-xl-base-1.0",
|
20 |
+
custom_pipeline="pipeline_demofusion_sdxl.py",
|
21 |
+
custom_revision="main",
|
22 |
+
torch_dtype=dtype,
|
23 |
+
variant="fp16",
|
24 |
+
use_safetensors=True,
|
25 |
+
vae=vae,
|
26 |
+
)
|
27 |
+
pipe = pipe.to(device)
|
28 |
+
if TORCH_COMPILE:
|
29 |
+
pipe.unet = torch.compile(pipe.unet, mode="reduce-overhead", fullgraph=True)
|
30 |
+
|
31 |
+
|
32 |
+
def load_and_process_image(pil_image):
|
33 |
+
transform = transforms.Compose(
|
34 |
+
[
|
35 |
+
transforms.Resize((1024, 1024)),
|
36 |
+
transforms.ToTensor(),
|
37 |
+
transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
|
38 |
+
]
|
39 |
+
)
|
40 |
+
image = transform(pil_image)
|
41 |
+
image = image.unsqueeze(0).half()
|
42 |
+
return image
|
43 |
+
|
44 |
+
|
45 |
+
def pad_image(image):
|
46 |
+
w, h = image.size
|
47 |
+
if w == h:
|
48 |
+
return image
|
49 |
+
elif w > h:
|
50 |
+
new_image = Image.new(image.mode, (w, w), (0, 0, 0))
|
51 |
+
pad_w = 0
|
52 |
+
pad_h = (w - h) // 2
|
53 |
+
new_image.paste(image, (0, pad_h))
|
54 |
+
return new_image
|
55 |
+
else:
|
56 |
+
new_image = Image.new(image.mode, (h, h), (0, 0, 0))
|
57 |
+
pad_w = (h - w) // 2
|
58 |
+
pad_h = 0
|
59 |
+
new_image.paste(image, (pad_w, 0))
|
60 |
+
return new_image
|
61 |
+
|
62 |
+
|
63 |
+
def predict(
|
64 |
+
input_image,
|
65 |
+
prompt,
|
66 |
+
negative_prompt,
|
67 |
+
seed,
|
68 |
+
scale=2,
|
69 |
+
progress=gr.Progress(track_tqdm=True),
|
70 |
+
):
|
71 |
+
if input_image is None:
|
72 |
+
raise gr.Error("Please upload an image.")
|
73 |
+
padded_image = pad_image(input_image).resize((1024, 1024))
|
74 |
+
padded_image.save(f"padded_image+{seed}.jpg")
|
75 |
+
image_lr = load_and_process_image(padded_image).to(device)
|
76 |
+
generator = torch.manual_seed(seed)
|
77 |
+
images = pipe(
|
78 |
+
prompt,
|
79 |
+
negative_prompt=negative_prompt,
|
80 |
+
image_lr=image_lr,
|
81 |
+
width=1024 * scale,
|
82 |
+
height=1024 * scale,
|
83 |
+
view_batch_size=16,
|
84 |
+
stride=64,
|
85 |
+
generator=generator,
|
86 |
+
num_inference_steps=25,
|
87 |
+
guidance_scale=7.5,
|
88 |
+
cosine_scale_1=3,
|
89 |
+
cosine_scale_2=1,
|
90 |
+
cosine_scale_3=1,
|
91 |
+
sigma=0.8,
|
92 |
+
multi_decoder=True,
|
93 |
+
show_image=False,
|
94 |
+
lowvram=True,
|
95 |
+
)
|
96 |
+
images_path = tempfile.mkdtemp()
|
97 |
+
paths = []
|
98 |
+
uuid_name = uuid.uuid4()
|
99 |
+
for i, img in enumerate(images):
|
100 |
+
img.save(images_path + f"/img_{uuid_name}_{img.size[0]}.jpg")
|
101 |
+
paths.append(images_path + f"/img_{uuid_name}_{img.size[0]}.jpg")
|
102 |
+
return (images[0], images[-1]), paths
|
103 |
+
|
104 |
+
|
105 |
+
css = """
|
106 |
+
#intro{
|
107 |
+
max-width: 100%;
|
108 |
+
text-align: center;
|
109 |
+
margin: 0 auto;
|
110 |
+
}
|
111 |
+
"""
|
112 |
+
|
113 |
+
with gr.Blocks(css=css) as demo:
|
114 |
+
gr.Markdown(
|
115 |
+
"""# Super Resolution - SDXL
|
116 |
+
## [DemoFusion](https://github.com/PRIS-CV/DemoFusion)""",
|
117 |
+
elem_id="intro",
|
118 |
+
)
|
119 |
+
with gr.Row():
|
120 |
+
with gr.Column(scale=1):
|
121 |
+
image_input = gr.Image(type="pil", label="Input Image")
|
122 |
+
prompt = gr.Textbox(
|
123 |
+
label="Prompt",
|
124 |
+
info="The prompt is very important to get the desired results. Please try to describe the image as best as you can.",
|
125 |
+
)
|
126 |
+
negative_prompt = gr.Textbox(
|
127 |
+
label="Negative Prompt",
|
128 |
+
value="blurry, ugly, duplicate, poorly drawn, deformed, mosaic",
|
129 |
+
)
|
130 |
+
scale = gr.Slider(minimum=2, maximum=5, value=2, step=1, label="x Scale")
|
131 |
+
seed = gr.Slider(
|
132 |
+
minimum=0,
|
133 |
+
maximum=2**64 - 1,
|
134 |
+
value=1415926535897932,
|
135 |
+
step=1,
|
136 |
+
label="Seed",
|
137 |
+
randomize=True,
|
138 |
+
)
|
139 |
+
btn = gr.Button()
|
140 |
+
with gr.Column(scale=2):
|
141 |
+
image_slider = ImageSlider()
|
142 |
+
files = gr.Files()
|
143 |
+
inputs = [image_input, prompt, negative_prompt, seed, scale]
|
144 |
+
outputs = [image_slider, files]
|
145 |
+
btn.click(predict, inputs=inputs, outputs=outputs, concurrency_limit=1)
|
146 |
+
gr.Examples(
|
147 |
+
fn=predict,
|
148 |
+
examples=[
|
149 |
+
[
|
150 |
+
"./examples/lara.jpeg",
|
151 |
+
"photography of lara croft 8k high definition award winning",
|
152 |
+
"blurry, ugly, duplicate, poorly drawn, deformed, mosaic",
|
153 |
+
1415535897932,
|
154 |
+
2,
|
155 |
+
],
|
156 |
+
[
|
157 |
+
"./examples/cybetruck.jpeg",
|
158 |
+
"photo of tesla cybertruck futuristic car 8k high definition on a sand dune in mars, future",
|
159 |
+
"blurry, ugly, duplicate, poorly drawn, deformed, mosaic",
|
160 |
+
1415535897932,
|
161 |
+
2,
|
162 |
+
],
|
163 |
+
[
|
164 |
+
"./examples/jesus.png",
|
165 |
+
"a photorealistic painting of Jesus Christ, 4k high definition",
|
166 |
+
"blurry, ugly, duplicate, poorly drawn, deformed, mosaic",
|
167 |
+
1415535897932,
|
168 |
+
2,
|
169 |
+
],
|
170 |
+
],
|
171 |
+
inputs=inputs,
|
172 |
+
outputs=outputs,
|
173 |
+
cache_examples=True,
|
174 |
+
)
|
175 |
+
|
176 |
+
|
177 |
+
demo.queue(api_open=False)
|
178 |
+
demo.launch(show_api=False)
|
examples/cybetruck.jpeg
ADDED
examples/jesus.png
ADDED
Git LFS Details
|
examples/lara.jpeg
ADDED
gradio_cached_examples/14/component 0/351a0bfafaaecc7814de/image.png
ADDED
Git LFS Details
|
gradio_cached_examples/14/component 0/b34adaae151a4459167b/image.png
ADDED
Git LFS Details
|
gradio_cached_examples/14/component 0/b3e9f831c3822912c747/image.png
ADDED
Git LFS Details
|
gradio_cached_examples/14/component 0/b5498d7a96d85e965a9b/image.png
ADDED
Git LFS Details
|
gradio_cached_examples/14/component 0/bdf0acf00cd9b1c85287/image.png
ADDED
Git LFS Details
|
gradio_cached_examples/14/component 0/e06cb354ee474e562e51/image.png
ADDED
Git LFS Details
|
gradio_cached_examples/14/component 1/3c86c69e7b46e996c594/img_bf8b5bfd-5769-445e-8b04-398fa66b36b1_1024.jpg
ADDED
gradio_cached_examples/14/component 1/8df9754c0e60183ba8f8/img_bf8b5bfd-5769-445e-8b04-398fa66b36b1_1024.jpg
ADDED
gradio_cached_examples/14/component 1/cdf61b32958e252f00b9/img_87222732-8f7b-4e26-bfa9-bd5842e2af61_2048.jpg
ADDED
gradio_cached_examples/14/component 1/d20358db86db5687c4d3/img_87222732-8f7b-4e26-bfa9-bd5842e2af61_1024.jpg
ADDED
gradio_cached_examples/14/component 1/d51a78500d54f78aef8f/img_2b3a159b-b19d-4810-8678-8dd6762db0c0_2048.jpg
ADDED
gradio_cached_examples/14/component 1/e80581741e20de234eb8/img_bf8b5bfd-5769-445e-8b04-398fa66b36b1_2048.jpg
ADDED
gradio_cached_examples/14/component 1/e96cc92c329d8c5f7b30/img_2b3a159b-b19d-4810-8678-8dd6762db0c0_1024.jpg
ADDED
gradio_cached_examples/14/component 1/ec2cd95acdcb6c98d37e/img_2b3a159b-b19d-4810-8678-8dd6762db0c0_1024.jpg
ADDED
gradio_cached_examples/14/component 1/ee84949074ae1250919e/img_87222732-8f7b-4e26-bfa9-bd5842e2af61_1024.jpg
ADDED
gradio_cached_examples/14/log.csv
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
component 0,component 1,flag,username,timestamp
|
2 |
+
"[{""path"":""gradio_cached_examples/14/component 0/b5498d7a96d85e965a9b/image.png"",""url"":null,""size"":null,""orig_name"":null,""mime_type"":null},{""path"":""gradio_cached_examples/14/component 0/b34adaae151a4459167b/image.png"",""url"":null,""size"":null,""orig_name"":null,""mime_type"":null}]","[{""path"":""gradio_cached_examples/14/component 1/8df9754c0e60183ba8f8/img_bf8b5bfd-5769-445e-8b04-398fa66b36b1_1024.jpg"",""url"":null,""size"":65560,""orig_name"":""img_bf8b5bfd-5769-445e-8b04-398fa66b36b1_1024.jpg"",""mime_type"":null},{""path"":""gradio_cached_examples/14/component 1/3c86c69e7b46e996c594/img_bf8b5bfd-5769-445e-8b04-398fa66b36b1_1024.jpg"",""url"":null,""size"":65560,""orig_name"":""img_bf8b5bfd-5769-445e-8b04-398fa66b36b1_1024.jpg"",""mime_type"":null},{""path"":""gradio_cached_examples/14/component 1/e80581741e20de234eb8/img_bf8b5bfd-5769-445e-8b04-398fa66b36b1_2048.jpg"",""url"":null,""size"":165512,""orig_name"":""img_bf8b5bfd-5769-445e-8b04-398fa66b36b1_2048.jpg"",""mime_type"":null}]",,,2023-12-06 19:52:37.669846
|
3 |
+
"[{""path"":""gradio_cached_examples/14/component 0/351a0bfafaaecc7814de/image.png"",""url"":null,""size"":null,""orig_name"":null,""mime_type"":null},{""path"":""gradio_cached_examples/14/component 0/e06cb354ee474e562e51/image.png"",""url"":null,""size"":null,""orig_name"":null,""mime_type"":null}]","[{""path"":""gradio_cached_examples/14/component 1/ee84949074ae1250919e/img_87222732-8f7b-4e26-bfa9-bd5842e2af61_1024.jpg"",""url"":null,""size"":65506,""orig_name"":""img_87222732-8f7b-4e26-bfa9-bd5842e2af61_1024.jpg"",""mime_type"":null},{""path"":""gradio_cached_examples/14/component 1/d20358db86db5687c4d3/img_87222732-8f7b-4e26-bfa9-bd5842e2af61_1024.jpg"",""url"":null,""size"":65506,""orig_name"":""img_87222732-8f7b-4e26-bfa9-bd5842e2af61_1024.jpg"",""mime_type"":null},{""path"":""gradio_cached_examples/14/component 1/cdf61b32958e252f00b9/img_87222732-8f7b-4e26-bfa9-bd5842e2af61_2048.jpg"",""url"":null,""size"":244888,""orig_name"":""img_87222732-8f7b-4e26-bfa9-bd5842e2af61_2048.jpg"",""mime_type"":null}]",,,2023-12-06 19:53:55.398688
|
4 |
+
"[{""path"":""gradio_cached_examples/14/component 0/bdf0acf00cd9b1c85287/image.png"",""url"":null,""size"":null,""orig_name"":null,""mime_type"":null},{""path"":""gradio_cached_examples/14/component 0/b3e9f831c3822912c747/image.png"",""url"":null,""size"":null,""orig_name"":null,""mime_type"":null}]","[{""path"":""gradio_cached_examples/14/component 1/e96cc92c329d8c5f7b30/img_2b3a159b-b19d-4810-8678-8dd6762db0c0_1024.jpg"",""url"":null,""size"":47077,""orig_name"":""img_2b3a159b-b19d-4810-8678-8dd6762db0c0_1024.jpg"",""mime_type"":null},{""path"":""gradio_cached_examples/14/component 1/ec2cd95acdcb6c98d37e/img_2b3a159b-b19d-4810-8678-8dd6762db0c0_1024.jpg"",""url"":null,""size"":47077,""orig_name"":""img_2b3a159b-b19d-4810-8678-8dd6762db0c0_1024.jpg"",""mime_type"":null},{""path"":""gradio_cached_examples/14/component 1/d51a78500d54f78aef8f/img_2b3a159b-b19d-4810-8678-8dd6762db0c0_2048.jpg"",""url"":null,""size"":143073,""orig_name"":""img_2b3a159b-b19d-4810-8678-8dd6762db0c0_2048.jpg"",""mime_type"":null}]",,,2023-12-06 19:55:13.167461
|
pipeline_demofusion_sdxl.py
ADDED
@@ -0,0 +1,1788 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
2 |
+
#
|
3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
# you may not use this file except in compliance with the License.
|
5 |
+
# You may obtain a copy of the License at
|
6 |
+
#
|
7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
#
|
9 |
+
# Unless required by applicable law or agreed to in writing, software
|
10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
+
# See the License for the specific language governing permissions and
|
13 |
+
# limitations under the License.
|
14 |
+
|
15 |
+
import inspect
|
16 |
+
import os
|
17 |
+
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
|
18 |
+
import matplotlib.pyplot as plt
|
19 |
+
|
20 |
+
import torch
|
21 |
+
import torch.nn.functional as F
|
22 |
+
import numpy as np
|
23 |
+
import random
|
24 |
+
import warnings
|
25 |
+
from transformers import CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer
|
26 |
+
|
27 |
+
from diffusers.image_processor import VaeImageProcessor
|
28 |
+
from diffusers.loaders import (
|
29 |
+
FromSingleFileMixin,
|
30 |
+
LoraLoaderMixin,
|
31 |
+
TextualInversionLoaderMixin,
|
32 |
+
)
|
33 |
+
from diffusers.models import AutoencoderKL, UNet2DConditionModel
|
34 |
+
from diffusers.models.attention_processor import (
|
35 |
+
AttnProcessor2_0,
|
36 |
+
LoRAAttnProcessor2_0,
|
37 |
+
LoRAXFormersAttnProcessor,
|
38 |
+
XFormersAttnProcessor,
|
39 |
+
)
|
40 |
+
from diffusers.models.lora import adjust_lora_scale_text_encoder
|
41 |
+
from diffusers.schedulers import KarrasDiffusionSchedulers
|
42 |
+
from diffusers.utils import (
|
43 |
+
is_accelerate_available,
|
44 |
+
is_accelerate_version,
|
45 |
+
is_invisible_watermark_available,
|
46 |
+
logging,
|
47 |
+
replace_example_docstring,
|
48 |
+
)
|
49 |
+
from diffusers.utils.torch_utils import randn_tensor
|
50 |
+
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
|
51 |
+
from diffusers.pipelines.stable_diffusion_xl import StableDiffusionXLPipelineOutput
|
52 |
+
|
53 |
+
|
54 |
+
if is_invisible_watermark_available():
|
55 |
+
from diffusers.pipelines.stable_diffusion_xl.watermark import (
|
56 |
+
StableDiffusionXLWatermarker,
|
57 |
+
)
|
58 |
+
|
59 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
60 |
+
|
61 |
+
EXAMPLE_DOC_STRING = """
|
62 |
+
Examples:
|
63 |
+
```py
|
64 |
+
>>> import torch
|
65 |
+
>>> from diffusers import StableDiffusionXLPipeline
|
66 |
+
|
67 |
+
>>> pipe = StableDiffusionXLPipeline.from_pretrained(
|
68 |
+
... "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
|
69 |
+
... )
|
70 |
+
>>> pipe = pipe.to("cuda")
|
71 |
+
|
72 |
+
>>> prompt = "a photo of an astronaut riding a horse on mars"
|
73 |
+
>>> image = pipe(prompt).images[0]
|
74 |
+
```
|
75 |
+
"""
|
76 |
+
|
77 |
+
|
78 |
+
def gaussian_kernel(kernel_size=3, sigma=1.0, channels=3):
|
79 |
+
x_coord = torch.arange(kernel_size)
|
80 |
+
gaussian_1d = torch.exp(
|
81 |
+
-((x_coord - (kernel_size - 1) / 2) ** 2) / (2 * sigma**2)
|
82 |
+
)
|
83 |
+
gaussian_1d = gaussian_1d / gaussian_1d.sum()
|
84 |
+
gaussian_2d = gaussian_1d[:, None] * gaussian_1d[None, :]
|
85 |
+
kernel = gaussian_2d[None, None, :, :].repeat(channels, 1, 1, 1)
|
86 |
+
|
87 |
+
return kernel
|
88 |
+
|
89 |
+
|
90 |
+
def gaussian_filter(latents, kernel_size=3, sigma=1.0):
|
91 |
+
channels = latents.shape[1]
|
92 |
+
kernel = gaussian_kernel(kernel_size, sigma, channels).to(
|
93 |
+
latents.device, latents.dtype
|
94 |
+
)
|
95 |
+
blurred_latents = F.conv2d(
|
96 |
+
latents, kernel, padding=kernel_size // 2, groups=channels
|
97 |
+
)
|
98 |
+
|
99 |
+
return blurred_latents
|
100 |
+
|
101 |
+
|
102 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
|
103 |
+
def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
|
104 |
+
"""
|
105 |
+
Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
|
106 |
+
Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
|
107 |
+
"""
|
108 |
+
std_text = noise_pred_text.std(
|
109 |
+
dim=list(range(1, noise_pred_text.ndim)), keepdim=True
|
110 |
+
)
|
111 |
+
std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
|
112 |
+
# rescale the results from guidance (fixes overexposure)
|
113 |
+
noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
|
114 |
+
# mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
|
115 |
+
noise_cfg = (
|
116 |
+
guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
|
117 |
+
)
|
118 |
+
return noise_cfg
|
119 |
+
|
120 |
+
|
121 |
+
class DemoFusionSDXLPipeline(
|
122 |
+
DiffusionPipeline, FromSingleFileMixin, LoraLoaderMixin, TextualInversionLoaderMixin
|
123 |
+
):
|
124 |
+
r"""
|
125 |
+
Pipeline for text-to-image generation using Stable Diffusion XL.
|
126 |
+
|
127 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
|
128 |
+
library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
|
129 |
+
|
130 |
+
In addition the pipeline inherits the following loading methods:
|
131 |
+
- *LoRA*: [`StableDiffusionXLPipeline.load_lora_weights`]
|
132 |
+
- *Ckpt*: [`loaders.FromSingleFileMixin.from_single_file`]
|
133 |
+
|
134 |
+
as well as the following saving methods:
|
135 |
+
- *LoRA*: [`loaders.StableDiffusionXLPipeline.save_lora_weights`]
|
136 |
+
|
137 |
+
Args:
|
138 |
+
vae ([`AutoencoderKL`]):
|
139 |
+
Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
|
140 |
+
text_encoder ([`CLIPTextModel`]):
|
141 |
+
Frozen text-encoder. Stable Diffusion XL uses the text portion of
|
142 |
+
[CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
|
143 |
+
the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
|
144 |
+
text_encoder_2 ([` CLIPTextModelWithProjection`]):
|
145 |
+
Second frozen text-encoder. Stable Diffusion XL uses the text and pool portion of
|
146 |
+
[CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
|
147 |
+
specifically the
|
148 |
+
[laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)
|
149 |
+
variant.
|
150 |
+
tokenizer (`CLIPTokenizer`):
|
151 |
+
Tokenizer of class
|
152 |
+
[CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
|
153 |
+
tokenizer_2 (`CLIPTokenizer`):
|
154 |
+
Second Tokenizer of class
|
155 |
+
[CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
|
156 |
+
unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
|
157 |
+
scheduler ([`SchedulerMixin`]):
|
158 |
+
A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
|
159 |
+
[`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
|
160 |
+
force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"True"`):
|
161 |
+
Whether the negative prompt embeddings shall be forced to always be set to 0. Also see the config of
|
162 |
+
`stabilityai/stable-diffusion-xl-base-1-0`.
|
163 |
+
add_watermarker (`bool`, *optional*):
|
164 |
+
Whether to use the [invisible_watermark library](https://github.com/ShieldMnt/invisible-watermark/) to
|
165 |
+
watermark output images. If not defined, it will default to True if the package is installed, otherwise no
|
166 |
+
watermarker will be used.
|
167 |
+
"""
|
168 |
+
model_cpu_offload_seq = "text_encoder->text_encoder_2->unet->vae"
|
169 |
+
|
170 |
+
def __init__(
|
171 |
+
self,
|
172 |
+
vae: AutoencoderKL,
|
173 |
+
text_encoder: CLIPTextModel,
|
174 |
+
text_encoder_2: CLIPTextModelWithProjection,
|
175 |
+
tokenizer: CLIPTokenizer,
|
176 |
+
tokenizer_2: CLIPTokenizer,
|
177 |
+
unet: UNet2DConditionModel,
|
178 |
+
scheduler: KarrasDiffusionSchedulers,
|
179 |
+
force_zeros_for_empty_prompt: bool = True,
|
180 |
+
add_watermarker: Optional[bool] = None,
|
181 |
+
):
|
182 |
+
super().__init__()
|
183 |
+
|
184 |
+
self.register_modules(
|
185 |
+
vae=vae,
|
186 |
+
text_encoder=text_encoder,
|
187 |
+
text_encoder_2=text_encoder_2,
|
188 |
+
tokenizer=tokenizer,
|
189 |
+
tokenizer_2=tokenizer_2,
|
190 |
+
unet=unet,
|
191 |
+
scheduler=scheduler,
|
192 |
+
)
|
193 |
+
self.register_to_config(
|
194 |
+
force_zeros_for_empty_prompt=force_zeros_for_empty_prompt
|
195 |
+
)
|
196 |
+
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
197 |
+
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
|
198 |
+
self.default_sample_size = self.unet.config.sample_size
|
199 |
+
|
200 |
+
add_watermarker = (
|
201 |
+
add_watermarker
|
202 |
+
if add_watermarker is not None
|
203 |
+
else is_invisible_watermark_available()
|
204 |
+
)
|
205 |
+
|
206 |
+
if add_watermarker:
|
207 |
+
self.watermark = StableDiffusionXLWatermarker()
|
208 |
+
else:
|
209 |
+
self.watermark = None
|
210 |
+
|
211 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_slicing
|
212 |
+
def enable_vae_slicing(self):
|
213 |
+
r"""
|
214 |
+
Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
|
215 |
+
compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
|
216 |
+
"""
|
217 |
+
self.vae.enable_slicing()
|
218 |
+
|
219 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_slicing
|
220 |
+
def disable_vae_slicing(self):
|
221 |
+
r"""
|
222 |
+
Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
|
223 |
+
computing decoding in one step.
|
224 |
+
"""
|
225 |
+
self.vae.disable_slicing()
|
226 |
+
|
227 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_tiling
|
228 |
+
def enable_vae_tiling(self):
|
229 |
+
r"""
|
230 |
+
Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
|
231 |
+
compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
|
232 |
+
processing larger images.
|
233 |
+
"""
|
234 |
+
self.vae.enable_tiling()
|
235 |
+
|
236 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_tiling
|
237 |
+
def disable_vae_tiling(self):
|
238 |
+
r"""
|
239 |
+
Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
|
240 |
+
computing decoding in one step.
|
241 |
+
"""
|
242 |
+
self.vae.disable_tiling()
|
243 |
+
|
244 |
+
def encode_prompt(
|
245 |
+
self,
|
246 |
+
prompt: str,
|
247 |
+
prompt_2: Optional[str] = None,
|
248 |
+
device: Optional[torch.device] = None,
|
249 |
+
num_images_per_prompt: int = 1,
|
250 |
+
do_classifier_free_guidance: bool = True,
|
251 |
+
negative_prompt: Optional[str] = None,
|
252 |
+
negative_prompt_2: Optional[str] = None,
|
253 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
254 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
255 |
+
pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
256 |
+
negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
257 |
+
lora_scale: Optional[float] = None,
|
258 |
+
):
|
259 |
+
r"""
|
260 |
+
Encodes the prompt into text encoder hidden states.
|
261 |
+
|
262 |
+
Args:
|
263 |
+
prompt (`str` or `List[str]`, *optional*):
|
264 |
+
prompt to be encoded
|
265 |
+
prompt_2 (`str` or `List[str]`, *optional*):
|
266 |
+
The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
|
267 |
+
used in both text-encoders
|
268 |
+
device: (`torch.device`):
|
269 |
+
torch device
|
270 |
+
num_images_per_prompt (`int`):
|
271 |
+
number of images that should be generated per prompt
|
272 |
+
do_classifier_free_guidance (`bool`):
|
273 |
+
whether to use classifier free guidance or not
|
274 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
275 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
276 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
277 |
+
less than `1`).
|
278 |
+
negative_prompt_2 (`str` or `List[str]`, *optional*):
|
279 |
+
The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
|
280 |
+
`text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
|
281 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
282 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
283 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
284 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
285 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
286 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
287 |
+
argument.
|
288 |
+
pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
289 |
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
290 |
+
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
291 |
+
negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
292 |
+
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
293 |
+
weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
|
294 |
+
input argument.
|
295 |
+
lora_scale (`float`, *optional*):
|
296 |
+
A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
|
297 |
+
"""
|
298 |
+
device = device or self._execution_device
|
299 |
+
|
300 |
+
# set lora scale so that monkey patched LoRA
|
301 |
+
# function of text encoder can correctly access it
|
302 |
+
if lora_scale is not None and isinstance(self, LoraLoaderMixin):
|
303 |
+
self._lora_scale = lora_scale
|
304 |
+
|
305 |
+
# dynamically adjust the LoRA scale
|
306 |
+
adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
|
307 |
+
adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
|
308 |
+
|
309 |
+
if prompt is not None and isinstance(prompt, str):
|
310 |
+
batch_size = 1
|
311 |
+
elif prompt is not None and isinstance(prompt, list):
|
312 |
+
batch_size = len(prompt)
|
313 |
+
else:
|
314 |
+
batch_size = prompt_embeds.shape[0]
|
315 |
+
|
316 |
+
# Define tokenizers and text encoders
|
317 |
+
tokenizers = (
|
318 |
+
[self.tokenizer, self.tokenizer_2]
|
319 |
+
if self.tokenizer is not None
|
320 |
+
else [self.tokenizer_2]
|
321 |
+
)
|
322 |
+
text_encoders = (
|
323 |
+
[self.text_encoder, self.text_encoder_2]
|
324 |
+
if self.text_encoder is not None
|
325 |
+
else [self.text_encoder_2]
|
326 |
+
)
|
327 |
+
|
328 |
+
if prompt_embeds is None:
|
329 |
+
prompt_2 = prompt_2 or prompt
|
330 |
+
# textual inversion: procecss multi-vector tokens if necessary
|
331 |
+
prompt_embeds_list = []
|
332 |
+
prompts = [prompt, prompt_2]
|
333 |
+
for prompt, tokenizer, text_encoder in zip(
|
334 |
+
prompts, tokenizers, text_encoders
|
335 |
+
):
|
336 |
+
if isinstance(self, TextualInversionLoaderMixin):
|
337 |
+
prompt = self.maybe_convert_prompt(prompt, tokenizer)
|
338 |
+
|
339 |
+
text_inputs = tokenizer(
|
340 |
+
prompt,
|
341 |
+
padding="max_length",
|
342 |
+
max_length=tokenizer.model_max_length,
|
343 |
+
truncation=True,
|
344 |
+
return_tensors="pt",
|
345 |
+
)
|
346 |
+
|
347 |
+
text_input_ids = text_inputs.input_ids
|
348 |
+
untruncated_ids = tokenizer(
|
349 |
+
prompt, padding="longest", return_tensors="pt"
|
350 |
+
).input_ids
|
351 |
+
|
352 |
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[
|
353 |
+
-1
|
354 |
+
] and not torch.equal(text_input_ids, untruncated_ids):
|
355 |
+
removed_text = tokenizer.batch_decode(
|
356 |
+
untruncated_ids[:, tokenizer.model_max_length - 1 : -1]
|
357 |
+
)
|
358 |
+
logger.warning(
|
359 |
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
360 |
+
f" {tokenizer.model_max_length} tokens: {removed_text}"
|
361 |
+
)
|
362 |
+
|
363 |
+
prompt_embeds = text_encoder(
|
364 |
+
text_input_ids.to(device),
|
365 |
+
output_hidden_states=True,
|
366 |
+
)
|
367 |
+
|
368 |
+
# We are only ALWAYS interested in the pooled output of the final text encoder
|
369 |
+
pooled_prompt_embeds = prompt_embeds[0]
|
370 |
+
prompt_embeds = prompt_embeds.hidden_states[-2]
|
371 |
+
|
372 |
+
prompt_embeds_list.append(prompt_embeds)
|
373 |
+
|
374 |
+
prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
|
375 |
+
|
376 |
+
# get unconditional embeddings for classifier free guidance
|
377 |
+
zero_out_negative_prompt = (
|
378 |
+
negative_prompt is None and self.config.force_zeros_for_empty_prompt
|
379 |
+
)
|
380 |
+
if (
|
381 |
+
do_classifier_free_guidance
|
382 |
+
and negative_prompt_embeds is None
|
383 |
+
and zero_out_negative_prompt
|
384 |
+
):
|
385 |
+
negative_prompt_embeds = torch.zeros_like(prompt_embeds)
|
386 |
+
negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
|
387 |
+
elif do_classifier_free_guidance and negative_prompt_embeds is None:
|
388 |
+
negative_prompt = negative_prompt or ""
|
389 |
+
negative_prompt_2 = negative_prompt_2 or negative_prompt
|
390 |
+
|
391 |
+
uncond_tokens: List[str]
|
392 |
+
if prompt is not None and type(prompt) is not type(negative_prompt):
|
393 |
+
raise TypeError(
|
394 |
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
395 |
+
f" {type(prompt)}."
|
396 |
+
)
|
397 |
+
elif isinstance(negative_prompt, str):
|
398 |
+
uncond_tokens = [negative_prompt, negative_prompt_2]
|
399 |
+
elif batch_size != len(negative_prompt):
|
400 |
+
raise ValueError(
|
401 |
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
402 |
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
403 |
+
" the batch size of `prompt`."
|
404 |
+
)
|
405 |
+
else:
|
406 |
+
uncond_tokens = [negative_prompt, negative_prompt_2]
|
407 |
+
|
408 |
+
negative_prompt_embeds_list = []
|
409 |
+
for negative_prompt, tokenizer, text_encoder in zip(
|
410 |
+
uncond_tokens, tokenizers, text_encoders
|
411 |
+
):
|
412 |
+
if isinstance(self, TextualInversionLoaderMixin):
|
413 |
+
negative_prompt = self.maybe_convert_prompt(
|
414 |
+
negative_prompt, tokenizer
|
415 |
+
)
|
416 |
+
|
417 |
+
max_length = prompt_embeds.shape[1]
|
418 |
+
uncond_input = tokenizer(
|
419 |
+
negative_prompt,
|
420 |
+
padding="max_length",
|
421 |
+
max_length=max_length,
|
422 |
+
truncation=True,
|
423 |
+
return_tensors="pt",
|
424 |
+
)
|
425 |
+
|
426 |
+
negative_prompt_embeds = text_encoder(
|
427 |
+
uncond_input.input_ids.to(device),
|
428 |
+
output_hidden_states=True,
|
429 |
+
)
|
430 |
+
# We are only ALWAYS interested in the pooled output of the final text encoder
|
431 |
+
negative_pooled_prompt_embeds = negative_prompt_embeds[0]
|
432 |
+
negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
|
433 |
+
|
434 |
+
negative_prompt_embeds_list.append(negative_prompt_embeds)
|
435 |
+
|
436 |
+
negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
|
437 |
+
|
438 |
+
prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
|
439 |
+
bs_embed, seq_len, _ = prompt_embeds.shape
|
440 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
441 |
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
442 |
+
prompt_embeds = prompt_embeds.view(
|
443 |
+
bs_embed * num_images_per_prompt, seq_len, -1
|
444 |
+
)
|
445 |
+
|
446 |
+
if do_classifier_free_guidance:
|
447 |
+
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
|
448 |
+
seq_len = negative_prompt_embeds.shape[1]
|
449 |
+
negative_prompt_embeds = negative_prompt_embeds.to(
|
450 |
+
dtype=self.text_encoder_2.dtype, device=device
|
451 |
+
)
|
452 |
+
negative_prompt_embeds = negative_prompt_embeds.repeat(
|
453 |
+
1, num_images_per_prompt, 1
|
454 |
+
)
|
455 |
+
negative_prompt_embeds = negative_prompt_embeds.view(
|
456 |
+
batch_size * num_images_per_prompt, seq_len, -1
|
457 |
+
)
|
458 |
+
|
459 |
+
pooled_prompt_embeds = pooled_prompt_embeds.repeat(
|
460 |
+
1, num_images_per_prompt
|
461 |
+
).view(bs_embed * num_images_per_prompt, -1)
|
462 |
+
if do_classifier_free_guidance:
|
463 |
+
negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(
|
464 |
+
1, num_images_per_prompt
|
465 |
+
).view(bs_embed * num_images_per_prompt, -1)
|
466 |
+
|
467 |
+
return (
|
468 |
+
prompt_embeds,
|
469 |
+
negative_prompt_embeds,
|
470 |
+
pooled_prompt_embeds,
|
471 |
+
negative_pooled_prompt_embeds,
|
472 |
+
)
|
473 |
+
|
474 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
|
475 |
+
def prepare_extra_step_kwargs(self, generator, eta):
|
476 |
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
477 |
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
478 |
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
479 |
+
# and should be between [0, 1]
|
480 |
+
|
481 |
+
accepts_eta = "eta" in set(
|
482 |
+
inspect.signature(self.scheduler.step).parameters.keys()
|
483 |
+
)
|
484 |
+
extra_step_kwargs = {}
|
485 |
+
if accepts_eta:
|
486 |
+
extra_step_kwargs["eta"] = eta
|
487 |
+
|
488 |
+
# check if the scheduler accepts generator
|
489 |
+
accepts_generator = "generator" in set(
|
490 |
+
inspect.signature(self.scheduler.step).parameters.keys()
|
491 |
+
)
|
492 |
+
if accepts_generator:
|
493 |
+
extra_step_kwargs["generator"] = generator
|
494 |
+
return extra_step_kwargs
|
495 |
+
|
496 |
+
def check_inputs(
|
497 |
+
self,
|
498 |
+
prompt,
|
499 |
+
prompt_2,
|
500 |
+
height,
|
501 |
+
width,
|
502 |
+
callback_steps,
|
503 |
+
negative_prompt=None,
|
504 |
+
negative_prompt_2=None,
|
505 |
+
prompt_embeds=None,
|
506 |
+
negative_prompt_embeds=None,
|
507 |
+
pooled_prompt_embeds=None,
|
508 |
+
negative_pooled_prompt_embeds=None,
|
509 |
+
num_images_per_prompt=None,
|
510 |
+
):
|
511 |
+
if height % 8 != 0 or width % 8 != 0:
|
512 |
+
raise ValueError(
|
513 |
+
f"`height` and `width` have to be divisible by 8 but are {height} and {width}."
|
514 |
+
)
|
515 |
+
|
516 |
+
if (callback_steps is None) or (
|
517 |
+
callback_steps is not None
|
518 |
+
and (not isinstance(callback_steps, int) or callback_steps <= 0)
|
519 |
+
):
|
520 |
+
raise ValueError(
|
521 |
+
f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
|
522 |
+
f" {type(callback_steps)}."
|
523 |
+
)
|
524 |
+
|
525 |
+
if prompt is not None and prompt_embeds is not None:
|
526 |
+
raise ValueError(
|
527 |
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
528 |
+
" only forward one of the two."
|
529 |
+
)
|
530 |
+
elif prompt_2 is not None and prompt_embeds is not None:
|
531 |
+
raise ValueError(
|
532 |
+
f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
533 |
+
" only forward one of the two."
|
534 |
+
)
|
535 |
+
elif prompt is None and prompt_embeds is None:
|
536 |
+
raise ValueError(
|
537 |
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
538 |
+
)
|
539 |
+
elif prompt is not None and (
|
540 |
+
not isinstance(prompt, str) and not isinstance(prompt, list)
|
541 |
+
):
|
542 |
+
raise ValueError(
|
543 |
+
f"`prompt` has to be of type `str` or `list` but is {type(prompt)}"
|
544 |
+
)
|
545 |
+
elif prompt_2 is not None and (
|
546 |
+
not isinstance(prompt_2, str) and not isinstance(prompt_2, list)
|
547 |
+
):
|
548 |
+
raise ValueError(
|
549 |
+
f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}"
|
550 |
+
)
|
551 |
+
|
552 |
+
if negative_prompt is not None and negative_prompt_embeds is not None:
|
553 |
+
raise ValueError(
|
554 |
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
555 |
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
556 |
+
)
|
557 |
+
elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
|
558 |
+
raise ValueError(
|
559 |
+
f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
|
560 |
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
561 |
+
)
|
562 |
+
|
563 |
+
if prompt_embeds is not None and negative_prompt_embeds is not None:
|
564 |
+
if prompt_embeds.shape != negative_prompt_embeds.shape:
|
565 |
+
raise ValueError(
|
566 |
+
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
|
567 |
+
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
|
568 |
+
f" {negative_prompt_embeds.shape}."
|
569 |
+
)
|
570 |
+
|
571 |
+
if prompt_embeds is not None and pooled_prompt_embeds is None:
|
572 |
+
raise ValueError(
|
573 |
+
"If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`."
|
574 |
+
)
|
575 |
+
|
576 |
+
if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
|
577 |
+
raise ValueError(
|
578 |
+
"If `negative_prompt_embeds` are provided, `negative_pooled_prompt_embeds` also have to be passed. Make sure to generate `negative_pooled_prompt_embeds` from the same text encoder that was used to generate `negative_prompt_embeds`."
|
579 |
+
)
|
580 |
+
|
581 |
+
# DemoFusion specific checks
|
582 |
+
if max(height, width) % 512 != 0:
|
583 |
+
raise ValueError(
|
584 |
+
f"the larger one of `height` and `width` has to be divisible by 1024 but are {height} and {width}."
|
585 |
+
)
|
586 |
+
|
587 |
+
if num_images_per_prompt != 1:
|
588 |
+
warnings.warn(
|
589 |
+
"num_images_per_prompt != 1 is not supported by DemoFusion and will be ignored."
|
590 |
+
)
|
591 |
+
num_images_per_prompt = 1
|
592 |
+
|
593 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
|
594 |
+
def prepare_latents(
|
595 |
+
self,
|
596 |
+
batch_size,
|
597 |
+
num_channels_latents,
|
598 |
+
height,
|
599 |
+
width,
|
600 |
+
dtype,
|
601 |
+
device,
|
602 |
+
generator,
|
603 |
+
latents=None,
|
604 |
+
):
|
605 |
+
shape = (
|
606 |
+
batch_size,
|
607 |
+
num_channels_latents,
|
608 |
+
height // self.vae_scale_factor,
|
609 |
+
width // self.vae_scale_factor,
|
610 |
+
)
|
611 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
612 |
+
raise ValueError(
|
613 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
614 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
615 |
+
)
|
616 |
+
|
617 |
+
if latents is None:
|
618 |
+
latents = randn_tensor(
|
619 |
+
shape, generator=generator, device=device, dtype=dtype
|
620 |
+
)
|
621 |
+
else:
|
622 |
+
latents = latents.to(device)
|
623 |
+
|
624 |
+
# scale the initial noise by the standard deviation required by the scheduler
|
625 |
+
latents = latents * self.scheduler.init_noise_sigma
|
626 |
+
return latents
|
627 |
+
|
628 |
+
def _get_add_time_ids(
|
629 |
+
self, original_size, crops_coords_top_left, target_size, dtype
|
630 |
+
):
|
631 |
+
add_time_ids = list(original_size + crops_coords_top_left + target_size)
|
632 |
+
|
633 |
+
passed_add_embed_dim = (
|
634 |
+
self.unet.config.addition_time_embed_dim * len(add_time_ids)
|
635 |
+
+ self.text_encoder_2.config.projection_dim
|
636 |
+
)
|
637 |
+
expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
|
638 |
+
|
639 |
+
if expected_add_embed_dim != passed_add_embed_dim:
|
640 |
+
raise ValueError(
|
641 |
+
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`."
|
642 |
+
)
|
643 |
+
|
644 |
+
add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
|
645 |
+
return add_time_ids
|
646 |
+
|
647 |
+
def get_views(self, height, width, window_size=128, stride=64, random_jitter=False):
|
648 |
+
# Here, we define the mappings F_i (see Eq. 7 in the MultiDiffusion paper https://arxiv.org/abs/2302.08113)
|
649 |
+
# if panorama's height/width < window_size, num_blocks of height/width should return 1
|
650 |
+
height //= self.vae_scale_factor
|
651 |
+
width //= self.vae_scale_factor
|
652 |
+
num_blocks_height = (
|
653 |
+
int((height - window_size) / stride - 1e-6) + 2
|
654 |
+
if height > window_size
|
655 |
+
else 1
|
656 |
+
)
|
657 |
+
num_blocks_width = (
|
658 |
+
int((width - window_size) / stride - 1e-6) + 2 if width > window_size else 1
|
659 |
+
)
|
660 |
+
total_num_blocks = int(num_blocks_height * num_blocks_width)
|
661 |
+
views = []
|
662 |
+
for i in range(total_num_blocks):
|
663 |
+
h_start = int((i // num_blocks_width) * stride)
|
664 |
+
h_end = h_start + window_size
|
665 |
+
w_start = int((i % num_blocks_width) * stride)
|
666 |
+
w_end = w_start + window_size
|
667 |
+
|
668 |
+
if h_end > height:
|
669 |
+
h_start = int(h_start + height - h_end)
|
670 |
+
h_end = int(height)
|
671 |
+
if w_end > width:
|
672 |
+
w_start = int(w_start + width - w_end)
|
673 |
+
w_end = int(width)
|
674 |
+
if h_start < 0:
|
675 |
+
h_end = int(h_end - h_start)
|
676 |
+
h_start = 0
|
677 |
+
if w_start < 0:
|
678 |
+
w_end = int(w_end - w_start)
|
679 |
+
w_start = 0
|
680 |
+
|
681 |
+
if random_jitter:
|
682 |
+
jitter_range = (window_size - stride) // 4
|
683 |
+
w_jitter = 0
|
684 |
+
h_jitter = 0
|
685 |
+
if (w_start != 0) and (w_end != width):
|
686 |
+
w_jitter = random.randint(-jitter_range, jitter_range)
|
687 |
+
elif (w_start == 0) and (w_end != width):
|
688 |
+
w_jitter = random.randint(-jitter_range, 0)
|
689 |
+
elif (w_start != 0) and (w_end == width):
|
690 |
+
w_jitter = random.randint(0, jitter_range)
|
691 |
+
if (h_start != 0) and (h_end != height):
|
692 |
+
h_jitter = random.randint(-jitter_range, jitter_range)
|
693 |
+
elif (h_start == 0) and (h_end != height):
|
694 |
+
h_jitter = random.randint(-jitter_range, 0)
|
695 |
+
elif (h_start != 0) and (h_end == height):
|
696 |
+
h_jitter = random.randint(0, jitter_range)
|
697 |
+
h_start += h_jitter + jitter_range
|
698 |
+
h_end += h_jitter + jitter_range
|
699 |
+
w_start += w_jitter + jitter_range
|
700 |
+
w_end += w_jitter + jitter_range
|
701 |
+
|
702 |
+
views.append((h_start, h_end, w_start, w_end))
|
703 |
+
return views
|
704 |
+
|
705 |
+
def tiled_decode(self, latents, current_height, current_width):
|
706 |
+
sample_size = self.unet.config.sample_size
|
707 |
+
core_size = self.unet.config.sample_size // 4
|
708 |
+
core_stride = core_size
|
709 |
+
pad_size = self.unet.config.sample_size // 4 * 3
|
710 |
+
decoder_view_batch_size = 1
|
711 |
+
|
712 |
+
if self.lowvram:
|
713 |
+
core_stride = core_size // 2
|
714 |
+
pad_size = core_size
|
715 |
+
|
716 |
+
views = self.get_views(
|
717 |
+
current_height, current_width, stride=core_stride, window_size=core_size
|
718 |
+
)
|
719 |
+
views_batch = [
|
720 |
+
views[i : i + decoder_view_batch_size]
|
721 |
+
for i in range(0, len(views), decoder_view_batch_size)
|
722 |
+
]
|
723 |
+
latents_ = F.pad(
|
724 |
+
latents, (pad_size, pad_size, pad_size, pad_size), "constant", 0
|
725 |
+
)
|
726 |
+
image = torch.zeros(latents.size(0), 3, current_height, current_width).to(
|
727 |
+
latents.device
|
728 |
+
)
|
729 |
+
count = torch.zeros_like(image).to(latents.device)
|
730 |
+
# get the latents corresponding to the current view coordinates
|
731 |
+
with self.progress_bar(total=len(views_batch)) as progress_bar:
|
732 |
+
for j, batch_view in enumerate(views_batch):
|
733 |
+
vb_size = len(batch_view)
|
734 |
+
latents_for_view = torch.cat(
|
735 |
+
[
|
736 |
+
latents_[
|
737 |
+
:,
|
738 |
+
:,
|
739 |
+
h_start : h_end + pad_size * 2,
|
740 |
+
w_start : w_end + pad_size * 2,
|
741 |
+
]
|
742 |
+
for h_start, h_end, w_start, w_end in batch_view
|
743 |
+
]
|
744 |
+
).to(self.vae.device)
|
745 |
+
image_patch = self.vae.decode(
|
746 |
+
latents_for_view / self.vae.config.scaling_factor, return_dict=False
|
747 |
+
)[0]
|
748 |
+
h_start, h_end, w_start, w_end = views[j]
|
749 |
+
h_start, h_end, w_start, w_end = (
|
750 |
+
h_start * self.vae_scale_factor,
|
751 |
+
h_end * self.vae_scale_factor,
|
752 |
+
w_start * self.vae_scale_factor,
|
753 |
+
w_end * self.vae_scale_factor,
|
754 |
+
)
|
755 |
+
p_h_start, p_h_end, p_w_start, p_w_end = (
|
756 |
+
pad_size * self.vae_scale_factor,
|
757 |
+
image_patch.size(2) - pad_size * self.vae_scale_factor,
|
758 |
+
pad_size * self.vae_scale_factor,
|
759 |
+
image_patch.size(3) - pad_size * self.vae_scale_factor,
|
760 |
+
)
|
761 |
+
image[:, :, h_start:h_end, w_start:w_end] += image_patch[
|
762 |
+
:, :, p_h_start:p_h_end, p_w_start:p_w_end
|
763 |
+
].to(latents.device)
|
764 |
+
count[:, :, h_start:h_end, w_start:w_end] += 1
|
765 |
+
progress_bar.update()
|
766 |
+
image = image / count
|
767 |
+
|
768 |
+
return image
|
769 |
+
|
770 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.StableDiffusionUpscalePipeline.upcast_vae
|
771 |
+
def upcast_vae(self):
|
772 |
+
dtype = self.vae.dtype
|
773 |
+
self.vae.to(dtype=torch.float32)
|
774 |
+
use_torch_2_0_or_xformers = isinstance(
|
775 |
+
self.vae.decoder.mid_block.attentions[0].processor,
|
776 |
+
(
|
777 |
+
AttnProcessor2_0,
|
778 |
+
XFormersAttnProcessor,
|
779 |
+
LoRAXFormersAttnProcessor,
|
780 |
+
LoRAAttnProcessor2_0,
|
781 |
+
),
|
782 |
+
)
|
783 |
+
# if xformers or torch_2_0 is used attention block does not need
|
784 |
+
# to be in float32 which can save lots of memory
|
785 |
+
if use_torch_2_0_or_xformers:
|
786 |
+
self.vae.post_quant_conv.to(dtype)
|
787 |
+
self.vae.decoder.conv_in.to(dtype)
|
788 |
+
self.vae.decoder.mid_block.to(dtype)
|
789 |
+
|
790 |
+
@torch.no_grad()
|
791 |
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
792 |
+
def __call__(
|
793 |
+
self,
|
794 |
+
prompt: Union[str, List[str]] = None,
|
795 |
+
prompt_2: Optional[Union[str, List[str]]] = None,
|
796 |
+
height: Optional[int] = None,
|
797 |
+
width: Optional[int] = None,
|
798 |
+
num_inference_steps: int = 50,
|
799 |
+
denoising_end: Optional[float] = None,
|
800 |
+
guidance_scale: float = 5.0,
|
801 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
802 |
+
negative_prompt_2: Optional[Union[str, List[str]]] = None,
|
803 |
+
num_images_per_prompt: Optional[int] = 1,
|
804 |
+
eta: float = 0.0,
|
805 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
806 |
+
latents: Optional[torch.FloatTensor] = None,
|
807 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
808 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
809 |
+
pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
810 |
+
negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
811 |
+
output_type: Optional[str] = "pil",
|
812 |
+
return_dict: bool = False,
|
813 |
+
callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
|
814 |
+
callback_steps: int = 1,
|
815 |
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
816 |
+
guidance_rescale: float = 0.0,
|
817 |
+
original_size: Optional[Tuple[int, int]] = None,
|
818 |
+
crops_coords_top_left: Tuple[int, int] = (0, 0),
|
819 |
+
target_size: Optional[Tuple[int, int]] = None,
|
820 |
+
negative_original_size: Optional[Tuple[int, int]] = None,
|
821 |
+
negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
|
822 |
+
negative_target_size: Optional[Tuple[int, int]] = None,
|
823 |
+
################### DemoFusion specific parameters ####################
|
824 |
+
view_batch_size: int = 16,
|
825 |
+
multi_decoder: bool = True,
|
826 |
+
stride: Optional[int] = 64,
|
827 |
+
cosine_scale_1: Optional[float] = 3.0,
|
828 |
+
cosine_scale_2: Optional[float] = 1.0,
|
829 |
+
cosine_scale_3: Optional[float] = 1.0,
|
830 |
+
sigma: Optional[float] = 1.0,
|
831 |
+
show_image: bool = False,
|
832 |
+
lowvram: bool = False,
|
833 |
+
image_lr: Optional[torch.FloatTensor] = None,
|
834 |
+
):
|
835 |
+
r"""
|
836 |
+
Function invoked when calling the pipeline for generation.
|
837 |
+
|
838 |
+
Args:
|
839 |
+
prompt (`str` or `List[str]`, *optional*):
|
840 |
+
The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
|
841 |
+
instead.
|
842 |
+
prompt_2 (`str` or `List[str]`, *optional*):
|
843 |
+
The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
|
844 |
+
used in both text-encoders
|
845 |
+
height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
846 |
+
The height in pixels of the generated image. This is set to 1024 by default for the best results.
|
847 |
+
Anything below 512 pixels won't work well for
|
848 |
+
[stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
|
849 |
+
and checkpoints that are not specifically fine-tuned on low resolutions.
|
850 |
+
width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
851 |
+
The width in pixels of the generated image. This is set to 1024 by default for the best results.
|
852 |
+
Anything below 512 pixels won't work well for
|
853 |
+
[stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
|
854 |
+
and checkpoints that are not specifically fine-tuned on low resolutions.
|
855 |
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
856 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
857 |
+
expense of slower inference.
|
858 |
+
denoising_end (`float`, *optional*):
|
859 |
+
When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
|
860 |
+
completed before it is intentionally prematurely terminated. As a result, the returned sample will
|
861 |
+
still retain a substantial amount of noise as determined by the discrete timesteps selected by the
|
862 |
+
scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
|
863 |
+
"Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
|
864 |
+
Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)
|
865 |
+
guidance_scale (`float`, *optional*, defaults to 5.0):
|
866 |
+
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
|
867 |
+
`guidance_scale` is defined as `w` of equation 2. of [Imagen
|
868 |
+
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
|
869 |
+
1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
|
870 |
+
usually at the expense of lower image quality.
|
871 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
872 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
873 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
874 |
+
less than `1`).
|
875 |
+
negative_prompt_2 (`str` or `List[str]`, *optional*):
|
876 |
+
The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
|
877 |
+
`text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
|
878 |
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
879 |
+
The number of images to generate per prompt.
|
880 |
+
eta (`float`, *optional*, defaults to 0.0):
|
881 |
+
Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
|
882 |
+
[`schedulers.DDIMScheduler`], will be ignored for others.
|
883 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
884 |
+
One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
|
885 |
+
to make generation deterministic.
|
886 |
+
latents (`torch.FloatTensor`, *optional*):
|
887 |
+
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
|
888 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
889 |
+
tensor will ge generated by sampling using the supplied random `generator`.
|
890 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
891 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
892 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
893 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
894 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
895 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
896 |
+
argument.
|
897 |
+
pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
898 |
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
899 |
+
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
900 |
+
negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
901 |
+
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
902 |
+
weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
|
903 |
+
input argument.
|
904 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
905 |
+
The output format of the generate image. Choose between
|
906 |
+
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
|
907 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
908 |
+
Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
|
909 |
+
of a plain tuple.
|
910 |
+
callback (`Callable`, *optional*):
|
911 |
+
A function that will be called every `callback_steps` steps during inference. The function will be
|
912 |
+
called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
|
913 |
+
callback_steps (`int`, *optional*, defaults to 1):
|
914 |
+
The frequency at which the `callback` function will be called. If not specified, the callback will be
|
915 |
+
called at every step.
|
916 |
+
cross_attention_kwargs (`dict`, *optional*):
|
917 |
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
918 |
+
`self.processor` in
|
919 |
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
920 |
+
guidance_rescale (`float`, *optional*, defaults to 0.7):
|
921 |
+
Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
|
922 |
+
Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
|
923 |
+
[Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
|
924 |
+
Guidance rescale factor should fix overexposure when using zero terminal SNR.
|
925 |
+
original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
926 |
+
If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
|
927 |
+
`original_size` defaults to `(width, height)` if not specified. Part of SDXL's micro-conditioning as
|
928 |
+
explained in section 2.2 of
|
929 |
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
930 |
+
crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
|
931 |
+
`crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
|
932 |
+
`crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
|
933 |
+
`crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
|
934 |
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
935 |
+
target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
936 |
+
For most cases, `target_size` should be set to the desired height and width of the generated image. If
|
937 |
+
not specified it will default to `(width, height)`. Part of SDXL's micro-conditioning as explained in
|
938 |
+
section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
939 |
+
negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
940 |
+
To negatively condition the generation process based on a specific image resolution. Part of SDXL's
|
941 |
+
micro-conditioning as explained in section 2.2 of
|
942 |
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
|
943 |
+
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
|
944 |
+
negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
|
945 |
+
To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
|
946 |
+
micro-conditioning as explained in section 2.2 of
|
947 |
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
|
948 |
+
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
|
949 |
+
negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
950 |
+
To negatively condition the generation process based on a target image resolution. It should be as same
|
951 |
+
as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
|
952 |
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
|
953 |
+
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
|
954 |
+
################### DemoFusion specific parameters ####################
|
955 |
+
view_batch_size (`int`, defaults to 16):
|
956 |
+
The batch size for multiple denoising paths. Typically, a larger batch size can result in higher
|
957 |
+
efficiency but comes with increased GPU memory requirements.
|
958 |
+
multi_decoder (`bool`, defaults to True):
|
959 |
+
Determine whether to use a tiled decoder. Generally, when the resolution exceeds 3072x3072,
|
960 |
+
a tiled decoder becomes necessary.
|
961 |
+
stride (`int`, defaults to 64):
|
962 |
+
The stride of moving local patches. A smaller stride is better for alleviating seam issues,
|
963 |
+
but it also introduces additional computational overhead and inference time.
|
964 |
+
cosine_scale_1 (`float`, defaults to 3):
|
965 |
+
Control the strength of skip-residual. For specific impacts, please refer to Appendix C
|
966 |
+
in the DemoFusion paper.
|
967 |
+
cosine_scale_2 (`float`, defaults to 1):
|
968 |
+
Control the strength of dilated sampling. For specific impacts, please refer to Appendix C
|
969 |
+
in the DemoFusion paper.
|
970 |
+
cosine_scale_3 (`float`, defaults to 1):
|
971 |
+
Control the strength of the gaussion filter. For specific impacts, please refer to Appendix C
|
972 |
+
in the DemoFusion paper.
|
973 |
+
sigma (`float`, defaults to 1):
|
974 |
+
The standerd value of the gaussian filter.
|
975 |
+
show_image (`bool`, defaults to False):
|
976 |
+
Determine whether to show intermediate results during generation.
|
977 |
+
lowvram (`bool`, defaults to False):
|
978 |
+
Try to fit in 8 Gb of VRAM, with xformers installed.
|
979 |
+
|
980 |
+
Examples:
|
981 |
+
|
982 |
+
Returns:
|
983 |
+
a `list` with the generated images at each phase.
|
984 |
+
"""
|
985 |
+
|
986 |
+
# 0. Default height and width to unet
|
987 |
+
height = height or self.default_sample_size * self.vae_scale_factor
|
988 |
+
width = width or self.default_sample_size * self.vae_scale_factor
|
989 |
+
|
990 |
+
x1_size = self.default_sample_size * self.vae_scale_factor
|
991 |
+
|
992 |
+
height_scale = height / x1_size
|
993 |
+
width_scale = width / x1_size
|
994 |
+
scale_num = int(max(height_scale, width_scale))
|
995 |
+
aspect_ratio = min(height_scale, width_scale) / max(height_scale, width_scale)
|
996 |
+
|
997 |
+
original_size = original_size or (height, width)
|
998 |
+
target_size = target_size or (height, width)
|
999 |
+
|
1000 |
+
# 1. Check inputs. Raise error if not correct
|
1001 |
+
self.check_inputs(
|
1002 |
+
prompt,
|
1003 |
+
prompt_2,
|
1004 |
+
height,
|
1005 |
+
width,
|
1006 |
+
callback_steps,
|
1007 |
+
negative_prompt,
|
1008 |
+
negative_prompt_2,
|
1009 |
+
prompt_embeds,
|
1010 |
+
negative_prompt_embeds,
|
1011 |
+
pooled_prompt_embeds,
|
1012 |
+
negative_pooled_prompt_embeds,
|
1013 |
+
num_images_per_prompt,
|
1014 |
+
)
|
1015 |
+
|
1016 |
+
# 2. Define call parameters
|
1017 |
+
if prompt is not None and isinstance(prompt, str):
|
1018 |
+
batch_size = 1
|
1019 |
+
elif prompt is not None and isinstance(prompt, list):
|
1020 |
+
batch_size = len(prompt)
|
1021 |
+
else:
|
1022 |
+
batch_size = prompt_embeds.shape[0]
|
1023 |
+
|
1024 |
+
device = self._execution_device
|
1025 |
+
self.lowvram = lowvram
|
1026 |
+
if self.lowvram:
|
1027 |
+
self.vae.cpu()
|
1028 |
+
self.unet.cpu()
|
1029 |
+
self.text_encoder.to(device)
|
1030 |
+
self.text_encoder_2.to(device)
|
1031 |
+
|
1032 |
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
1033 |
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
1034 |
+
# corresponds to doing no classifier free guidance.
|
1035 |
+
do_classifier_free_guidance = guidance_scale > 1.0
|
1036 |
+
|
1037 |
+
# 3. Encode input prompt
|
1038 |
+
text_encoder_lora_scale = (
|
1039 |
+
cross_attention_kwargs.get("scale", None)
|
1040 |
+
if cross_attention_kwargs is not None
|
1041 |
+
else None
|
1042 |
+
)
|
1043 |
+
(
|
1044 |
+
prompt_embeds,
|
1045 |
+
negative_prompt_embeds,
|
1046 |
+
pooled_prompt_embeds,
|
1047 |
+
negative_pooled_prompt_embeds,
|
1048 |
+
) = self.encode_prompt(
|
1049 |
+
prompt=prompt,
|
1050 |
+
prompt_2=prompt_2,
|
1051 |
+
device=device,
|
1052 |
+
num_images_per_prompt=num_images_per_prompt,
|
1053 |
+
do_classifier_free_guidance=do_classifier_free_guidance,
|
1054 |
+
negative_prompt=negative_prompt,
|
1055 |
+
negative_prompt_2=negative_prompt_2,
|
1056 |
+
prompt_embeds=prompt_embeds,
|
1057 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
1058 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
1059 |
+
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
1060 |
+
lora_scale=text_encoder_lora_scale,
|
1061 |
+
)
|
1062 |
+
|
1063 |
+
# 4. Prepare timesteps
|
1064 |
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
1065 |
+
|
1066 |
+
timesteps = self.scheduler.timesteps
|
1067 |
+
|
1068 |
+
# 5. Prepare latent variables
|
1069 |
+
num_channels_latents = self.unet.config.in_channels
|
1070 |
+
latents = self.prepare_latents(
|
1071 |
+
batch_size * num_images_per_prompt,
|
1072 |
+
num_channels_latents,
|
1073 |
+
height // scale_num,
|
1074 |
+
width // scale_num,
|
1075 |
+
prompt_embeds.dtype,
|
1076 |
+
device,
|
1077 |
+
generator,
|
1078 |
+
latents,
|
1079 |
+
)
|
1080 |
+
|
1081 |
+
# 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
1082 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
1083 |
+
|
1084 |
+
# 7. Prepare added time ids & embeddings
|
1085 |
+
add_text_embeds = pooled_prompt_embeds
|
1086 |
+
add_time_ids = self._get_add_time_ids(
|
1087 |
+
original_size, crops_coords_top_left, target_size, dtype=prompt_embeds.dtype
|
1088 |
+
)
|
1089 |
+
if negative_original_size is not None and negative_target_size is not None:
|
1090 |
+
negative_add_time_ids = self._get_add_time_ids(
|
1091 |
+
negative_original_size,
|
1092 |
+
negative_crops_coords_top_left,
|
1093 |
+
negative_target_size,
|
1094 |
+
dtype=prompt_embeds.dtype,
|
1095 |
+
)
|
1096 |
+
else:
|
1097 |
+
negative_add_time_ids = add_time_ids
|
1098 |
+
|
1099 |
+
if do_classifier_free_guidance:
|
1100 |
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
|
1101 |
+
add_text_embeds = torch.cat(
|
1102 |
+
[negative_pooled_prompt_embeds, add_text_embeds], dim=0
|
1103 |
+
)
|
1104 |
+
add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
|
1105 |
+
del negative_prompt_embeds, negative_pooled_prompt_embeds, negative_add_time_ids
|
1106 |
+
|
1107 |
+
prompt_embeds = prompt_embeds.to(device)
|
1108 |
+
add_text_embeds = add_text_embeds.to(device)
|
1109 |
+
add_time_ids = add_time_ids.to(device).repeat(
|
1110 |
+
batch_size * num_images_per_prompt, 1
|
1111 |
+
)
|
1112 |
+
|
1113 |
+
# 8. Denoising loop
|
1114 |
+
num_warmup_steps = max(
|
1115 |
+
len(timesteps) - num_inference_steps * self.scheduler.order, 0
|
1116 |
+
)
|
1117 |
+
|
1118 |
+
# 7.1 Apply denoising_end
|
1119 |
+
if (
|
1120 |
+
denoising_end is not None
|
1121 |
+
and isinstance(denoising_end, float)
|
1122 |
+
and denoising_end > 0
|
1123 |
+
and denoising_end < 1
|
1124 |
+
):
|
1125 |
+
discrete_timestep_cutoff = int(
|
1126 |
+
round(
|
1127 |
+
self.scheduler.config.num_train_timesteps
|
1128 |
+
- (denoising_end * self.scheduler.config.num_train_timesteps)
|
1129 |
+
)
|
1130 |
+
)
|
1131 |
+
num_inference_steps = len(
|
1132 |
+
list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps))
|
1133 |
+
)
|
1134 |
+
timesteps = timesteps[:num_inference_steps]
|
1135 |
+
|
1136 |
+
output_images = []
|
1137 |
+
|
1138 |
+
############################################################### Phase 1 #################################################################
|
1139 |
+
|
1140 |
+
if self.lowvram:
|
1141 |
+
self.text_encoder.cpu()
|
1142 |
+
self.text_encoder_2.cpu()
|
1143 |
+
|
1144 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
1145 |
+
if image_lr == None:
|
1146 |
+
print("### Phase 1 Denoising ###")
|
1147 |
+
for i, t in enumerate(timesteps):
|
1148 |
+
if self.lowvram:
|
1149 |
+
self.vae.cpu()
|
1150 |
+
self.unet.to(device)
|
1151 |
+
|
1152 |
+
latents_for_view = latents
|
1153 |
+
|
1154 |
+
# expand the latents if we are doing classifier free guidance
|
1155 |
+
latent_model_input = (
|
1156 |
+
latents.repeat_interleave(2, dim=0)
|
1157 |
+
if do_classifier_free_guidance
|
1158 |
+
else latents
|
1159 |
+
)
|
1160 |
+
latent_model_input = self.scheduler.scale_model_input(
|
1161 |
+
latent_model_input, t
|
1162 |
+
)
|
1163 |
+
|
1164 |
+
# predict the noise residual
|
1165 |
+
added_cond_kwargs = {
|
1166 |
+
"text_embeds": add_text_embeds,
|
1167 |
+
"time_ids": add_time_ids,
|
1168 |
+
}
|
1169 |
+
noise_pred = self.unet(
|
1170 |
+
latent_model_input,
|
1171 |
+
t,
|
1172 |
+
encoder_hidden_states=prompt_embeds,
|
1173 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
1174 |
+
added_cond_kwargs=added_cond_kwargs,
|
1175 |
+
return_dict=False,
|
1176 |
+
)[0]
|
1177 |
+
|
1178 |
+
# perform guidance
|
1179 |
+
if do_classifier_free_guidance:
|
1180 |
+
noise_pred_uncond, noise_pred_text = (
|
1181 |
+
noise_pred[::2],
|
1182 |
+
noise_pred[1::2],
|
1183 |
+
)
|
1184 |
+
noise_pred = noise_pred_uncond + guidance_scale * (
|
1185 |
+
noise_pred_text - noise_pred_uncond
|
1186 |
+
)
|
1187 |
+
|
1188 |
+
if do_classifier_free_guidance and guidance_rescale > 0.0:
|
1189 |
+
# Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
|
1190 |
+
noise_pred = rescale_noise_cfg(
|
1191 |
+
noise_pred,
|
1192 |
+
noise_pred_text,
|
1193 |
+
guidance_rescale=guidance_rescale,
|
1194 |
+
)
|
1195 |
+
|
1196 |
+
# compute the previous noisy sample x_t -> x_t-1
|
1197 |
+
latents = self.scheduler.step(
|
1198 |
+
noise_pred, t, latents, **extra_step_kwargs, return_dict=False
|
1199 |
+
)[0]
|
1200 |
+
|
1201 |
+
# call the callback, if provided
|
1202 |
+
if i == len(timesteps) - 1 or (
|
1203 |
+
(i + 1) > num_warmup_steps
|
1204 |
+
and (i + 1) % self.scheduler.order == 0
|
1205 |
+
):
|
1206 |
+
progress_bar.update()
|
1207 |
+
if callback is not None and i % callback_steps == 0:
|
1208 |
+
step_idx = i // getattr(self.scheduler, "order", 1)
|
1209 |
+
callback(step_idx, t, latents)
|
1210 |
+
del (
|
1211 |
+
latents_for_view,
|
1212 |
+
latent_model_input,
|
1213 |
+
noise_pred,
|
1214 |
+
noise_pred_text,
|
1215 |
+
noise_pred_uncond,
|
1216 |
+
)
|
1217 |
+
else:
|
1218 |
+
print("### Phase Encoding ###")
|
1219 |
+
self.vae.to(device)
|
1220 |
+
latents = self.vae.encode(image_lr)
|
1221 |
+
latents = latents.latent_dist.sample() * self.vae.config.scaling_factor
|
1222 |
+
|
1223 |
+
anchor_mean = latents.mean()
|
1224 |
+
anchor_std = latents.std()
|
1225 |
+
if self.lowvram:
|
1226 |
+
latents = latents.cpu()
|
1227 |
+
torch.cuda.empty_cache()
|
1228 |
+
if not output_type == "latent":
|
1229 |
+
# make sure the VAE is in float32 mode, as it overflows in float16
|
1230 |
+
needs_upcasting = (
|
1231 |
+
self.vae.dtype == torch.float16 and self.vae.config.force_upcast
|
1232 |
+
)
|
1233 |
+
|
1234 |
+
if self.lowvram:
|
1235 |
+
needs_upcasting = (
|
1236 |
+
False # use madebyollin/sdxl-vae-fp16-fix in lowvram mode!
|
1237 |
+
)
|
1238 |
+
self.unet.cpu()
|
1239 |
+
self.vae.to(device)
|
1240 |
+
|
1241 |
+
if needs_upcasting:
|
1242 |
+
self.upcast_vae()
|
1243 |
+
latents = latents.to(
|
1244 |
+
next(iter(self.vae.post_quant_conv.parameters())).dtype
|
1245 |
+
)
|
1246 |
+
if self.lowvram and multi_decoder:
|
1247 |
+
current_width_height = (
|
1248 |
+
self.unet.config.sample_size * self.vae_scale_factor
|
1249 |
+
)
|
1250 |
+
image = self.tiled_decode(
|
1251 |
+
latents, current_width_height, current_width_height
|
1252 |
+
)
|
1253 |
+
else:
|
1254 |
+
image = self.vae.decode(
|
1255 |
+
latents / self.vae.config.scaling_factor, return_dict=False
|
1256 |
+
)[0]
|
1257 |
+
# cast back to fp16 if needed
|
1258 |
+
if needs_upcasting:
|
1259 |
+
self.vae.to(dtype=torch.float16)
|
1260 |
+
|
1261 |
+
image = self.image_processor.postprocess(image, output_type=output_type)
|
1262 |
+
if show_image:
|
1263 |
+
plt.figure(figsize=(10, 10))
|
1264 |
+
plt.imshow(image[0])
|
1265 |
+
plt.axis("off") # Turn off axis numbers and ticks
|
1266 |
+
plt.show()
|
1267 |
+
output_images.append(image[0])
|
1268 |
+
|
1269 |
+
####################################################### Phase 2+ #####################################################
|
1270 |
+
for current_scale_num in range(1, scale_num + 1):
|
1271 |
+
if self.lowvram:
|
1272 |
+
latents = latents.to(device)
|
1273 |
+
self.unet.to(device)
|
1274 |
+
torch.cuda.empty_cache()
|
1275 |
+
print("### Phase {} Denoising ###".format(current_scale_num))
|
1276 |
+
current_height = (
|
1277 |
+
self.unet.config.sample_size * self.vae_scale_factor * current_scale_num
|
1278 |
+
)
|
1279 |
+
current_width = (
|
1280 |
+
self.unet.config.sample_size * self.vae_scale_factor * current_scale_num
|
1281 |
+
)
|
1282 |
+
if height > width:
|
1283 |
+
current_width = int(current_width * aspect_ratio)
|
1284 |
+
else:
|
1285 |
+
current_height = int(current_height * aspect_ratio)
|
1286 |
+
|
1287 |
+
latents = F.interpolate(
|
1288 |
+
latents.to(device),
|
1289 |
+
size=(
|
1290 |
+
int(current_height / self.vae_scale_factor),
|
1291 |
+
int(current_width / self.vae_scale_factor),
|
1292 |
+
),
|
1293 |
+
mode="bicubic",
|
1294 |
+
)
|
1295 |
+
|
1296 |
+
noise_latents = []
|
1297 |
+
noise = torch.randn_like(latents)
|
1298 |
+
for timestep in timesteps:
|
1299 |
+
noise_latent = self.scheduler.add_noise(
|
1300 |
+
latents, noise, timestep.unsqueeze(0)
|
1301 |
+
)
|
1302 |
+
noise_latents.append(noise_latent)
|
1303 |
+
latents = noise_latents[0]
|
1304 |
+
|
1305 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
1306 |
+
for i, t in enumerate(timesteps):
|
1307 |
+
count = torch.zeros_like(latents)
|
1308 |
+
value = torch.zeros_like(latents)
|
1309 |
+
cosine_factor = (
|
1310 |
+
0.5
|
1311 |
+
* (
|
1312 |
+
1
|
1313 |
+
+ torch.cos(
|
1314 |
+
torch.pi
|
1315 |
+
* (self.scheduler.config.num_train_timesteps - t)
|
1316 |
+
/ self.scheduler.config.num_train_timesteps
|
1317 |
+
)
|
1318 |
+
).cpu()
|
1319 |
+
)
|
1320 |
+
|
1321 |
+
c1 = cosine_factor**cosine_scale_1
|
1322 |
+
latents = latents * (1 - c1) + noise_latents[i] * c1
|
1323 |
+
|
1324 |
+
############################################# MultiDiffusion #############################################
|
1325 |
+
|
1326 |
+
views = self.get_views(
|
1327 |
+
current_height,
|
1328 |
+
current_width,
|
1329 |
+
stride=stride,
|
1330 |
+
window_size=self.unet.config.sample_size,
|
1331 |
+
random_jitter=True,
|
1332 |
+
)
|
1333 |
+
views_batch = [
|
1334 |
+
views[i : i + view_batch_size]
|
1335 |
+
for i in range(0, len(views), view_batch_size)
|
1336 |
+
]
|
1337 |
+
|
1338 |
+
jitter_range = (self.unet.config.sample_size - stride) // 4
|
1339 |
+
latents_ = F.pad(
|
1340 |
+
latents,
|
1341 |
+
(jitter_range, jitter_range, jitter_range, jitter_range),
|
1342 |
+
"constant",
|
1343 |
+
0,
|
1344 |
+
)
|
1345 |
+
|
1346 |
+
count_local = torch.zeros_like(latents_)
|
1347 |
+
value_local = torch.zeros_like(latents_)
|
1348 |
+
|
1349 |
+
for j, batch_view in enumerate(views_batch):
|
1350 |
+
vb_size = len(batch_view)
|
1351 |
+
|
1352 |
+
# get the latents corresponding to the current view coordinates
|
1353 |
+
latents_for_view = torch.cat(
|
1354 |
+
[
|
1355 |
+
latents_[:, :, h_start:h_end, w_start:w_end]
|
1356 |
+
for h_start, h_end, w_start, w_end in batch_view
|
1357 |
+
]
|
1358 |
+
)
|
1359 |
+
|
1360 |
+
# expand the latents if we are doing classifier free guidance
|
1361 |
+
latent_model_input = latents_for_view
|
1362 |
+
latent_model_input = (
|
1363 |
+
latent_model_input.repeat_interleave(2, dim=0)
|
1364 |
+
if do_classifier_free_guidance
|
1365 |
+
else latent_model_input
|
1366 |
+
)
|
1367 |
+
latent_model_input = self.scheduler.scale_model_input(
|
1368 |
+
latent_model_input, t
|
1369 |
+
)
|
1370 |
+
|
1371 |
+
prompt_embeds_input = torch.cat([prompt_embeds] * vb_size)
|
1372 |
+
add_text_embeds_input = torch.cat([add_text_embeds] * vb_size)
|
1373 |
+
add_time_ids_input = []
|
1374 |
+
for h_start, h_end, w_start, w_end in batch_view:
|
1375 |
+
add_time_ids_ = add_time_ids.clone()
|
1376 |
+
add_time_ids_[:, 2] = h_start * self.vae_scale_factor
|
1377 |
+
add_time_ids_[:, 3] = w_start * self.vae_scale_factor
|
1378 |
+
add_time_ids_input.append(add_time_ids_)
|
1379 |
+
add_time_ids_input = torch.cat(add_time_ids_input)
|
1380 |
+
|
1381 |
+
# predict the noise residual
|
1382 |
+
added_cond_kwargs = {
|
1383 |
+
"text_embeds": add_text_embeds_input,
|
1384 |
+
"time_ids": add_time_ids_input,
|
1385 |
+
}
|
1386 |
+
noise_pred = self.unet(
|
1387 |
+
latent_model_input,
|
1388 |
+
t,
|
1389 |
+
encoder_hidden_states=prompt_embeds_input,
|
1390 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
1391 |
+
added_cond_kwargs=added_cond_kwargs,
|
1392 |
+
return_dict=False,
|
1393 |
+
)[0]
|
1394 |
+
|
1395 |
+
if do_classifier_free_guidance:
|
1396 |
+
noise_pred_uncond, noise_pred_text = (
|
1397 |
+
noise_pred[::2],
|
1398 |
+
noise_pred[1::2],
|
1399 |
+
)
|
1400 |
+
noise_pred = noise_pred_uncond + guidance_scale * (
|
1401 |
+
noise_pred_text - noise_pred_uncond
|
1402 |
+
)
|
1403 |
+
|
1404 |
+
if do_classifier_free_guidance and guidance_rescale > 0.0:
|
1405 |
+
# Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
|
1406 |
+
noise_pred = rescale_noise_cfg(
|
1407 |
+
noise_pred,
|
1408 |
+
noise_pred_text,
|
1409 |
+
guidance_rescale=guidance_rescale,
|
1410 |
+
)
|
1411 |
+
|
1412 |
+
# compute the previous noisy sample x_t -> x_t-1
|
1413 |
+
self.scheduler._init_step_index(t)
|
1414 |
+
latents_denoised_batch = self.scheduler.step(
|
1415 |
+
noise_pred,
|
1416 |
+
t,
|
1417 |
+
latents_for_view,
|
1418 |
+
**extra_step_kwargs,
|
1419 |
+
return_dict=False,
|
1420 |
+
)[0]
|
1421 |
+
|
1422 |
+
# extract value from batch
|
1423 |
+
for latents_view_denoised, (
|
1424 |
+
h_start,
|
1425 |
+
h_end,
|
1426 |
+
w_start,
|
1427 |
+
w_end,
|
1428 |
+
) in zip(latents_denoised_batch.chunk(vb_size), batch_view):
|
1429 |
+
value_local[
|
1430 |
+
:, :, h_start:h_end, w_start:w_end
|
1431 |
+
] += latents_view_denoised
|
1432 |
+
count_local[:, :, h_start:h_end, w_start:w_end] += 1
|
1433 |
+
|
1434 |
+
value_local = value_local[
|
1435 |
+
:,
|
1436 |
+
:,
|
1437 |
+
jitter_range : jitter_range
|
1438 |
+
+ current_height // self.vae_scale_factor,
|
1439 |
+
jitter_range : jitter_range
|
1440 |
+
+ current_width // self.vae_scale_factor,
|
1441 |
+
]
|
1442 |
+
count_local = count_local[
|
1443 |
+
:,
|
1444 |
+
:,
|
1445 |
+
jitter_range : jitter_range
|
1446 |
+
+ current_height // self.vae_scale_factor,
|
1447 |
+
jitter_range : jitter_range
|
1448 |
+
+ current_width // self.vae_scale_factor,
|
1449 |
+
]
|
1450 |
+
|
1451 |
+
c2 = cosine_factor**cosine_scale_2
|
1452 |
+
|
1453 |
+
value += value_local / count_local * (1 - c2)
|
1454 |
+
count += torch.ones_like(value_local) * (1 - c2)
|
1455 |
+
|
1456 |
+
############################################# Dilated Sampling #############################################
|
1457 |
+
|
1458 |
+
views = [
|
1459 |
+
[h, w]
|
1460 |
+
for h in range(current_scale_num)
|
1461 |
+
for w in range(current_scale_num)
|
1462 |
+
]
|
1463 |
+
views_batch = [
|
1464 |
+
views[i : i + view_batch_size]
|
1465 |
+
for i in range(0, len(views), view_batch_size)
|
1466 |
+
]
|
1467 |
+
|
1468 |
+
h_pad = (
|
1469 |
+
current_scale_num - (latents.size(2) % current_scale_num)
|
1470 |
+
) % current_scale_num
|
1471 |
+
w_pad = (
|
1472 |
+
current_scale_num - (latents.size(3) % current_scale_num)
|
1473 |
+
) % current_scale_num
|
1474 |
+
latents_ = F.pad(latents, (w_pad, 0, h_pad, 0), "constant", 0)
|
1475 |
+
|
1476 |
+
count_global = torch.zeros_like(latents_)
|
1477 |
+
value_global = torch.zeros_like(latents_)
|
1478 |
+
|
1479 |
+
c3 = 0.99 * cosine_factor**cosine_scale_3 + 1e-2
|
1480 |
+
std_, mean_ = latents_.std(), latents_.mean()
|
1481 |
+
latents_gaussian = gaussian_filter(
|
1482 |
+
latents_,
|
1483 |
+
kernel_size=(2 * current_scale_num - 1),
|
1484 |
+
sigma=sigma * c3,
|
1485 |
+
)
|
1486 |
+
latents_gaussian = (
|
1487 |
+
latents_gaussian - latents_gaussian.mean()
|
1488 |
+
) / latents_gaussian.std() * std_ + mean_
|
1489 |
+
|
1490 |
+
for j, batch_view in enumerate(views_batch):
|
1491 |
+
latents_for_view = torch.cat(
|
1492 |
+
[
|
1493 |
+
latents_[
|
1494 |
+
:, :, h::current_scale_num, w::current_scale_num
|
1495 |
+
]
|
1496 |
+
for h, w in batch_view
|
1497 |
+
]
|
1498 |
+
)
|
1499 |
+
latents_for_view_gaussian = torch.cat(
|
1500 |
+
[
|
1501 |
+
latents_gaussian[
|
1502 |
+
:, :, h::current_scale_num, w::current_scale_num
|
1503 |
+
]
|
1504 |
+
for h, w in batch_view
|
1505 |
+
]
|
1506 |
+
)
|
1507 |
+
|
1508 |
+
vb_size = latents_for_view.size(0)
|
1509 |
+
|
1510 |
+
# expand the latents if we are doing classifier free guidance
|
1511 |
+
latent_model_input = latents_for_view_gaussian
|
1512 |
+
latent_model_input = (
|
1513 |
+
latent_model_input.repeat_interleave(2, dim=0)
|
1514 |
+
if do_classifier_free_guidance
|
1515 |
+
else latent_model_input
|
1516 |
+
)
|
1517 |
+
latent_model_input = self.scheduler.scale_model_input(
|
1518 |
+
latent_model_input, t
|
1519 |
+
)
|
1520 |
+
|
1521 |
+
prompt_embeds_input = torch.cat([prompt_embeds] * vb_size)
|
1522 |
+
add_text_embeds_input = torch.cat([add_text_embeds] * vb_size)
|
1523 |
+
add_time_ids_input = torch.cat([add_time_ids] * vb_size)
|
1524 |
+
|
1525 |
+
# predict the noise residual
|
1526 |
+
added_cond_kwargs = {
|
1527 |
+
"text_embeds": add_text_embeds_input,
|
1528 |
+
"time_ids": add_time_ids_input,
|
1529 |
+
}
|
1530 |
+
noise_pred = self.unet(
|
1531 |
+
latent_model_input,
|
1532 |
+
t,
|
1533 |
+
encoder_hidden_states=prompt_embeds_input,
|
1534 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
1535 |
+
added_cond_kwargs=added_cond_kwargs,
|
1536 |
+
return_dict=False,
|
1537 |
+
)[0]
|
1538 |
+
|
1539 |
+
if do_classifier_free_guidance:
|
1540 |
+
noise_pred_uncond, noise_pred_text = (
|
1541 |
+
noise_pred[::2],
|
1542 |
+
noise_pred[1::2],
|
1543 |
+
)
|
1544 |
+
noise_pred = noise_pred_uncond + guidance_scale * (
|
1545 |
+
noise_pred_text - noise_pred_uncond
|
1546 |
+
)
|
1547 |
+
|
1548 |
+
if do_classifier_free_guidance and guidance_rescale > 0.0:
|
1549 |
+
# Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
|
1550 |
+
noise_pred = rescale_noise_cfg(
|
1551 |
+
noise_pred,
|
1552 |
+
noise_pred_text,
|
1553 |
+
guidance_rescale=guidance_rescale,
|
1554 |
+
)
|
1555 |
+
|
1556 |
+
# compute the previous noisy sample x_t -> x_t-1
|
1557 |
+
self.scheduler._init_step_index(t)
|
1558 |
+
latents_denoised_batch = self.scheduler.step(
|
1559 |
+
noise_pred,
|
1560 |
+
t,
|
1561 |
+
latents_for_view,
|
1562 |
+
**extra_step_kwargs,
|
1563 |
+
return_dict=False,
|
1564 |
+
)[0]
|
1565 |
+
|
1566 |
+
# extract value from batch
|
1567 |
+
for latents_view_denoised, (h, w) in zip(
|
1568 |
+
latents_denoised_batch.chunk(vb_size), batch_view
|
1569 |
+
):
|
1570 |
+
value_global[
|
1571 |
+
:, :, h::current_scale_num, w::current_scale_num
|
1572 |
+
] += latents_view_denoised
|
1573 |
+
count_global[
|
1574 |
+
:, :, h::current_scale_num, w::current_scale_num
|
1575 |
+
] += 1
|
1576 |
+
|
1577 |
+
c2 = cosine_factor**cosine_scale_2
|
1578 |
+
|
1579 |
+
value_global = value_global[:, :, h_pad:, w_pad:]
|
1580 |
+
|
1581 |
+
value += value_global * c2
|
1582 |
+
count += torch.ones_like(value_global) * c2
|
1583 |
+
|
1584 |
+
###########################################################
|
1585 |
+
|
1586 |
+
latents = torch.where(count > 0, value / count, value)
|
1587 |
+
|
1588 |
+
# call the callback, if provided
|
1589 |
+
if i == len(timesteps) - 1 or (
|
1590 |
+
(i + 1) > num_warmup_steps
|
1591 |
+
and (i + 1) % self.scheduler.order == 0
|
1592 |
+
):
|
1593 |
+
progress_bar.update()
|
1594 |
+
if callback is not None and i % callback_steps == 0:
|
1595 |
+
step_idx = i // getattr(self.scheduler, "order", 1)
|
1596 |
+
callback(step_idx, t, latents)
|
1597 |
+
|
1598 |
+
#########################################################################################################################################
|
1599 |
+
|
1600 |
+
latents = (
|
1601 |
+
latents - latents.mean()
|
1602 |
+
) / latents.std() * anchor_std + anchor_mean
|
1603 |
+
if self.lowvram:
|
1604 |
+
latents = latents.cpu()
|
1605 |
+
torch.cuda.empty_cache()
|
1606 |
+
if not output_type == "latent":
|
1607 |
+
# make sure the VAE is in float32 mode, as it overflows in float16
|
1608 |
+
needs_upcasting = (
|
1609 |
+
self.vae.dtype == torch.float16 and self.vae.config.force_upcast
|
1610 |
+
)
|
1611 |
+
|
1612 |
+
if self.lowvram:
|
1613 |
+
needs_upcasting = (
|
1614 |
+
False # use madebyollin/sdxl-vae-fp16-fix in lowvram mode!
|
1615 |
+
)
|
1616 |
+
self.unet.cpu()
|
1617 |
+
self.vae.to(device)
|
1618 |
+
|
1619 |
+
if needs_upcasting:
|
1620 |
+
self.upcast_vae()
|
1621 |
+
latents = latents.to(
|
1622 |
+
next(iter(self.vae.post_quant_conv.parameters())).dtype
|
1623 |
+
)
|
1624 |
+
|
1625 |
+
print("### Phase {} Decoding ###".format(current_scale_num))
|
1626 |
+
if multi_decoder:
|
1627 |
+
image = self.tiled_decode(
|
1628 |
+
latents, current_height, current_width
|
1629 |
+
)
|
1630 |
+
else:
|
1631 |
+
image = self.vae.decode(
|
1632 |
+
latents / self.vae.config.scaling_factor, return_dict=False
|
1633 |
+
)[0]
|
1634 |
+
|
1635 |
+
# cast back to fp16 if needed
|
1636 |
+
if needs_upcasting:
|
1637 |
+
self.vae.to(dtype=torch.float16)
|
1638 |
+
else:
|
1639 |
+
image = latents
|
1640 |
+
|
1641 |
+
if not output_type == "latent":
|
1642 |
+
image = self.image_processor.postprocess(
|
1643 |
+
image, output_type=output_type
|
1644 |
+
)
|
1645 |
+
if show_image:
|
1646 |
+
plt.figure(figsize=(10, 10))
|
1647 |
+
plt.imshow(image[0])
|
1648 |
+
plt.axis("off") # Turn off axis numbers and ticks
|
1649 |
+
plt.show()
|
1650 |
+
output_images.append(image[0])
|
1651 |
+
|
1652 |
+
# Offload all models
|
1653 |
+
self.maybe_free_model_hooks()
|
1654 |
+
|
1655 |
+
return output_images
|
1656 |
+
|
1657 |
+
# Overrride to properly handle the loading and unloading of the additional text encoder.
|
1658 |
+
def load_lora_weights(
|
1659 |
+
self,
|
1660 |
+
pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]],
|
1661 |
+
**kwargs,
|
1662 |
+
):
|
1663 |
+
# We could have accessed the unet config from `lora_state_dict()` too. We pass
|
1664 |
+
# it here explicitly to be able to tell that it's coming from an SDXL
|
1665 |
+
# pipeline.
|
1666 |
+
|
1667 |
+
# Remove any existing hooks.
|
1668 |
+
if is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"):
|
1669 |
+
from accelerate.hooks import (
|
1670 |
+
AlignDevicesHook,
|
1671 |
+
CpuOffload,
|
1672 |
+
remove_hook_from_module,
|
1673 |
+
)
|
1674 |
+
else:
|
1675 |
+
raise ImportError("Offloading requires `accelerate v0.17.0` or higher.")
|
1676 |
+
|
1677 |
+
is_model_cpu_offload = False
|
1678 |
+
is_sequential_cpu_offload = False
|
1679 |
+
recursive = False
|
1680 |
+
for _, component in self.components.items():
|
1681 |
+
if isinstance(component, torch.nn.Module):
|
1682 |
+
if hasattr(component, "_hf_hook"):
|
1683 |
+
is_model_cpu_offload = isinstance(
|
1684 |
+
getattr(component, "_hf_hook"), CpuOffload
|
1685 |
+
)
|
1686 |
+
is_sequential_cpu_offload = isinstance(
|
1687 |
+
getattr(component, "_hf_hook"), AlignDevicesHook
|
1688 |
+
)
|
1689 |
+
logger.info(
|
1690 |
+
"Accelerate hooks detected. Since you have called `load_lora_weights()`, the previous hooks will be first removed. Then the LoRA parameters will be loaded and the hooks will be applied again."
|
1691 |
+
)
|
1692 |
+
recursive = is_sequential_cpu_offload
|
1693 |
+
remove_hook_from_module(component, recurse=recursive)
|
1694 |
+
state_dict, network_alphas = self.lora_state_dict(
|
1695 |
+
pretrained_model_name_or_path_or_dict,
|
1696 |
+
unet_config=self.unet.config,
|
1697 |
+
**kwargs,
|
1698 |
+
)
|
1699 |
+
self.load_lora_into_unet(
|
1700 |
+
state_dict, network_alphas=network_alphas, unet=self.unet
|
1701 |
+
)
|
1702 |
+
|
1703 |
+
text_encoder_state_dict = {
|
1704 |
+
k: v for k, v in state_dict.items() if "text_encoder." in k
|
1705 |
+
}
|
1706 |
+
if len(text_encoder_state_dict) > 0:
|
1707 |
+
self.load_lora_into_text_encoder(
|
1708 |
+
text_encoder_state_dict,
|
1709 |
+
network_alphas=network_alphas,
|
1710 |
+
text_encoder=self.text_encoder,
|
1711 |
+
prefix="text_encoder",
|
1712 |
+
lora_scale=self.lora_scale,
|
1713 |
+
)
|
1714 |
+
|
1715 |
+
text_encoder_2_state_dict = {
|
1716 |
+
k: v for k, v in state_dict.items() if "text_encoder_2." in k
|
1717 |
+
}
|
1718 |
+
if len(text_encoder_2_state_dict) > 0:
|
1719 |
+
self.load_lora_into_text_encoder(
|
1720 |
+
text_encoder_2_state_dict,
|
1721 |
+
network_alphas=network_alphas,
|
1722 |
+
text_encoder=self.text_encoder_2,
|
1723 |
+
prefix="text_encoder_2",
|
1724 |
+
lora_scale=self.lora_scale,
|
1725 |
+
)
|
1726 |
+
|
1727 |
+
# Offload back.
|
1728 |
+
if is_model_cpu_offload:
|
1729 |
+
self.enable_model_cpu_offload()
|
1730 |
+
elif is_sequential_cpu_offload:
|
1731 |
+
self.enable_sequential_cpu_offload()
|
1732 |
+
|
1733 |
+
@classmethod
|
1734 |
+
def save_lora_weights(
|
1735 |
+
self,
|
1736 |
+
save_directory: Union[str, os.PathLike],
|
1737 |
+
unet_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
|
1738 |
+
text_encoder_lora_layers: Dict[
|
1739 |
+
str, Union[torch.nn.Module, torch.Tensor]
|
1740 |
+
] = None,
|
1741 |
+
text_encoder_2_lora_layers: Dict[
|
1742 |
+
str, Union[torch.nn.Module, torch.Tensor]
|
1743 |
+
] = None,
|
1744 |
+
is_main_process: bool = True,
|
1745 |
+
weight_name: str = None,
|
1746 |
+
save_function: Callable = None,
|
1747 |
+
safe_serialization: bool = True,
|
1748 |
+
):
|
1749 |
+
state_dict = {}
|
1750 |
+
|
1751 |
+
def pack_weights(layers, prefix):
|
1752 |
+
layers_weights = (
|
1753 |
+
layers.state_dict() if isinstance(layers, torch.nn.Module) else layers
|
1754 |
+
)
|
1755 |
+
layers_state_dict = {
|
1756 |
+
f"{prefix}.{module_name}": param
|
1757 |
+
for module_name, param in layers_weights.items()
|
1758 |
+
}
|
1759 |
+
return layers_state_dict
|
1760 |
+
|
1761 |
+
if not (
|
1762 |
+
unet_lora_layers or text_encoder_lora_layers or text_encoder_2_lora_layers
|
1763 |
+
):
|
1764 |
+
raise ValueError(
|
1765 |
+
"You must pass at least one of `unet_lora_layers`, `text_encoder_lora_layers` or `text_encoder_2_lora_layers`."
|
1766 |
+
)
|
1767 |
+
|
1768 |
+
if unet_lora_layers:
|
1769 |
+
state_dict.update(pack_weights(unet_lora_layers, "unet"))
|
1770 |
+
|
1771 |
+
if text_encoder_lora_layers and text_encoder_2_lora_layers:
|
1772 |
+
state_dict.update(pack_weights(text_encoder_lora_layers, "text_encoder"))
|
1773 |
+
state_dict.update(
|
1774 |
+
pack_weights(text_encoder_2_lora_layers, "text_encoder_2")
|
1775 |
+
)
|
1776 |
+
|
1777 |
+
self.write_lora_layers(
|
1778 |
+
state_dict=state_dict,
|
1779 |
+
save_directory=save_directory,
|
1780 |
+
is_main_process=is_main_process,
|
1781 |
+
weight_name=weight_name,
|
1782 |
+
save_function=save_function,
|
1783 |
+
safe_serialization=safe_serialization,
|
1784 |
+
)
|
1785 |
+
|
1786 |
+
def _remove_text_encoder_monkey_patch(self):
|
1787 |
+
self._remove_text_encoder_monkey_patch_classmethod(self.text_encoder)
|
1788 |
+
self._remove_text_encoder_monkey_patch_classmethod(self.text_encoder_2)
|
requirements.txt
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
gradio==4.8.0
|
2 |
+
git+https://github.com/huggingface/diffusers@4684ea2fe8d568f44c491068c3eb94aac27045f3
|
3 |
+
accelerate
|
4 |
+
transformers
|
5 |
+
--extra-index-url https://download.pytorch.org/whl/cu118
|
6 |
+
torch
|
7 |
+
torchvision
|
8 |
+
xformers
|
9 |
+
accelerate
|
10 |
+
invisible-watermark
|
11 |
+
huggingface-hub
|
12 |
+
hf-transfer
|
13 |
+
gradio-imageslider
|