forked from bmaltais/kohya_ss
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon_gui.py
1232 lines (1063 loc) · 40.2 KB
/
common_gui.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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from tkinter import filedialog, Tk
from easygui import msgbox
import os
import gradio as gr
import easygui
import shutil
import sys
folder_symbol = '\U0001f4c2' # 📂
refresh_symbol = '\U0001f504' # 🔄
save_style_symbol = '\U0001f4be' # 💾
document_symbol = '\U0001F4C4' # 📄
# define a list of substrings to search for v2 base models
V2_BASE_MODELS = [
'stabilityai/stable-diffusion-2-1-base',
'stabilityai/stable-diffusion-2-base',
]
# define a list of substrings to search for v_parameterization models
V_PARAMETERIZATION_MODELS = [
'stabilityai/stable-diffusion-2-1',
'stabilityai/stable-diffusion-2',
]
# define a list of substrings to v1.x models
V1_MODELS = [
'CompVis/stable-diffusion-v1-4',
'runwayml/stable-diffusion-v1-5',
]
# define a list of substrings to search for
ALL_PRESET_MODELS = V2_BASE_MODELS + V_PARAMETERIZATION_MODELS + V1_MODELS
ENV_EXCLUSION = ['COLAB_GPU', 'RUNPOD_POD_ID']
def check_if_model_exist(
output_name, output_dir, save_model_as, headless=False
):
if headless:
print(
'Headless mode, skipping verification if model already exist... if model already exist it will be overwritten...'
)
return False
if save_model_as in ['diffusers', 'diffusers_safetendors']:
ckpt_folder = os.path.join(output_dir, output_name)
if os.path.isdir(ckpt_folder):
msg = f'A diffuser model with the same name {ckpt_folder} already exists. Do you want to overwrite it?'
if not easygui.ynbox(msg, 'Overwrite Existing Model?'):
print(
'Aborting training due to existing model with same name...'
)
return True
elif save_model_as in ['ckpt', 'safetensors']:
ckpt_file = os.path.join(output_dir, output_name + '.' + save_model_as)
if os.path.isfile(ckpt_file):
msg = f'A model with the same file name {ckpt_file} already exists. Do you want to overwrite it?'
if not easygui.ynbox(msg, 'Overwrite Existing Model?'):
print(
'Aborting training due to existing model with same name...'
)
return True
else:
print(
'Can\'t verify if existing model exist when save model is set a "same as source model", continuing to train model...'
)
return False
return False
def output_message(msg='', title='', headless=False):
if headless:
print(msg)
else:
msgbox(msg=msg, title=title)
def update_my_data(my_data):
# Update the optimizer based on the use_8bit_adam flag
use_8bit_adam = my_data.get('use_8bit_adam', False)
my_data.setdefault('optimizer', 'AdamW8bit' if use_8bit_adam else 'AdamW')
# Update model_list to custom if empty or pretrained_model_name_or_path is not a preset model
model_list = my_data.get('model_list', [])
pretrained_model_name_or_path = my_data.get(
'pretrained_model_name_or_path', ''
)
if (
not model_list
or pretrained_model_name_or_path not in ALL_PRESET_MODELS
):
my_data['model_list'] = 'custom'
# Convert values to int if they are strings
for key in ['epoch', 'save_every_n_epochs', 'lr_warmup']:
value = my_data.get(key, 0)
if isinstance(value, str) and value.strip().isdigit():
my_data[key] = int(value)
elif not value:
my_data[key] = 0
# Convert values to float if they are strings
for key in ['noise_offset', 'learning_rate', 'text_encoder_lr', 'unet_lr']:
value = my_data.get(key, 0)
if isinstance(value, str) and value.strip().isdigit():
my_data[key] = float(value)
elif not value:
my_data[key] = 0
# Update LoRA_type if it is set to LoCon
if my_data.get('LoRA_type', 'Standard') == 'LoCon':
my_data['LoRA_type'] = 'LyCORIS/LoCon'
# Update model save choices due to changes for LoRA and TI training
if (
my_data.get('LoRA_type') or my_data.get('num_vectors_per_token')
) and my_data.get('save_model_as') not in ['safetensors', 'ckpt']:
message = 'Updating save_model_as to safetensors because the current value in the config file is no longer applicable to {}'
if my_data.get('LoRA_type'):
print(message.format('LoRA'))
if my_data.get('num_vectors_per_token'):
print(message.format('TI'))
my_data['save_model_as'] = 'safetensors'
return my_data
def get_dir_and_file(file_path):
dir_path, file_name = os.path.split(file_path)
return (dir_path, file_name)
# def has_ext_files(directory, extension):
# # Iterate through all the files in the directory
# for file in os.listdir(directory):
# # If the file name ends with extension, return True
# if file.endswith(extension):
# return True
# # If no extension files were found, return False
# return False
def get_file_path(
file_path='', default_extension='.json', extension_name='Config files'
):
if (
not any(var in os.environ for var in ENV_EXCLUSION)
and sys.platform != 'darwin'
):
current_file_path = file_path
# print(f'current file path: {current_file_path}')
initial_dir, initial_file = get_dir_and_file(file_path)
# Create a hidden Tkinter root window
root = Tk()
root.wm_attributes('-topmost', 1)
root.withdraw()
# Show the open file dialog and get the selected file path
file_path = filedialog.askopenfilename(
filetypes=(
(extension_name, f'*{default_extension}'),
('All files', '*.*'),
),
defaultextension=default_extension,
initialfile=initial_file,
initialdir=initial_dir,
)
# Destroy the hidden root window
root.destroy()
# If no file is selected, use the current file path
if not file_path:
file_path = current_file_path
current_file_path = file_path
# print(f'current file path: {current_file_path}')
return file_path
def get_any_file_path(file_path=''):
if (
not any(var in os.environ for var in ENV_EXCLUSION)
and sys.platform != 'darwin'
):
current_file_path = file_path
# print(f'current file path: {current_file_path}')
initial_dir, initial_file = get_dir_and_file(file_path)
root = Tk()
root.wm_attributes('-topmost', 1)
root.withdraw()
file_path = filedialog.askopenfilename(
initialdir=initial_dir,
initialfile=initial_file,
)
root.destroy()
if file_path == '':
file_path = current_file_path
return file_path
def remove_doublequote(file_path):
if file_path != None:
file_path = file_path.replace('"', '')
return file_path
# def set_legacy_8bitadam(optimizer, use_8bit_adam):
# if optimizer == 'AdamW8bit':
# # use_8bit_adam = True
# return gr.Dropdown.update(value=optimizer), gr.Checkbox.update(
# value=True, interactive=False, visible=True
# )
# else:
# # use_8bit_adam = False
# return gr.Dropdown.update(value=optimizer), gr.Checkbox.update(
# value=False, interactive=False, visible=True
# )
def get_folder_path(folder_path=''):
if (
not any(var in os.environ for var in ENV_EXCLUSION)
and sys.platform != 'darwin'
):
current_folder_path = folder_path
initial_dir, initial_file = get_dir_and_file(folder_path)
root = Tk()
root.wm_attributes('-topmost', 1)
root.withdraw()
folder_path = filedialog.askdirectory(initialdir=initial_dir)
root.destroy()
if folder_path == '':
folder_path = current_folder_path
return folder_path
def get_saveasfile_path(
file_path='', defaultextension='.json', extension_name='Config files'
):
if (
not any(var in os.environ for var in ENV_EXCLUSION)
and sys.platform != 'darwin'
):
current_file_path = file_path
# print(f'current file path: {current_file_path}')
initial_dir, initial_file = get_dir_and_file(file_path)
root = Tk()
root.wm_attributes('-topmost', 1)
root.withdraw()
save_file_path = filedialog.asksaveasfile(
filetypes=(
(f'{extension_name}', f'{defaultextension}'),
('All files', '*'),
),
defaultextension=defaultextension,
initialdir=initial_dir,
initialfile=initial_file,
)
root.destroy()
# print(save_file_path)
if save_file_path == None:
file_path = current_file_path
else:
print(save_file_path.name)
file_path = save_file_path.name
# print(file_path)
return file_path
def get_saveasfilename_path(
file_path='', extensions='*', extension_name='Config files'
):
if (
not any(var in os.environ for var in ENV_EXCLUSION)
and sys.platform != 'darwin'
):
current_file_path = file_path
# print(f'current file path: {current_file_path}')
initial_dir, initial_file = get_dir_and_file(file_path)
root = Tk()
root.wm_attributes('-topmost', 1)
root.withdraw()
save_file_path = filedialog.asksaveasfilename(
filetypes=(
(f'{extension_name}', f'{extensions}'),
('All files', '*'),
),
defaultextension=extensions,
initialdir=initial_dir,
initialfile=initial_file,
)
root.destroy()
if save_file_path == '':
file_path = current_file_path
else:
# print(save_file_path)
file_path = save_file_path
return file_path
def add_pre_postfix(
folder: str = '',
prefix: str = '',
postfix: str = '',
caption_file_ext: str = '.caption',
) -> None:
"""
Add prefix and/or postfix to the content of caption files within a folder.
If no caption files are found, create one with the requested prefix and/or postfix.
Args:
folder (str): Path to the folder containing caption files.
prefix (str, optional): Prefix to add to the content of the caption files.
postfix (str, optional): Postfix to add to the content of the caption files.
caption_file_ext (str, optional): Extension of the caption files.
"""
if prefix == '' and postfix == '':
return
image_extensions = ('.jpg', '.jpeg', '.png', '.webp')
image_files = [
f for f in os.listdir(folder) if f.lower().endswith(image_extensions)
]
for image_file in image_files:
caption_file_name = os.path.splitext(image_file)[0] + caption_file_ext
caption_file_path = os.path.join(folder, caption_file_name)
if not os.path.exists(caption_file_path):
with open(caption_file_path, 'w', encoding='utf8') as f:
separator = ' ' if prefix and postfix else ''
f.write(f'{prefix}{separator}{postfix}')
else:
with open(caption_file_path, 'r+', encoding='utf8') as f:
content = f.read()
content = content.rstrip()
f.seek(0, 0)
prefix_separator = ' ' if prefix else ''
postfix_separator = ' ' if postfix else ''
f.write(
f'{prefix}{prefix_separator}{content}{postfix_separator}{postfix}'
)
def has_ext_files(folder_path: str, file_extension: str) -> bool:
"""
Check if there are any files with the specified extension in the given folder.
Args:
folder_path (str): Path to the folder containing files.
file_extension (str): Extension of the files to look for.
Returns:
bool: True if files with the specified extension are found, False otherwise.
"""
for file in os.listdir(folder_path):
if file.endswith(file_extension):
return True
return False
def find_replace(
folder_path: str = '',
caption_file_ext: str = '.caption',
search_text: str = '',
replace_text: str = '',
) -> None:
"""
Find and replace text in caption files within a folder.
Args:
folder_path (str, optional): Path to the folder containing caption files.
caption_file_ext (str, optional): Extension of the caption files.
search_text (str, optional): Text to search for in the caption files.
replace_text (str, optional): Text to replace the search text with.
"""
print('Running caption find/replace')
if not has_ext_files(folder_path, caption_file_ext):
msgbox(
f'No files with extension {caption_file_ext} were found in {folder_path}...'
)
return
if search_text == '':
return
caption_files = [
f for f in os.listdir(folder_path) if f.endswith(caption_file_ext)
]
for caption_file in caption_files:
with open(
os.path.join(folder_path, caption_file), 'r', errors='ignore'
) as f:
content = f.read()
content = content.replace(search_text, replace_text)
with open(os.path.join(folder_path, caption_file), 'w') as f:
f.write(content)
def color_aug_changed(color_aug):
if color_aug:
msgbox(
'Disabling "Cache latent" because "Color augmentation" has been selected...'
)
return gr.Checkbox.update(value=False, interactive=False)
else:
return gr.Checkbox.update(value=True, interactive=True)
def save_inference_file(output_dir, v2, v_parameterization, output_name):
# List all files in the directory
files = os.listdir(output_dir)
# Iterate over the list of files
for file in files:
# Check if the file starts with the value of output_name
if file.startswith(output_name):
# Check if it is a file or a directory
if os.path.isfile(os.path.join(output_dir, file)):
# Split the file name and extension
file_name, ext = os.path.splitext(file)
# Copy the v2-inference-v.yaml file to the current file, with a .yaml extension
if v2 and v_parameterization:
print(
f'Saving v2-inference-v.yaml as {output_dir}/{file_name}.yaml'
)
shutil.copy(
f'./v2_inference/v2-inference-v.yaml',
f'{output_dir}/{file_name}.yaml',
)
elif v2:
print(
f'Saving v2-inference.yaml as {output_dir}/{file_name}.yaml'
)
shutil.copy(
f'./v2_inference/v2-inference.yaml',
f'{output_dir}/{file_name}.yaml',
)
def set_pretrained_model_name_or_path_input(
model_list, pretrained_model_name_or_path, v2, v_parameterization
):
# check if $v2 and $v_parameterization are empty and if $pretrained_model_name_or_path contains any of the substrings in the v2 list
if str(model_list) in V2_BASE_MODELS:
print('SD v2 model detected. Setting --v2 parameter')
v2 = True
v_parameterization = False
pretrained_model_name_or_path = str(model_list)
# check if $v2 and $v_parameterization are empty and if $pretrained_model_name_or_path contains any of the substrings in the v_parameterization list
if str(model_list) in V_PARAMETERIZATION_MODELS:
print(
'SD v2 v_parameterization detected. Setting --v2 parameter and --v_parameterization'
)
v2 = True
v_parameterization = True
pretrained_model_name_or_path = str(model_list)
if str(model_list) in V1_MODELS:
v2 = False
v_parameterization = False
pretrained_model_name_or_path = str(model_list)
if model_list == 'custom':
if (
str(pretrained_model_name_or_path) in V1_MODELS
or str(pretrained_model_name_or_path) in V2_BASE_MODELS
or str(pretrained_model_name_or_path) in V_PARAMETERIZATION_MODELS
):
pretrained_model_name_or_path = ''
v2 = False
v_parameterization = False
return model_list, pretrained_model_name_or_path, v2, v_parameterization
def set_v2_checkbox(model_list, v2, v_parameterization):
# check if $v2 and $v_parameterization are empty and if $pretrained_model_name_or_path contains any of the substrings in the v2 list
if str(model_list) in V2_BASE_MODELS:
v2 = True
v_parameterization = False
# check if $v2 and $v_parameterization are empty and if $pretrained_model_name_or_path contains any of the substrings in the v_parameterization list
if str(model_list) in V_PARAMETERIZATION_MODELS:
v2 = True
v_parameterization = True
if str(model_list) in V1_MODELS:
v2 = False
v_parameterization = False
return v2, v_parameterization
def set_model_list(
model_list,
pretrained_model_name_or_path,
v2,
v_parameterization,
):
if not pretrained_model_name_or_path in ALL_PRESET_MODELS:
model_list = 'custom'
else:
model_list = pretrained_model_name_or_path
return model_list, v2, v_parameterization
###
### Gradio common GUI section
###
def gradio_config(headless=False):
with gr.Accordion('Configuration file', open=False):
with gr.Row():
button_open_config = gr.Button(
'Open 📂', elem_id='open_folder', visible=(not headless)
)
button_save_config = gr.Button(
'Save 💾', elem_id='open_folder', visible=(not headless)
)
button_save_as_config = gr.Button(
'Save as... 💾', elem_id='open_folder', visible=(not headless)
)
config_file_name = gr.Textbox(
label='',
placeholder="type the configuration file path or use the 'Open' button above to select it...",
interactive=True,
)
button_load_config = gr.Button('Load 💾', elem_id='open_folder')
config_file_name.change(
remove_doublequote,
inputs=[config_file_name],
outputs=[config_file_name],
)
return (
button_open_config,
button_save_config,
button_save_as_config,
config_file_name,
button_load_config,
)
def get_pretrained_model_name_or_path_file(
model_list, pretrained_model_name_or_path
):
pretrained_model_name_or_path = get_any_file_path(
pretrained_model_name_or_path
)
set_model_list(model_list, pretrained_model_name_or_path)
def gradio_source_model(
save_model_as_choices=[
'same as source model',
'ckpt',
'diffusers',
'diffusers_safetensors',
'safetensors',
],
headless=False,
):
with gr.Tab('Source model'):
# Define the input elements
with gr.Row():
pretrained_model_name_or_path = gr.Textbox(
label='Pretrained model name or path',
placeholder='enter the path to custom model or name of pretrained model',
value='runwayml/stable-diffusion-v1-5',
)
pretrained_model_name_or_path_file = gr.Button(
document_symbol,
elem_id='open_folder_small',
visible=(not headless),
)
pretrained_model_name_or_path_file.click(
get_any_file_path,
inputs=pretrained_model_name_or_path,
outputs=pretrained_model_name_or_path,
show_progress=False,
)
pretrained_model_name_or_path_folder = gr.Button(
folder_symbol,
elem_id='open_folder_small',
visible=(not headless),
)
pretrained_model_name_or_path_folder.click(
get_folder_path,
inputs=pretrained_model_name_or_path,
outputs=pretrained_model_name_or_path,
show_progress=False,
)
model_list = gr.Dropdown(
label='Model Quick Pick',
choices=[
'custom',
'stabilityai/stable-diffusion-2-1-base',
'stabilityai/stable-diffusion-2-base',
'stabilityai/stable-diffusion-2-1',
'stabilityai/stable-diffusion-2',
'runwayml/stable-diffusion-v1-5',
'CompVis/stable-diffusion-v1-4',
],
value='runwayml/stable-diffusion-v1-5',
)
save_model_as = gr.Dropdown(
label='Save trained model as',
choices=save_model_as_choices,
value='safetensors',
)
with gr.Row():
v2 = gr.Checkbox(label='v2', value=False)
v_parameterization = gr.Checkbox(
label='v_parameterization', value=False
)
v2.change(
set_v2_checkbox,
inputs=[model_list, v2, v_parameterization],
outputs=[v2, v_parameterization],
show_progress=False,
)
v_parameterization.change(
set_v2_checkbox,
inputs=[model_list, v2, v_parameterization],
outputs=[v2, v_parameterization],
show_progress=False,
)
model_list.change(
set_pretrained_model_name_or_path_input,
inputs=[
model_list,
pretrained_model_name_or_path,
v2,
v_parameterization,
],
outputs=[
model_list,
pretrained_model_name_or_path,
v2,
v_parameterization,
],
show_progress=False,
)
# Update the model list and parameters when user click outside the button or field
pretrained_model_name_or_path.change(
set_model_list,
inputs=[
model_list,
pretrained_model_name_or_path,
v2,
v_parameterization,
],
outputs=[
model_list,
v2,
v_parameterization,
],
show_progress=False,
)
return (
pretrained_model_name_or_path,
v2,
v_parameterization,
save_model_as,
model_list,
)
def gradio_training(
learning_rate_value='1e-6',
lr_scheduler_value='constant',
lr_warmup_value='0',
):
with gr.Row():
train_batch_size = gr.Slider(
minimum=1,
maximum=64,
label='Train batch size',
value=1,
step=1,
)
epoch = gr.Number(label='Epoch', value=1, precision=0)
save_every_n_epochs = gr.Number(
label='Save every N epochs', value=1, precision=0
)
caption_extension = gr.Textbox(
label='Caption Extension',
placeholder='(Optional) Extension for caption files. default: .caption',
)
with gr.Row():
mixed_precision = gr.Dropdown(
label='Mixed precision',
choices=[
'no',
'fp16',
'bf16',
],
value='fp16',
)
save_precision = gr.Dropdown(
label='Save precision',
choices=[
'float',
'fp16',
'bf16',
],
value='fp16',
)
num_cpu_threads_per_process = gr.Slider(
minimum=1,
maximum=os.cpu_count(),
step=1,
label='Number of CPU threads per core',
value=2,
)
seed = gr.Textbox(label='Seed', placeholder='(Optional) eg:1234')
cache_latents = gr.Checkbox(label='Cache latents', value=True)
cache_latents_to_disk = gr.Checkbox(
label='Cache latents to disk', value=False
)
with gr.Row():
learning_rate = gr.Number(
label='Learning rate', value=learning_rate_value
)
lr_scheduler = gr.Dropdown(
label='LR Scheduler',
choices=[
'adafactor',
'constant',
'constant_with_warmup',
'cosine',
'cosine_with_restarts',
'linear',
'polynomial',
],
value=lr_scheduler_value,
)
lr_warmup = gr.Slider(
label='LR warmup (% of steps)',
value=lr_warmup_value,
minimum=0,
maximum=100,
step=1,
)
optimizer = gr.Dropdown(
label='Optimizer',
choices=[
'AdamW',
'AdamW8bit',
'Adafactor',
'DAdaptation',
'DAdaptAdaGrad',
'DAdaptAdan',
'DAdaptSGD',
'Lion',
'Lion8bit',
'SGDNesterov',
'SGDNesterov8bit',
],
value='AdamW8bit',
interactive=True,
)
with gr.Row():
optimizer_args = gr.Textbox(
label='Optimizer extra arguments',
placeholder='(Optional) eg: relative_step=True scale_parameter=True warmup_init=True',
)
return (
learning_rate,
lr_scheduler,
lr_warmup,
train_batch_size,
epoch,
save_every_n_epochs,
mixed_precision,
save_precision,
num_cpu_threads_per_process,
seed,
caption_extension,
cache_latents,
cache_latents_to_disk,
optimizer,
optimizer_args,
)
def run_cmd_training(**kwargs):
run_cmd = ''
learning_rate = kwargs.get("learning_rate", "")
if learning_rate:
run_cmd += f' --learning_rate="{learning_rate}"'
lr_scheduler = kwargs.get("lr_scheduler", "")
if lr_scheduler:
run_cmd += f' --lr_scheduler="{lr_scheduler}"'
lr_warmup_steps = kwargs.get("lr_warmup_steps", "")
if lr_warmup_steps:
if lr_scheduler == 'constant':
print('Can\'t use LR warmup with LR Scheduler constant... ignoring...')
else:
run_cmd += f' --lr_warmup_steps="{lr_warmup_steps}"'
train_batch_size = kwargs.get("train_batch_size", "")
if train_batch_size:
run_cmd += f' --train_batch_size="{train_batch_size}"'
max_train_steps = kwargs.get("max_train_steps", "")
if max_train_steps:
run_cmd += f' --max_train_steps="{max_train_steps}"'
save_every_n_epochs = kwargs.get("save_every_n_epochs")
if save_every_n_epochs:
run_cmd += f' --save_every_n_epochs="{int(save_every_n_epochs)}"'
mixed_precision = kwargs.get("mixed_precision", "")
if mixed_precision:
run_cmd += f' --mixed_precision="{mixed_precision}"'
save_precision = kwargs.get("save_precision", "")
if save_precision:
run_cmd += f' --save_precision="{save_precision}"'
seed = kwargs.get("seed", "")
if seed != '':
run_cmd += f' --seed="{seed}"'
caption_extension = kwargs.get("caption_extension", "")
if caption_extension:
run_cmd += f' --caption_extension="{caption_extension}"'
cache_latents = kwargs.get('cache_latents')
if cache_latents:
run_cmd += ' --cache_latents'
cache_latents_to_disk = kwargs.get('cache_latents_to_disk')
if cache_latents_to_disk:
run_cmd += ' --cache_latents_to_disk'
optimizer_type = kwargs.get("optimizer", "AdamW")
run_cmd += f' --optimizer_type="{optimizer_type}"'
optimizer_args = kwargs.get("optimizer_args", "")
if optimizer_args != '':
run_cmd += f' --optimizer_args {optimizer_args}'
return run_cmd
def gradio_advanced_training(headless=False):
def noise_offset_type_change(noise_offset_type):
if noise_offset_type == 'Original':
return (gr.Group.update(visible=True), gr.Group.update(visible=False))
else:
return (gr.Group.update(visible=False), gr.Group.update(visible=True))
with gr.Row():
additional_parameters = gr.Textbox(
label='Additional parameters',
placeholder='(Optional) Use to provide additional parameters not handled by the GUI. Eg: --some_parameters "value"',
)
with gr.Row():
save_every_n_steps = gr.Number(
label='Save every N steps',
value=0,
precision=0,
info='(Optional) The model is saved every specified steps',
)
save_last_n_steps = gr.Number(
label='Save last N steps',
value=0,
precision=0,
info='(Optional) Save only the specified number of models (old models will be deleted)',
)
save_last_n_steps_state = gr.Number(
label='Save last N steps',
value=0,
precision=0,
info='(Optional) Save only the specified number of states (old models will be deleted)',
)
with gr.Row():
keep_tokens = gr.Slider(
label='Keep n tokens', value='0', minimum=0, maximum=32, step=1
)
clip_skip = gr.Slider(
label='Clip skip', value='1', minimum=1, maximum=12, step=1
)
max_token_length = gr.Dropdown(
label='Max Token Length',
choices=[
'75',
'150',
'225',
],
value='75',
)
full_fp16 = gr.Checkbox(
label='Full fp16 training (experimental)', value=False
)
with gr.Row():
gradient_checkpointing = gr.Checkbox(
label='Gradient checkpointing', value=False
)
shuffle_caption = gr.Checkbox(label='Shuffle caption', value=False)
persistent_data_loader_workers = gr.Checkbox(
label='Persistent data loader', value=False
)
mem_eff_attn = gr.Checkbox(
label='Memory efficient attention', value=False
)
with gr.Row():
# This use_8bit_adam element should be removed in a future release as it is no longer used
# use_8bit_adam = gr.Checkbox(
# label='Use 8bit adam', value=False, visible=False
# )
xformers = gr.Checkbox(label='Use xformers', value=True)
color_aug = gr.Checkbox(label='Color augmentation', value=False)
flip_aug = gr.Checkbox(label='Flip augmentation', value=False)
min_snr_gamma = gr.Slider(
label='Min SNR gamma', value=0, minimum=0, maximum=20, step=1
)
with gr.Row():
bucket_no_upscale = gr.Checkbox(
label="Don't upscale bucket resolution", value=True
)
bucket_reso_steps = gr.Number(
label='Bucket resolution steps', value=64
)
random_crop = gr.Checkbox(
label='Random crop instead of center crop', value=False
)
with gr.Row():
noise_offset_type = gr.Dropdown(
label='Noise offset type',
choices=[
'Original',
'Multires',
],
value='Original',
)
with gr.Row(visible=True) as noise_offset_original:
noise_offset = gr.Slider(
label='Noise offset',
value=0,
minimum=0,
maximum=1,
step=0.01,
info='recommended values are 0.05 - 0.15',
)
adaptive_noise_scale = gr.Slider(
label='Adaptive noise scale',
value=0,
minimum=-1,
maximum=1,
step=0.001,
info='(Experimental, Optional) Since the latent is close to a normal distribution, it may be a good idea to specify a value around 1/10 the noise offset.',
)
with gr.Row(visible=False) as noise_offset_multires:
multires_noise_iterations = gr.Slider(
label='Multires noise iterations',
value=0,
minimum=0,
maximum=64,