Spaces:
Running
on
A10G
Running
on
A10G
rynmurdock
commited on
Commit
•
0186388
1
Parent(s):
8b9775e
text & image, faster
Browse files- app.py +158 -67
- patch_sdxl.py +0 -559
app.py
CHANGED
@@ -1,5 +1,9 @@
|
|
1 |
DEVICE = 'cuda'
|
2 |
|
|
|
|
|
|
|
|
|
3 |
import gradio as gr
|
4 |
import numpy as np
|
5 |
from sklearn.svm import LinearSVC
|
@@ -23,7 +27,7 @@ from io import BytesIO, StringIO
|
|
23 |
from transformers import CLIPVisionModelWithProjection
|
24 |
from huggingface_hub import hf_hub_download
|
25 |
from safetensors.torch import load_file
|
26 |
-
import spaces
|
27 |
|
28 |
prompt_list = [p for p in list(set(
|
29 |
pd.read_csv('./twitter_prompts.csv').iloc[:, 1].tolist())) if type(p) == str]
|
@@ -46,12 +50,81 @@ pipe.register_modules(image_encoder = image_encoder)
|
|
46 |
pipe.vae = AutoencoderTiny.from_pretrained("madebyollin/taesdxl", torch_dtype=torch.float16)
|
47 |
pipe.scheduler = EulerDiscreteScheduler.from_config(pipe.scheduler.config, timestep_spacing="trailing")
|
48 |
pipe.to(device=DEVICE)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
49 |
|
50 |
|
51 |
output_hidden_state = False
|
52 |
#######################
|
53 |
|
54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
55 |
def predict(
|
56 |
prompt,
|
57 |
im_emb=None,
|
@@ -86,11 +159,47 @@ def predict(
|
|
86 |
image, DEVICE, 1, output_hidden_state
|
87 |
)
|
88 |
return image, im_emb.to('cpu')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
89 |
|
90 |
# TODO add to state instead of shared across all
|
91 |
glob_idx = 0
|
92 |
|
93 |
-
def next_image(embs, ys, calibrate_prompts):
|
94 |
global glob_idx
|
95 |
glob_idx = glob_idx + 1
|
96 |
if glob_idx >= 12:
|
@@ -100,6 +209,8 @@ def next_image(embs, ys, calibrate_prompts):
|
|
100 |
if len(calibrate_prompts) == 0 and len(list(set(ys))) <= 1:
|
101 |
embs.append(.01*torch.randn(1, 1024))
|
102 |
embs.append(.01*torch.randn(1, 1024))
|
|
|
|
|
103 |
ys.append(0)
|
104 |
ys.append(1)
|
105 |
|
@@ -109,53 +220,34 @@ def next_image(embs, ys, calibrate_prompts):
|
|
109 |
prompt = calibrate_prompts.pop(0)
|
110 |
print(prompt)
|
111 |
image, img_emb = predict(prompt)
|
112 |
-
|
113 |
-
|
|
|
|
|
114 |
else:
|
115 |
print('######### Roaming #########')
|
116 |
-
# sample a .8 of rated embeddings for some stochasticity, or at least two embeddings.
|
117 |
-
n_to_choose = max(int(len(embs)*.8), 2)
|
118 |
-
indices = random.sample(range(len(embs)), n_to_choose)
|
119 |
-
|
120 |
-
# we may have just encountered a rare multi-threading diffusers issue (https://github.com/huggingface/diffusers/issues/5749);
|
121 |
-
# this ends up adding a rating but losing an embedding, it seems.
|
122 |
-
# let's take off a rating if so to continue without indexing errors.
|
123 |
-
if len(ys) > len(embs):
|
124 |
-
print('ys are longer than embs; popping latest rating')
|
125 |
-
ys.pop(-1)
|
126 |
-
|
127 |
-
# also add the latest 0 and the latest 1
|
128 |
-
has_0 = False
|
129 |
-
has_1 = False
|
130 |
-
for i in reversed(range(len(ys))):
|
131 |
-
if ys[i] == 0 and has_0 == False:
|
132 |
-
indices.append(i)
|
133 |
-
has_0 = True
|
134 |
-
elif ys[i] == 1 and has_1 == False:
|
135 |
-
indices.append(i)
|
136 |
-
has_1 = True
|
137 |
-
if has_0 and has_1:
|
138 |
-
break
|
139 |
-
|
140 |
-
feature_embs = np.array(torch.cat([embs[i].to('cpu') for i in indices]).to('cpu'))
|
141 |
-
scaler = preprocessing.StandardScaler().fit(feature_embs)
|
142 |
-
feature_embs = scaler.transform(feature_embs)
|
143 |
-
|
144 |
-
lin_class = LinearSVC(max_iter=50000, dual='auto', class_weight='balanced').fit(feature_embs, np.array([ys[i] for i in indices]))
|
145 |
-
lin_class.coef_ = torch.tensor(lin_class.coef_, dtype=torch.double)
|
146 |
-
lin_class.coef_ = (lin_class.coef_.flatten() / (lin_class.coef_.flatten().norm())).unsqueeze(0)
|
147 |
|
|
|
148 |
rng_prompt = random.choice(prompt_list)
|
149 |
w = 1.4# if len(embs) % 2 == 0 else 0
|
150 |
-
|
151 |
-
prompt= '
|
152 |
-
|
153 |
-
|
|
|
|
|
154 |
embs.append(im_emb)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
155 |
if len(embs) > 20:
|
156 |
embs.pop(0)
|
157 |
ys.pop(0)
|
158 |
-
return image, embs, ys, calibrate_prompts
|
159 |
|
160 |
|
161 |
|
@@ -165,8 +257,8 @@ def next_image(embs, ys, calibrate_prompts):
|
|
165 |
|
166 |
|
167 |
|
168 |
-
def start(_, embs, ys, calibrate_prompts):
|
169 |
-
image, embs, ys, calibrate_prompts = next_image(embs, ys, calibrate_prompts)
|
170 |
return [
|
171 |
gr.Button(value='Like (L)', interactive=True),
|
172 |
gr.Button(value='Neither (Space)', interactive=True),
|
@@ -174,23 +266,24 @@ def start(_, embs, ys, calibrate_prompts):
|
|
174 |
gr.Button(value='Start', interactive=False),
|
175 |
image,
|
176 |
embs,
|
|
|
177 |
ys,
|
178 |
calibrate_prompts
|
179 |
]
|
180 |
|
181 |
|
182 |
-
def choose(choice, embs, ys, calibrate_prompts):
|
183 |
if choice == 'Like (L)':
|
184 |
choice = 1
|
185 |
elif choice == 'Neither (Space)':
|
186 |
_ = embs.pop(-1)
|
187 |
-
img, embs, ys, calibrate_prompts = next_image(embs, ys, calibrate_prompts)
|
188 |
-
return img, embs, ys, calibrate_prompts
|
189 |
else:
|
190 |
choice = 0
|
191 |
ys.append(choice)
|
192 |
-
img, embs, ys, calibrate_prompts = next_image(embs, ys, calibrate_prompts)
|
193 |
-
return img, embs, ys, calibrate_prompts
|
194 |
|
195 |
css = '''.gradio-container{max-width: 700px !important}
|
196 |
#description{text-align: center}
|
@@ -248,48 +341,46 @@ with gr.Blocks(css=css, head=js_head) as demo:
|
|
248 |
Explore the latent space without text prompts, based on your preferences. Learn more on [the write-up](https://rynmurdock.github.io/posts/2024/3/generative_recomenders/).
|
249 |
''', elem_id="description")
|
250 |
embs = gr.State([])
|
|
|
251 |
ys = gr.State([])
|
252 |
calibrate_prompts = gr.State([
|
253 |
-
|
254 |
-
'
|
255 |
-
|
256 |
-
'a
|
257 |
-
'
|
258 |
-
'
|
259 |
-
'a sketch',
|
260 |
-
# 'a city full of darkness and graffiti',
|
261 |
-
'',
|
262 |
])
|
263 |
|
264 |
with gr.Row(elem_id='output-image'):
|
265 |
-
img = gr.Image(interactive=False, elem_id='output-image',width=700)
|
266 |
with gr.Row(equal_height=True):
|
267 |
b3 = gr.Button(value='Dislike (A)', interactive=False, elem_id="dislike")
|
268 |
b2 = gr.Button(value='Neither (Space)', interactive=False, elem_id="neither")
|
269 |
b1 = gr.Button(value='Like (L)', interactive=False, elem_id="like")
|
270 |
b1.click(
|
271 |
choose,
|
272 |
-
[b1, embs, ys, calibrate_prompts],
|
273 |
-
[img, embs, ys, calibrate_prompts]
|
274 |
)
|
275 |
b2.click(
|
276 |
choose,
|
277 |
-
[b2, embs, ys, calibrate_prompts],
|
278 |
-
[img, embs, ys, calibrate_prompts]
|
279 |
)
|
280 |
b3.click(
|
281 |
choose,
|
282 |
-
[b3, embs, ys, calibrate_prompts],
|
283 |
-
[img, embs, ys, calibrate_prompts]
|
284 |
)
|
285 |
with gr.Row():
|
286 |
b4 = gr.Button(value='Start')
|
287 |
b4.click(start,
|
288 |
-
[b4, embs, ys, calibrate_prompts],
|
289 |
-
[b1, b2, b3, b4, img, embs, ys, calibrate_prompts])
|
290 |
with gr.Row():
|
291 |
html = gr.HTML('''<div style='text-align:center; font-size:20px'>You will calibrate for several prompts and then roam. </ div><br><br><br>
|
292 |
<div style='text-align:center; font-size:14px'>Note that while the SDXL model is unlikely to produce NSFW images, it still may be possible, and users should avoid NSFW content when rating.
|
293 |
</ div>''')
|
294 |
|
295 |
-
demo.launch() # Share your demo with just 1 extra parameter 🚀
|
|
|
1 |
DEVICE = 'cuda'
|
2 |
|
3 |
+
from sfast.compilers.diffusion_pipeline_compiler import (compile,
|
4 |
+
CompilationConfig)
|
5 |
+
config = CompilationConfig.Default()
|
6 |
+
|
7 |
import gradio as gr
|
8 |
import numpy as np
|
9 |
from sklearn.svm import LinearSVC
|
|
|
27 |
from transformers import CLIPVisionModelWithProjection
|
28 |
from huggingface_hub import hf_hub_download
|
29 |
from safetensors.torch import load_file
|
30 |
+
#import spaces
|
31 |
|
32 |
prompt_list = [p for p in list(set(
|
33 |
pd.read_csv('./twitter_prompts.csv').iloc[:, 1].tolist())) if type(p) == str]
|
|
|
50 |
pipe.vae = AutoencoderTiny.from_pretrained("madebyollin/taesdxl", torch_dtype=torch.float16)
|
51 |
pipe.scheduler = EulerDiscreteScheduler.from_config(pipe.scheduler.config, timestep_spacing="trailing")
|
52 |
pipe.to(device=DEVICE)
|
53 |
+
pipe = compile(pipe, config=config)
|
54 |
+
|
55 |
+
image = pipe(prompt_embeds=torch.zeros(1, 1, 2048, dtype=torch.float16, device=DEVICE),
|
56 |
+
pooled_prompt_embeds=torch.zeros(1, 1280, dtype=torch.float16, device=DEVICE),
|
57 |
+
ip_adapter_image_embeds=[torch.zeros(1, 1, 1024, dtype=torch.float16, device=DEVICE)],
|
58 |
+
height=1024,
|
59 |
+
width=1024,
|
60 |
+
num_inference_steps=2,
|
61 |
+
guidance_scale=0,
|
62 |
+
).images[0]
|
63 |
|
64 |
|
65 |
output_hidden_state = False
|
66 |
#######################
|
67 |
|
68 |
+
####################### Setup autoencoder
|
69 |
+
|
70 |
+
from tqdm import tqdm
|
71 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
72 |
+
|
73 |
+
class BottleneckT5Autoencoder:
|
74 |
+
def __init__(self, model_path: str, device='cuda'):
|
75 |
+
self.device = device
|
76 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_path, model_max_length=512, torch_dtype=torch.bfloat16)
|
77 |
+
self.model = AutoModelForCausalLM.from_pretrained(model_path, trust_remote_code=True).to(self.device)
|
78 |
+
self.model.eval()
|
79 |
+
# self.model = torch.compile(self.model)
|
80 |
+
|
81 |
+
|
82 |
+
def embed(self, text: str) -> torch.FloatTensor:
|
83 |
+
inputs = self.tokenizer(text, return_tensors='pt', padding=True).to(self.device)
|
84 |
+
decoder_inputs = self.tokenizer('', return_tensors='pt').to(self.device)
|
85 |
+
return self.model(
|
86 |
+
**inputs,
|
87 |
+
decoder_input_ids=decoder_inputs['input_ids'],
|
88 |
+
encode_only=True,
|
89 |
+
)
|
90 |
+
|
91 |
+
def generate_from_latent(self, latent: torch.FloatTensor, max_length=512, temperature=1., top_p=.8, length_penalty=10, min_new_tokens=30) -> str:
|
92 |
+
dummy_text = '.'
|
93 |
+
dummy = self.embed(dummy_text)
|
94 |
+
perturb_vector = latent - dummy
|
95 |
+
self.model.perturb_vector = perturb_vector
|
96 |
+
input_ids = self.tokenizer(dummy_text, return_tensors='pt').to(self.device).input_ids
|
97 |
+
output = self.model.generate(
|
98 |
+
input_ids=input_ids,
|
99 |
+
max_length=max_length,
|
100 |
+
do_sample=True,
|
101 |
+
temperature=temperature,
|
102 |
+
top_p=top_p,
|
103 |
+
num_return_sequences=1,
|
104 |
+
length_penalty=length_penalty,
|
105 |
+
min_new_tokens=min_new_tokens,
|
106 |
+
# num_beams=8,
|
107 |
+
)
|
108 |
+
return self.tokenizer.decode(output[0], skip_special_tokens=True)
|
109 |
+
|
110 |
+
autoencoder = BottleneckT5Autoencoder(model_path='thesephist/contra-bottleneck-t5-xl-wikipedia')
|
111 |
+
|
112 |
+
#######################
|
113 |
+
|
114 |
+
def generate(prompt, in_embs=None,):
|
115 |
+
if prompt != '':
|
116 |
+
print(prompt)
|
117 |
+
in_embs = in_embs / in_embs.abs().max() * .15 if in_embs != None else None
|
118 |
+
in_embs = .9 * in_embs.to('cuda') + .5 * autoencoder.embed(prompt).to('cuda') if in_embs != None else autoencoder.embed(prompt).to('cuda')
|
119 |
+
else:
|
120 |
+
print('From embeds.')
|
121 |
+
in_embs = in_embs / in_embs.abs().max() * .15
|
122 |
+
text = autoencoder.generate_from_latent(in_embs.to('cuda').to(dtype=torch.bfloat16), temperature=.3, top_p=.99, min_new_tokens=5)
|
123 |
+
return text, in_embs.to('cpu')
|
124 |
+
|
125 |
+
|
126 |
+
|
127 |
+
#@spaces.GPU
|
128 |
def predict(
|
129 |
prompt,
|
130 |
im_emb=None,
|
|
|
159 |
image, DEVICE, 1, output_hidden_state
|
160 |
)
|
161 |
return image, im_emb.to('cpu')
|
162 |
+
|
163 |
+
|
164 |
+
# sample a .8 of rated embeddings for some stochasticity, or at least two embeddings.
|
165 |
+
def get_coeff(embs, ys):
|
166 |
+
n_to_choose = max(int(len(embs)*.8), 2)
|
167 |
+
indices = random.sample(range(len(embs)), n_to_choose)
|
168 |
+
|
169 |
+
# we may have just encountered a rare multi-threading diffusers issue (https://github.com/huggingface/diffusers/issues/5749);
|
170 |
+
# this ends up adding a rating but losing an embedding, it seems.
|
171 |
+
# let's take off a rating if so to continue without indexing errors.
|
172 |
+
if len(ys) > len(embs):
|
173 |
+
print('ys are longer than embs; popping latest rating')
|
174 |
+
ys.pop(-1)
|
175 |
+
|
176 |
+
# also add the latest 0 and the latest 1
|
177 |
+
has_0 = False
|
178 |
+
has_1 = False
|
179 |
+
for i in reversed(range(len(ys))):
|
180 |
+
if ys[i] == 0 and has_0 == False:
|
181 |
+
indices.append(i)
|
182 |
+
has_0 = True
|
183 |
+
elif ys[i] == 1 and has_1 == False:
|
184 |
+
indices.append(i)
|
185 |
+
has_1 = True
|
186 |
+
if has_0 and has_1:
|
187 |
+
break
|
188 |
+
|
189 |
+
feature_embs = np.array(torch.cat([embs[i].to('cpu') for i in indices]).to('cpu'))
|
190 |
+
scaler = preprocessing.StandardScaler().fit(feature_embs)
|
191 |
+
feature_embs = scaler.transform(feature_embs)
|
192 |
+
|
193 |
+
lin_class = LinearSVC(max_iter=50000, dual='auto', class_weight='balanced').fit(feature_embs, np.array([ys[i] for i in indices]))
|
194 |
+
lin_class.coef_ = torch.tensor(lin_class.coef_, dtype=torch.double)
|
195 |
+
lin_class.coef_ = (lin_class.coef_.flatten() / (lin_class.coef_.flatten().norm())).unsqueeze(0)
|
196 |
+
|
197 |
+
return lin_class.coef_
|
198 |
|
199 |
# TODO add to state instead of shared across all
|
200 |
glob_idx = 0
|
201 |
|
202 |
+
def next_image(embs, img_embs, ys, calibrate_prompts):
|
203 |
global glob_idx
|
204 |
glob_idx = glob_idx + 1
|
205 |
if glob_idx >= 12:
|
|
|
209 |
if len(calibrate_prompts) == 0 and len(list(set(ys))) <= 1:
|
210 |
embs.append(.01*torch.randn(1, 1024))
|
211 |
embs.append(.01*torch.randn(1, 1024))
|
212 |
+
img_embs.append(.01*torch.randn(1, 1024))
|
213 |
+
img_embs.append(.01*torch.randn(1, 1024))
|
214 |
ys.append(0)
|
215 |
ys.append(1)
|
216 |
|
|
|
220 |
prompt = calibrate_prompts.pop(0)
|
221 |
print(prompt)
|
222 |
image, img_emb = predict(prompt)
|
223 |
+
im_emb = autoencoder.embed(prompt)
|
224 |
+
embs.append(im_emb)
|
225 |
+
img_embs.append(img_emb)
|
226 |
+
return image, embs, img_embs, ys, calibrate_prompts
|
227 |
else:
|
228 |
print('######### Roaming #########')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
229 |
|
230 |
+
im_s = get_coeff(embs, ys)
|
231 |
rng_prompt = random.choice(prompt_list)
|
232 |
w = 1.4# if len(embs) % 2 == 0 else 0
|
233 |
+
|
234 |
+
prompt= '' if glob_idx % 2 == 0 else rng_prompt
|
235 |
+
|
236 |
+
prompt, _ = generate(prompt, in_embs=im_s)
|
237 |
+
print(prompt)
|
238 |
+
im_emb = autoencoder.embed(prompt)
|
239 |
embs.append(im_emb)
|
240 |
+
|
241 |
+
learn_emb = get_coeff(img_embs, ys)
|
242 |
+
|
243 |
+
img_emb = w * learn_emb.to(dtype=torch.float16)
|
244 |
+
image, img_emb = predict(prompt, im_emb=img_emb)
|
245 |
+
img_embs.append(img_emb)
|
246 |
+
|
247 |
if len(embs) > 20:
|
248 |
embs.pop(0)
|
249 |
ys.pop(0)
|
250 |
+
return image, embs, img_embs, ys, calibrate_prompts
|
251 |
|
252 |
|
253 |
|
|
|
257 |
|
258 |
|
259 |
|
260 |
+
def start(_, embs, img_embs, ys, calibrate_prompts):
|
261 |
+
image, embs, img_embs, ys, calibrate_prompts = next_image(embs, img_embs, ys, calibrate_prompts)
|
262 |
return [
|
263 |
gr.Button(value='Like (L)', interactive=True),
|
264 |
gr.Button(value='Neither (Space)', interactive=True),
|
|
|
266 |
gr.Button(value='Start', interactive=False),
|
267 |
image,
|
268 |
embs,
|
269 |
+
img_embs,
|
270 |
ys,
|
271 |
calibrate_prompts
|
272 |
]
|
273 |
|
274 |
|
275 |
+
def choose(choice, embs, img_embs, ys, calibrate_prompts):
|
276 |
if choice == 'Like (L)':
|
277 |
choice = 1
|
278 |
elif choice == 'Neither (Space)':
|
279 |
_ = embs.pop(-1)
|
280 |
+
img, embs, img_embs, ys, calibrate_prompts = next_image(embs, img_embs, ys, calibrate_prompts)
|
281 |
+
return img, embs, img_embs, ys, calibrate_prompts
|
282 |
else:
|
283 |
choice = 0
|
284 |
ys.append(choice)
|
285 |
+
img, embs, img_embs, ys, calibrate_prompts = next_image(embs, img_embs, ys, calibrate_prompts)
|
286 |
+
return img, embs, img_embs, ys, calibrate_prompts
|
287 |
|
288 |
css = '''.gradio-container{max-width: 700px !important}
|
289 |
#description{text-align: center}
|
|
|
341 |
Explore the latent space without text prompts, based on your preferences. Learn more on [the write-up](https://rynmurdock.github.io/posts/2024/3/generative_recomenders/).
|
342 |
''', elem_id="description")
|
343 |
embs = gr.State([])
|
344 |
+
img_embs = gr.State([])
|
345 |
ys = gr.State([])
|
346 |
calibrate_prompts = gr.State([
|
347 |
+
'the moon is melting into my glass of tea',
|
348 |
+
'a sea slug -- pair of claws scuttling -- jelly fish glowing',
|
349 |
+
'an adorable creature. It may be a goblin or a pig or a slug.',
|
350 |
+
'an animation about a gorgeous nebula',
|
351 |
+
'a sketch of an impressive mountain by da vinci',
|
352 |
+
'a watercolor painting: the octopus writhes',
|
|
|
|
|
|
|
353 |
])
|
354 |
|
355 |
with gr.Row(elem_id='output-image'):
|
356 |
+
img = gr.Image(interactive=False, elem_id='output-image', width=700)
|
357 |
with gr.Row(equal_height=True):
|
358 |
b3 = gr.Button(value='Dislike (A)', interactive=False, elem_id="dislike")
|
359 |
b2 = gr.Button(value='Neither (Space)', interactive=False, elem_id="neither")
|
360 |
b1 = gr.Button(value='Like (L)', interactive=False, elem_id="like")
|
361 |
b1.click(
|
362 |
choose,
|
363 |
+
[b1, embs, img_embs, ys, calibrate_prompts],
|
364 |
+
[img, embs, img_embs, ys, calibrate_prompts]
|
365 |
)
|
366 |
b2.click(
|
367 |
choose,
|
368 |
+
[b2, embs, img_embs, ys, calibrate_prompts],
|
369 |
+
[img, embs, img_embs, ys, calibrate_prompts]
|
370 |
)
|
371 |
b3.click(
|
372 |
choose,
|
373 |
+
[b3, embs, img_embs, ys, calibrate_prompts],
|
374 |
+
[img, embs, img_embs, ys, calibrate_prompts]
|
375 |
)
|
376 |
with gr.Row():
|
377 |
b4 = gr.Button(value='Start')
|
378 |
b4.click(start,
|
379 |
+
[b4, embs, img_embs, ys, calibrate_prompts],
|
380 |
+
[b1, b2, b3, b4, img, embs, img_embs, ys, calibrate_prompts])
|
381 |
with gr.Row():
|
382 |
html = gr.HTML('''<div style='text-align:center; font-size:20px'>You will calibrate for several prompts and then roam. </ div><br><br><br>
|
383 |
<div style='text-align:center; font-size:14px'>Note that while the SDXL model is unlikely to produce NSFW images, it still may be possible, and users should avoid NSFW content when rating.
|
384 |
</ div>''')
|
385 |
|
386 |
+
demo.launch(share=True) # Share your demo with just 1 extra parameter 🚀
|
patch_sdxl.py
DELETED
@@ -1,559 +0,0 @@
|
|
1 |
-
import inspect
|
2 |
-
from typing import Any, Callable, Dict, List, Optional, Union, Tuple
|
3 |
-
|
4 |
-
from diffusers import StableDiffusionXLPipeline
|
5 |
-
|
6 |
-
import torch
|
7 |
-
from packaging import version
|
8 |
-
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
|
9 |
-
|
10 |
-
from diffusers.configuration_utils import FrozenDict
|
11 |
-
from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
|
12 |
-
from diffusers.loaders import FromSingleFileMixin, IPAdapterMixin, LoraLoaderMixin, TextualInversionLoaderMixin
|
13 |
-
from diffusers.models import AutoencoderKL, ImageProjection, UNet2DConditionModel
|
14 |
-
from diffusers.models.attention_processor import FusedAttnProcessor2_0
|
15 |
-
from diffusers.models.lora import adjust_lora_scale_text_encoder
|
16 |
-
from diffusers.schedulers import KarrasDiffusionSchedulers
|
17 |
-
from diffusers.utils import (
|
18 |
-
USE_PEFT_BACKEND,
|
19 |
-
deprecate,
|
20 |
-
logging,
|
21 |
-
replace_example_docstring,
|
22 |
-
scale_lora_layers,
|
23 |
-
unscale_lora_layers,
|
24 |
-
)
|
25 |
-
from diffusers.pipelines.stable_diffusion_xl import StableDiffusionXLPipelineOutput
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
from transformers import CLIPFeatureExtractor
|
30 |
-
import numpy as np
|
31 |
-
import torch
|
32 |
-
from PIL import Image
|
33 |
-
from typing import Optional, Tuple, Union
|
34 |
-
|
35 |
-
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
36 |
-
torch_device = device
|
37 |
-
torch_dtype = torch.float16
|
38 |
-
|
39 |
-
|
40 |
-
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
41 |
-
|
42 |
-
EXAMPLE_DOC_STRING = """
|
43 |
-
Examples:
|
44 |
-
```py
|
45 |
-
>>> import torch
|
46 |
-
>>> from diffusers import StableDiffusionPipeline
|
47 |
-
|
48 |
-
>>> pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16)
|
49 |
-
>>> pipe = pipe.to("cuda")
|
50 |
-
|
51 |
-
>>> prompt = "a photo of an astronaut riding a horse on mars"
|
52 |
-
>>> image = pipe(prompt).images[0]
|
53 |
-
```
|
54 |
-
"""
|
55 |
-
|
56 |
-
|
57 |
-
def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
|
58 |
-
"""
|
59 |
-
Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
|
60 |
-
Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
|
61 |
-
"""
|
62 |
-
std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
|
63 |
-
std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
|
64 |
-
# rescale the results from guidance (fixes overexposure)
|
65 |
-
noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
|
66 |
-
# mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
|
67 |
-
noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
|
68 |
-
return noise_cfg
|
69 |
-
|
70 |
-
|
71 |
-
def retrieve_timesteps(
|
72 |
-
scheduler,
|
73 |
-
num_inference_steps: Optional[int] = None,
|
74 |
-
device: Optional[Union[str, torch.device]] = None,
|
75 |
-
timesteps: Optional[List[int]] = None,
|
76 |
-
**kwargs,
|
77 |
-
):
|
78 |
-
"""
|
79 |
-
Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
|
80 |
-
custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
|
81 |
-
|
82 |
-
Args:
|
83 |
-
scheduler (`SchedulerMixin`):
|
84 |
-
The scheduler to get timesteps from.
|
85 |
-
num_inference_steps (`int`):
|
86 |
-
The number of diffusion steps used when generating samples with a pre-trained model. If used,
|
87 |
-
`timesteps` must be `None`.
|
88 |
-
device (`str` or `torch.device`, *optional*):
|
89 |
-
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
|
90 |
-
timesteps (`List[int]`, *optional*):
|
91 |
-
Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
|
92 |
-
timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
|
93 |
-
must be `None`.
|
94 |
-
|
95 |
-
Returns:
|
96 |
-
`Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
|
97 |
-
second element is the number of inference steps.
|
98 |
-
"""
|
99 |
-
if timesteps is not None:
|
100 |
-
accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
101 |
-
if not accepts_timesteps:
|
102 |
-
raise ValueError(
|
103 |
-
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
104 |
-
f" timestep schedules. Please check whether you are using the correct scheduler."
|
105 |
-
)
|
106 |
-
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
|
107 |
-
timesteps = scheduler.timesteps
|
108 |
-
num_inference_steps = len(timesteps)
|
109 |
-
else:
|
110 |
-
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
111 |
-
timesteps = scheduler.timesteps
|
112 |
-
return timesteps, num_inference_steps
|
113 |
-
|
114 |
-
|
115 |
-
class SDEmb(StableDiffusionXLPipeline):
|
116 |
-
@torch.no_grad()
|
117 |
-
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
118 |
-
def __call__(
|
119 |
-
self,
|
120 |
-
prompt: Union[str, List[str]] = None,
|
121 |
-
prompt_2: Optional[Union[str, List[str]]] = None,
|
122 |
-
height: Optional[int] = None,
|
123 |
-
width: Optional[int] = None,
|
124 |
-
num_inference_steps: int = 50,
|
125 |
-
timesteps: List[int] = None,
|
126 |
-
denoising_end: Optional[float] = None,
|
127 |
-
guidance_scale: float = 5.0,
|
128 |
-
negative_prompt: Optional[Union[str, List[str]]] = None,
|
129 |
-
negative_prompt_2: Optional[Union[str, List[str]]] = None,
|
130 |
-
num_images_per_prompt: Optional[int] = 1,
|
131 |
-
eta: float = 0.0,
|
132 |
-
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
133 |
-
latents: Optional[torch.FloatTensor] = None,
|
134 |
-
prompt_embeds: Optional[torch.FloatTensor] = None,
|
135 |
-
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
136 |
-
pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
137 |
-
negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
138 |
-
ip_adapter_image: Optional[PipelineImageInput] = None,
|
139 |
-
output_type: Optional[str] = "pil",
|
140 |
-
return_dict: bool = True,
|
141 |
-
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
142 |
-
guidance_rescale: float = 0.0,
|
143 |
-
original_size: Optional[Tuple[int, int]] = None,
|
144 |
-
crops_coords_top_left: Tuple[int, int] = (0, 0),
|
145 |
-
target_size: Optional[Tuple[int, int]] = None,
|
146 |
-
negative_original_size: Optional[Tuple[int, int]] = None,
|
147 |
-
negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
|
148 |
-
negative_target_size: Optional[Tuple[int, int]] = None,
|
149 |
-
clip_skip: Optional[int] = None,
|
150 |
-
callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
|
151 |
-
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
152 |
-
ip_adapter_emb=None,
|
153 |
-
**kwargs,
|
154 |
-
):
|
155 |
-
r"""
|
156 |
-
Function invoked when calling the pipeline for generation.
|
157 |
-
|
158 |
-
Args:
|
159 |
-
prompt (`str` or `List[str]`, *optional*):
|
160 |
-
The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
|
161 |
-
instead.
|
162 |
-
prompt_2 (`str` or `List[str]`, *optional*):
|
163 |
-
The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
|
164 |
-
used in both text-encoders
|
165 |
-
height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
166 |
-
The height in pixels of the generated image. This is set to 1024 by default for the best results.
|
167 |
-
Anything below 512 pixels won't work well for
|
168 |
-
[stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
|
169 |
-
and checkpoints that are not specifically fine-tuned on low resolutions.
|
170 |
-
width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
171 |
-
The width in pixels of the generated image. This is set to 1024 by default for the best results.
|
172 |
-
Anything below 512 pixels won't work well for
|
173 |
-
[stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
|
174 |
-
and checkpoints that are not specifically fine-tuned on low resolutions.
|
175 |
-
num_inference_steps (`int`, *optional*, defaults to 50):
|
176 |
-
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
177 |
-
expense of slower inference.
|
178 |
-
timesteps (`List[int]`, *optional*):
|
179 |
-
Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
|
180 |
-
in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
|
181 |
-
passed will be used. Must be in descending order.
|
182 |
-
denoising_end (`float`, *optional*):
|
183 |
-
When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
|
184 |
-
completed before it is intentionally prematurely terminated. As a result, the returned sample will
|
185 |
-
still retain a substantial amount of noise as determined by the discrete timesteps selected by the
|
186 |
-
scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
|
187 |
-
"Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
|
188 |
-
Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)
|
189 |
-
guidance_scale (`float`, *optional*, defaults to 5.0):
|
190 |
-
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
|
191 |
-
`guidance_scale` is defined as `w` of equation 2. of [Imagen
|
192 |
-
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
|
193 |
-
1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
|
194 |
-
usually at the expense of lower image quality.
|
195 |
-
negative_prompt (`str` or `List[str]`, *optional*):
|
196 |
-
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
197 |
-
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
198 |
-
less than `1`).
|
199 |
-
negative_prompt_2 (`str` or `List[str]`, *optional*):
|
200 |
-
The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
|
201 |
-
`text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
|
202 |
-
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
203 |
-
The number of images to generate per prompt.
|
204 |
-
eta (`float`, *optional*, defaults to 0.0):
|
205 |
-
Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
|
206 |
-
[`schedulers.DDIMScheduler`], will be ignored for others.
|
207 |
-
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
208 |
-
One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
|
209 |
-
to make generation deterministic.
|
210 |
-
latents (`torch.FloatTensor`, *optional*):
|
211 |
-
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
|
212 |
-
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
213 |
-
tensor will ge generated by sampling using the supplied random `generator`.
|
214 |
-
prompt_embeds (`torch.FloatTensor`, *optional*):
|
215 |
-
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
216 |
-
provided, text embeddings will be generated from `prompt` input argument.
|
217 |
-
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
218 |
-
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
219 |
-
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
220 |
-
argument.
|
221 |
-
pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
222 |
-
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
223 |
-
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
224 |
-
negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
225 |
-
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
226 |
-
weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
|
227 |
-
input argument.
|
228 |
-
ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
|
229 |
-
output_type (`str`, *optional*, defaults to `"pil"`):
|
230 |
-
The output format of the generate image. Choose between
|
231 |
-
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
|
232 |
-
return_dict (`bool`, *optional*, defaults to `True`):
|
233 |
-
Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
|
234 |
-
of a plain tuple.
|
235 |
-
cross_attention_kwargs (`dict`, *optional*):
|
236 |
-
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
237 |
-
`self.processor` in
|
238 |
-
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
239 |
-
guidance_rescale (`float`, *optional*, defaults to 0.0):
|
240 |
-
Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
|
241 |
-
Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
|
242 |
-
[Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
|
243 |
-
Guidance rescale factor should fix overexposure when using zero terminal SNR.
|
244 |
-
original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
245 |
-
If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
|
246 |
-
`original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
|
247 |
-
explained in section 2.2 of
|
248 |
-
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
249 |
-
crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
|
250 |
-
`crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
|
251 |
-
`crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
|
252 |
-
`crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
|
253 |
-
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
254 |
-
target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
255 |
-
For most cases, `target_size` should be set to the desired height and width of the generated image. If
|
256 |
-
not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
|
257 |
-
section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
258 |
-
negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
259 |
-
To negatively condition the generation process based on a specific image resolution. Part of SDXL's
|
260 |
-
micro-conditioning as explained in section 2.2 of
|
261 |
-
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
|
262 |
-
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
|
263 |
-
negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
|
264 |
-
To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
|
265 |
-
micro-conditioning as explained in section 2.2 of
|
266 |
-
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
|
267 |
-
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
|
268 |
-
negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
269 |
-
To negatively condition the generation process based on a target image resolution. It should be as same
|
270 |
-
as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
|
271 |
-
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
|
272 |
-
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
|
273 |
-
callback_on_step_end (`Callable`, *optional*):
|
274 |
-
A function that calls at the end of each denoising steps during the inference. The function is called
|
275 |
-
with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
|
276 |
-
callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
|
277 |
-
`callback_on_step_end_tensor_inputs`.
|
278 |
-
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
279 |
-
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
280 |
-
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
281 |
-
`._callback_tensor_inputs` attribute of your pipeline class.
|
282 |
-
|
283 |
-
Examples:
|
284 |
-
|
285 |
-
Returns:
|
286 |
-
[`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] or `tuple`:
|
287 |
-
[`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
|
288 |
-
`tuple`. When returning a tuple, the first element is a list with the generated images.
|
289 |
-
"""
|
290 |
-
|
291 |
-
callback = kwargs.pop("callback", None)
|
292 |
-
callback_steps = kwargs.pop("callback_steps", None)
|
293 |
-
|
294 |
-
if callback is not None:
|
295 |
-
deprecate(
|
296 |
-
"callback",
|
297 |
-
"1.0.0",
|
298 |
-
"Passing `callback` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
|
299 |
-
)
|
300 |
-
if callback_steps is not None:
|
301 |
-
deprecate(
|
302 |
-
"callback_steps",
|
303 |
-
"1.0.0",
|
304 |
-
"Passing `callback_steps` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
|
305 |
-
)
|
306 |
-
|
307 |
-
# 0. Default height and width to unet
|
308 |
-
height = height or self.default_sample_size * self.vae_scale_factor
|
309 |
-
width = width or self.default_sample_size * self.vae_scale_factor
|
310 |
-
|
311 |
-
original_size = original_size or (height, width)
|
312 |
-
target_size = target_size or (height, width)
|
313 |
-
|
314 |
-
# 1. Check inputs. Raise error if not correct
|
315 |
-
self.check_inputs(
|
316 |
-
prompt,
|
317 |
-
prompt_2,
|
318 |
-
height,
|
319 |
-
width,
|
320 |
-
callback_steps,
|
321 |
-
negative_prompt,
|
322 |
-
negative_prompt_2,
|
323 |
-
prompt_embeds,
|
324 |
-
negative_prompt_embeds,
|
325 |
-
pooled_prompt_embeds,
|
326 |
-
negative_pooled_prompt_embeds,
|
327 |
-
callback_on_step_end_tensor_inputs,
|
328 |
-
)
|
329 |
-
|
330 |
-
self._guidance_scale = guidance_scale
|
331 |
-
self._guidance_rescale = guidance_rescale
|
332 |
-
self._clip_skip = clip_skip
|
333 |
-
self._cross_attention_kwargs = cross_attention_kwargs
|
334 |
-
self._denoising_end = denoising_end
|
335 |
-
self._interrupt = False
|
336 |
-
|
337 |
-
# 2. Define call parameters
|
338 |
-
if prompt is not None and isinstance(prompt, str):
|
339 |
-
batch_size = 1
|
340 |
-
elif prompt is not None and isinstance(prompt, list):
|
341 |
-
batch_size = len(prompt)
|
342 |
-
else:
|
343 |
-
batch_size = prompt_embeds.shape[0]
|
344 |
-
|
345 |
-
device = self._execution_device
|
346 |
-
|
347 |
-
# 3. Encode input prompt
|
348 |
-
lora_scale = (
|
349 |
-
self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
|
350 |
-
)
|
351 |
-
|
352 |
-
(
|
353 |
-
prompt_embeds,
|
354 |
-
negative_prompt_embeds,
|
355 |
-
pooled_prompt_embeds,
|
356 |
-
negative_pooled_prompt_embeds,
|
357 |
-
) = self.encode_prompt(
|
358 |
-
prompt=prompt,
|
359 |
-
prompt_2=prompt_2,
|
360 |
-
device=device,
|
361 |
-
num_images_per_prompt=num_images_per_prompt,
|
362 |
-
do_classifier_free_guidance=self.do_classifier_free_guidance,
|
363 |
-
negative_prompt=negative_prompt,
|
364 |
-
negative_prompt_2=negative_prompt_2,
|
365 |
-
prompt_embeds=prompt_embeds,
|
366 |
-
negative_prompt_embeds=negative_prompt_embeds,
|
367 |
-
pooled_prompt_embeds=pooled_prompt_embeds,
|
368 |
-
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
369 |
-
lora_scale=lora_scale,
|
370 |
-
clip_skip=self.clip_skip,
|
371 |
-
)
|
372 |
-
|
373 |
-
# 4. Prepare timesteps
|
374 |
-
timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
|
375 |
-
|
376 |
-
# 5. Prepare latent variables
|
377 |
-
num_channels_latents = self.unet.config.in_channels
|
378 |
-
latents = self.prepare_latents(
|
379 |
-
batch_size * num_images_per_prompt,
|
380 |
-
num_channels_latents,
|
381 |
-
height,
|
382 |
-
width,
|
383 |
-
prompt_embeds.dtype,
|
384 |
-
device,
|
385 |
-
generator,
|
386 |
-
latents,
|
387 |
-
)
|
388 |
-
|
389 |
-
# 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
390 |
-
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
391 |
-
|
392 |
-
# 7. Prepare added time ids & embeddings
|
393 |
-
add_text_embeds = pooled_prompt_embeds
|
394 |
-
if self.text_encoder_2 is None:
|
395 |
-
text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
|
396 |
-
else:
|
397 |
-
text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
|
398 |
-
|
399 |
-
add_time_ids = self._get_add_time_ids(
|
400 |
-
original_size,
|
401 |
-
crops_coords_top_left,
|
402 |
-
target_size,
|
403 |
-
dtype=prompt_embeds.dtype,
|
404 |
-
text_encoder_projection_dim=text_encoder_projection_dim,
|
405 |
-
)
|
406 |
-
if negative_original_size is not None and negative_target_size is not None:
|
407 |
-
negative_add_time_ids = self._get_add_time_ids(
|
408 |
-
negative_original_size,
|
409 |
-
negative_crops_coords_top_left,
|
410 |
-
negative_target_size,
|
411 |
-
dtype=prompt_embeds.dtype,
|
412 |
-
text_encoder_projection_dim=text_encoder_projection_dim,
|
413 |
-
)
|
414 |
-
else:
|
415 |
-
negative_add_time_ids = add_time_ids
|
416 |
-
|
417 |
-
if self.do_classifier_free_guidance:
|
418 |
-
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
|
419 |
-
add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
|
420 |
-
add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
|
421 |
-
|
422 |
-
prompt_embeds = prompt_embeds.to(device)
|
423 |
-
add_text_embeds = add_text_embeds.to(device)
|
424 |
-
add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
|
425 |
-
|
426 |
-
if ip_adapter_emb is not None:
|
427 |
-
image_embeds = ip_adapter_emb
|
428 |
-
|
429 |
-
elif ip_adapter_image is not None:
|
430 |
-
output_hidden_state = False if isinstance(self.unet.encoder_hid_proj, ImageProjection) else True
|
431 |
-
image_embeds, negative_image_embeds = self.encode_image(
|
432 |
-
ip_adapter_image, device, num_images_per_prompt, output_hidden_state
|
433 |
-
)
|
434 |
-
if self.do_classifier_free_guidance:
|
435 |
-
image_embeds = torch.cat([negative_image_embeds, image_embeds])
|
436 |
-
|
437 |
-
# 8. Denoising loop
|
438 |
-
num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
|
439 |
-
|
440 |
-
# 8.1 Apply denoising_end
|
441 |
-
if (
|
442 |
-
self.denoising_end is not None
|
443 |
-
and isinstance(self.denoising_end, float)
|
444 |
-
and self.denoising_end > 0
|
445 |
-
and self.denoising_end < 1
|
446 |
-
):
|
447 |
-
discrete_timestep_cutoff = int(
|
448 |
-
round(
|
449 |
-
self.scheduler.config.num_train_timesteps
|
450 |
-
- (self.denoising_end * self.scheduler.config.num_train_timesteps)
|
451 |
-
)
|
452 |
-
)
|
453 |
-
num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
|
454 |
-
timesteps = timesteps[:num_inference_steps]
|
455 |
-
|
456 |
-
# 9. Optionally get Guidance Scale Embedding
|
457 |
-
timestep_cond = None
|
458 |
-
if self.unet.config.time_cond_proj_dim is not None:
|
459 |
-
guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
|
460 |
-
timestep_cond = self.get_guidance_scale_embedding(
|
461 |
-
guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
|
462 |
-
).to(device=device, dtype=latents.dtype)
|
463 |
-
|
464 |
-
self._num_timesteps = len(timesteps)
|
465 |
-
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
466 |
-
for i, t in enumerate(timesteps):
|
467 |
-
if self.interrupt:
|
468 |
-
continue
|
469 |
-
|
470 |
-
# expand the latents if we are doing classifier free guidance
|
471 |
-
latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
|
472 |
-
|
473 |
-
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
474 |
-
|
475 |
-
# predict the noise residual
|
476 |
-
added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
|
477 |
-
if ip_adapter_image is not None or ip_adapter_emb is not None:
|
478 |
-
added_cond_kwargs["image_embeds"] = image_embeds
|
479 |
-
noise_pred = self.unet(
|
480 |
-
latent_model_input,
|
481 |
-
t,
|
482 |
-
encoder_hidden_states=prompt_embeds,
|
483 |
-
timestep_cond=timestep_cond,
|
484 |
-
cross_attention_kwargs=self.cross_attention_kwargs,
|
485 |
-
added_cond_kwargs=added_cond_kwargs,
|
486 |
-
return_dict=False,
|
487 |
-
)[0]
|
488 |
-
|
489 |
-
# perform guidance
|
490 |
-
if self.do_classifier_free_guidance:
|
491 |
-
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
492 |
-
noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
|
493 |
-
|
494 |
-
if self.do_classifier_free_guidance and self.guidance_rescale > 0.0:
|
495 |
-
# Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
|
496 |
-
noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale)
|
497 |
-
|
498 |
-
# compute the previous noisy sample x_t -> x_t-1
|
499 |
-
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
|
500 |
-
|
501 |
-
if callback_on_step_end is not None:
|
502 |
-
callback_kwargs = {}
|
503 |
-
for k in callback_on_step_end_tensor_inputs:
|
504 |
-
callback_kwargs[k] = locals()[k]
|
505 |
-
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
506 |
-
|
507 |
-
latents = callback_outputs.pop("latents", latents)
|
508 |
-
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
509 |
-
negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
|
510 |
-
add_text_embeds = callback_outputs.pop("add_text_embeds", add_text_embeds)
|
511 |
-
negative_pooled_prompt_embeds = callback_outputs.pop(
|
512 |
-
"negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
|
513 |
-
)
|
514 |
-
add_time_ids = callback_outputs.pop("add_time_ids", add_time_ids)
|
515 |
-
negative_add_time_ids = callback_outputs.pop("negative_add_time_ids", negative_add_time_ids)
|
516 |
-
|
517 |
-
# call the callback, if provided
|
518 |
-
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
519 |
-
progress_bar.update()
|
520 |
-
if callback is not None and i % callback_steps == 0:
|
521 |
-
step_idx = i // getattr(self.scheduler, "order", 1)
|
522 |
-
callback(step_idx, t, latents)
|
523 |
-
|
524 |
-
# if XLA_AVAILABLE:
|
525 |
-
# xm.mark_step()
|
526 |
-
|
527 |
-
if not output_type == "latent":
|
528 |
-
# make sure the VAE is in float32 mode, as it overflows in float16
|
529 |
-
needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
|
530 |
-
|
531 |
-
if needs_upcasting:
|
532 |
-
self.upcast_vae()
|
533 |
-
latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
|
534 |
-
|
535 |
-
image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
|
536 |
-
|
537 |
-
# cast back to fp16 if needed
|
538 |
-
if needs_upcasting:
|
539 |
-
self.vae.to(dtype=torch.float16)
|
540 |
-
else:
|
541 |
-
image = latents
|
542 |
-
|
543 |
-
if not output_type == "latent":
|
544 |
-
# apply watermark if available
|
545 |
-
if self.watermark is not None:
|
546 |
-
image = self.watermark.apply_watermark(image)
|
547 |
-
image = self.image_processor.postprocess(image, output_type=output_type)
|
548 |
-
#maybe_nsfw = any(check_nsfw_images(image))
|
549 |
-
#if maybe_nsfw:
|
550 |
-
# print('This image could be NSFW so we return a blank image.')
|
551 |
-
# return StableDiffusionXLPipelineOutput(images=[Image.new('RGB', (1024, 1024))])
|
552 |
-
|
553 |
-
# Offload all models
|
554 |
-
self.maybe_free_model_hooks()
|
555 |
-
|
556 |
-
if not return_dict:
|
557 |
-
return (image,)
|
558 |
-
|
559 |
-
return StableDiffusionXLPipelineOutput(images=image)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|