-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
351 lines (281 loc) · 10.4 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
#!/usr/bin/env python
import json
import os
import subprocess
import tempfile
import threading
import time
from os import path
from pathlib import Path
from shutil import rmtree
from typing import List, TypeVar, Dict
import gradio as gr
from convert import convert_lora_file_to_safetensors
TITLE = "DreamBooth LoRA WebUI"
working_dir = path.dirname(__file__)
cache_file = path.join(working_dir, "config.cache.json")
FIELDS = []
T = TypeVar("T")
def save_config_cache(data):
with open(cache_file, 'w') as f:
json.dump(data, f)
def load_config_cache() -> dict:
if not path.exists(cache_file):
return {}
with open(cache_file) as f:
return json.load(f)
def register_input(name, block: T) -> T:
FIELDS.append({
'name': name,
'block': block,
})
return block
def extract_field_names() -> List[str]:
return [item['name'] for item in FIELDS]
def extract_fields() -> List[any]:
return [item['block'] for item in FIELDS]
def extract_field_values(*args) -> Dict[str, any]:
names = extract_field_names()
return {name: args[idx] for idx, name in enumerate(names)}
def create_textbox(name: str, **kwargs) -> gr.Textbox:
kwargs['label'] = name.replace('_', ' ').capitalize()
if 'max_lines' not in kwargs:
kwargs['max_lines'] = 1
if 'interactive' not in kwargs:
kwargs['interactive'] = True
return register_input(name, gr.Textbox(**kwargs))
def create_files(name: str, **kwargs) -> gr.Files:
kwargs['label'] = name.replace('_', ' ').capitalize()
if 'interactive' not in kwargs:
kwargs['interactive'] = True
return register_input(name, gr.Files(**kwargs))
def create_radio(name: str, choices: List[str], **kwargs) -> gr.Radio:
kwargs['label'] = name.replace('_', ' ').capitalize()
if 'choices' not in kwargs:
kwargs['choices'] = choices
if 'interactive' not in kwargs:
kwargs['interactive'] = True
return register_input(name, gr.Radio(**kwargs))
def create_checkbox(name: str, value: bool, **kwargs) -> gr.Checkbox:
kwargs['label'] = name.replace('_', ' ').capitalize()
if 'interactive' not in kwargs:
kwargs['interactive'] = True
if 'value' not in kwargs:
kwargs['value'] = value
return register_input(name, gr.Checkbox(**kwargs))
def create_number(name: str, value: any, **kwargs) -> gr.Number:
kwargs['label'] = name.replace('_', ' ').capitalize()
if 'value' not in kwargs:
kwargs['value'] = value
if 'interactive' not in kwargs:
kwargs['interactive'] = True
return register_input(name, gr.Number(**kwargs))
def wrap_vargs_method_with_progress(m: str, num: int):
args = ''.join([f'v{i}, ' for i in range(1, num + 1)])
exec(f"""
def wrapped_method({args}progress=gr.Progress()):
return {m}({args}progress=progress)
""")
return locals().get('wrapped_method')
def do_load():
data = load_config_cache()
ret = []
for item in FIELDS:
if item['name'] in data:
ret.append(data[item['name']])
else:
ret.append(item['block'].value)
return ret
def do_train(*args, progress=gr.Progress()):
arg_train = [
"accelerate",
"launch",
path.join(path.dirname(__file__), "scripts", "train_dreambooth_lora.py")
]
values = extract_field_values(*args)
save_config_cache(values)
for key, val in values.items():
if val:
if val is True:
arg_train.append('--' + key)
else:
arg_train.append('--' + key)
arg_train.append(str(val))
else:
if val == 0 and val is not False:
arg_train.append('--' + key)
arg_train.append(str(val))
prg_path = tempfile.mktemp(suffix="train_dreambooth_lora.progress")
os.mkfifo(prg_path)
arg_train.append("--progress_file")
arg_train.append(prg_path)
def show_progress(_prg_path, _progress):
p = Path(_prg_path)
while True:
content = p.read_text().strip()
if content == 'done':
return
v_p, v_desc = content.split(',', 2)
_progress(float(v_p.strip()) * 0.9, v_desc.strip())
progress(0, "Starting")
threading.Thread(target=show_progress, args=(prg_path, progress)).start()
try:
subprocess.run(arg_train, check=True)
except subprocess.CalledProcessError as e:
return str(e)
finally:
Path(prg_path).write_text('done')
os.remove(prg_path)
progress(0.9, "Converting to .safetensors")
convert_input = path.join(values['output_dir'], 'pytorch_lora_weights.bin')
convert_output = path.join(values['output_dir'], 'lora.safetensors')
convert_lora_file_to_safetensors(convert_input, convert_output)
return f'\n\nCompleted:\n\n{convert_output}'
def create_training():
with gr.Row():
with gr.Column():
with gr.Box():
gr.Markdown('**Input**')
create_textbox(
'instance_data_dir',
value=path.join(working_dir, "src"),
)
create_textbox(
'instance_prompt',
value='a photo of guoyk',
)
gr.Markdown(
'''
- Upload images or specify a path of instance images
- For an instance prompt, use a unique, made up word to avoid collisions.
'''
)
with gr.Box():
gr.Markdown('Output')
create_textbox(
'output_dir',
value=path.join(working_dir, "out")
)
create_textbox(
'validation_prompt',
value='a photo of guoyk in red dress',
)
with gr.Row():
create_number(
'num_validation_images', 4,
precision=0,
)
create_number(
"validation_epochs", 50,
precision=0,
)
with gr.Box():
with gr.Row():
button_start = gr.Button("Start")
with gr.Box():
gr.Markdown('Output message')
with gr.Box():
output_message = gr.Markdown()
with gr.Column():
with gr.Box():
with gr.Row():
gr.Markdown("**🛠 Model & Loading**")
with gr.Row():
create_textbox(
'pretrained_model_name_or_path',
value='runwayml/stable-diffusion-v1-5'
)
create_textbox('revision')
with gr.Row():
create_radio(
'resolution', ['512', '768'],
value='512'
)
create_checkbox('center_crop', False)
with gr.Row():
create_number(
'train_batch_size', 1,
precision=0,
)
create_number(
'gradient_accumulation_steps', 1,
precision=0,
)
create_number(
'dataloader_num_workers', 0,
precision=0,
)
with gr.Row():
gr.Markdown("**🛠 Learning Rate & Steps**")
with gr.Row():
with gr.Column():
create_radio(
'lr_scheduler',
["linear", "cosine", "cosine_with_restarts", "polynomial", "constant",
"constant_with_warmup"],
value='constant',
)
with gr.Column():
create_number(
'lr_num_cycles', 1,
precision=0,
)
create_number(
'lr_power', 1
)
with gr.Row():
create_number(
'max_train_steps', 1000,
precision=0,
)
create_number(
'learning_rate', 0.0001
)
create_number(
'lr_warmup_steps', 200,
precision=0,
)
with gr.Row():
gr.Markdown("**🛠 Checkpointing & Seed**")
with gr.Row():
with gr.Column():
create_number(
'checkpointing_steps', 100,
precision=0,
)
create_textbox('resume_from_checkpoint')
with gr.Column():
create_number(
'seed', 0,
precision=0,
)
with gr.Row():
gr.Markdown("**🛠 Precision**")
with gr.Row():
with gr.Column():
create_radio('mixed_precision', ['no', 'fp16', 'bf16'], value="fp16")
create_radio('prior_generation_precision', ['no', 'fp32', 'fp16', 'bf16'], value="fp16")
with gr.Column():
create_checkbox('use_8bit_adam', False)
create_checkbox('enable_xformers_memory_efficient_attention', True)
button_start.click(
fn=wrap_vargs_method_with_progress('do_train', len(FIELDS)),
inputs=extract_fields(),
outputs=output_message
)
def create_app() -> gr.Blocks:
with gr.Blocks(
title=TITLE,
css=path.join(path.dirname(__file__), 'style.css'),
) as app:
with gr.Row():
with gr.Column():
gr.Markdown(f'**{TITLE}**')
create_training()
app.load(fn=do_load, outputs=extract_fields())
return app
def main():
app = create_app()
app.queue(max_size=1).launch(share=True)
if __name__ == "__main__":
main()