-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenhanced_onetrainer_ui.py
More file actions
executable file
·1796 lines (1538 loc) · 72.4 KB
/
enhanced_onetrainer_ui.py
File metadata and controls
executable file
·1796 lines (1538 loc) · 72.4 KB
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
#!/usr/bin/env python3
"""
Enhanced OneTrainer UI using DearPyGui
This is a more complete version of the OneTrainer UI that incorporates
all major functionality while avoiding segmentation faults and crashes.
"""
import os
import sys
import dearpygui.dearpygui as dpg
from pathlib import Path
import json
import traceback
import glob
import subprocess
import threading
import time
from typing import Dict, Any, List, Optional, Union, Callable, Tuple
# Add current directory to system path
current_dir = os.path.dirname(os.path.abspath(__file__))
if current_dir not in sys.path:
sys.path.insert(0, current_dir)
# Import OneTrainer modules with error handling
try:
from modules.util.enum.ModelType import ModelType
from modules.util.enum.TrainingMethod import TrainingMethod
from modules.util.enum.LossWeight import LossWeight
from modules.util.enum.Optimizer import Optimizer
from modules.util.enum.NoiseScheduler import NoiseScheduler
from modules.util.enum.LearningRateScheduler import LearningRateScheduler
from modules.util.config.TrainConfig import TrainConfig
from modules.util.config.ConceptConfig import ConceptConfig
HAS_MODULES = True
except ImportError as e:
print(f"Warning: Could not import OneTrainer modules: {e}")
HAS_MODULES = False
# Set up global config
CONFIG = {}
PRESETS_DIR = "training_presets"
THEMES = {
"dark_blue": {
"primary": (41, 83, 154, 255), # Blue
"secondary": (63, 119, 183, 255), # Lighter blue
"accent": (255, 255, 0, 255), # Yellow
"background": (30, 30, 30, 255), # Dark gray
"text": (255, 255, 255, 255), # White
"text_secondary": (200, 200, 200, 255), # Light gray
"disabled": (120, 120, 120, 255) # Gray
}
}
class EnhancedOneTrainerUI:
"""
Enhanced OneTrainer UI using DearPyGui
This class implements a comprehensive UI with all major tabs and functionality.
"""
def __init__(self):
"""Initialize the UI"""
print("Initializing Enhanced OneTrainer UI...")
# Initialize DearPyGui
dpg.create_context()
dpg.create_viewport(title="OneTrainer", width=1280, height=800)
dpg.setup_dearpygui()
# Create state
self.config = {}
self.training_thread = None
self.is_training = False
self.presets = []
self.preset_paths = {}
self.progress = {"step": 0, "total_steps": 1000, "epoch": 0, "total_epochs": 10}
# Load config
self.load_config()
# Load presets
self.load_presets()
# Create UI
self.create_ui()
# Apply theme
self.apply_theme()
def load_config(self):
"""Load configuration from file"""
# Try to load config from default location if it exists
config_file = "train_config.json"
if os.path.exists(config_file):
try:
with open(config_file, "r") as f:
self.config = json.load(f)
print(f"Loaded config from {config_file}")
except Exception as e:
print(f"Error loading config: {e}")
self.config = {}
else:
# Create default config
self.config = {
"model_type": "STABLE_DIFFUSION_15",
"training_method": "LORA",
"learning_rate": 0.0001,
"batch_size": 1,
"max_train_steps": 1000,
"save_every_n_steps": 100,
"lora_rank": 32,
"lora_alpha": 32.0,
"optimizer": "AdamW8bit",
"scheduler": "cosine"
}
def load_presets(self):
"""Load presets from directory"""
self.presets = ["-- Select Preset --"]
self.preset_paths = {}
if not os.path.exists(PRESETS_DIR):
os.makedirs(PRESETS_DIR, exist_ok=True)
return
try:
for preset_file in glob.glob(os.path.join(PRESETS_DIR, "*.json")):
preset_name = os.path.basename(preset_file).replace(".json", "")
self.presets.append(preset_name)
self.preset_paths[preset_name] = preset_file
except Exception as e:
print(f"Error loading presets: {e}")
def save_config(self, path=None):
"""Save configuration to file"""
if path is None:
path = "train_config.json"
try:
with open(path, "w") as f:
json.dump(self.config, f, indent=2)
print(f"Saved config to {path}")
except Exception as e:
print(f"Error saving config: {e}")
def apply_theme(self):
"""Apply theme to UI elements"""
theme = THEMES["dark_blue"]
with dpg.theme() as global_theme:
with dpg.theme_component(dpg.mvAll):
# Background colors
dpg.add_theme_color(dpg.mvThemeCol_WindowBg, theme["background"])
dpg.add_theme_color(dpg.mvThemeCol_ChildBg, (25, 25, 25, 255))
dpg.add_theme_color(dpg.mvThemeCol_PopupBg, (35, 35, 35, 255))
dpg.add_theme_color(dpg.mvThemeCol_Border, (60, 60, 60, 255))
# Control colors
dpg.add_theme_color(dpg.mvThemeCol_Button, theme["primary"])
dpg.add_theme_color(dpg.mvThemeCol_ButtonHovered, theme["secondary"])
dpg.add_theme_color(dpg.mvThemeCol_ButtonActive, theme["secondary"])
# Widget background
dpg.add_theme_color(dpg.mvThemeCol_FrameBg, (45, 45, 45, 255))
dpg.add_theme_color(dpg.mvThemeCol_FrameBgHovered, (55, 55, 55, 255))
dpg.add_theme_color(dpg.mvThemeCol_FrameBgActive, (65, 65, 65, 255))
# Text
dpg.add_theme_color(dpg.mvThemeCol_Text, theme["text"])
dpg.add_theme_color(dpg.mvThemeCol_TextDisabled, theme["disabled"])
# Tab colors
dpg.add_theme_color(dpg.mvThemeCol_Tab, (35, 35, 35, 255))
dpg.add_theme_color(dpg.mvThemeCol_TabHovered, theme["secondary"])
dpg.add_theme_color(dpg.mvThemeCol_TabActive, theme["primary"])
# Style settings
dpg.add_theme_style(dpg.mvStyleVar_WindowRounding, 5)
dpg.add_theme_style(dpg.mvStyleVar_FrameRounding, 3)
dpg.add_theme_style(dpg.mvStyleVar_FramePadding, 6, 4)
dpg.add_theme_style(dpg.mvStyleVar_ItemSpacing, 8, 6)
dpg.bind_theme(global_theme)
def create_ui(self):
"""Create the UI elements"""
# Create primary window
with dpg.window(tag="main_window", label="OneTrainer"):
# Create top bar
self.create_top_bar()
# Create tab bar
tab_bar = dpg.add_tab_bar(tag="main_tab_bar")
# Create tabs
model_tab = dpg.add_tab(label="Model", parent=tab_bar)
self.create_model_tab(model_tab)
training_tab = dpg.add_tab(label="Training", parent=tab_bar)
self.create_training_tab(training_tab)
lora_tab = dpg.add_tab(label="LoRA", parent=tab_bar)
self.create_lora_tab(lora_tab)
concept_tab = dpg.add_tab(label="Concept", parent=tab_bar)
self.create_concept_tab(concept_tab)
sampling_tab = dpg.add_tab(label="Sampling", parent=tab_bar)
self.create_sampling_tab(sampling_tab)
embeddings_tab = dpg.add_tab(label="Additional Embeddings", parent=tab_bar)
self.create_embeddings_tab(embeddings_tab)
cloud_tab = dpg.add_tab(label="Cloud", parent=tab_bar)
self.create_cloud_tab(cloud_tab)
# Status bar at the bottom
self.create_status_bar()
# Set primary window
dpg.set_primary_window("main_window", True)
def create_top_bar(self):
"""Create the top bar"""
with dpg.group(horizontal=True, tag="top_bar"):
# Logo placeholder
with dpg.drawlist(width=40, height=40):
dpg.draw_rectangle((0, 0), (40, 40), color=THEMES["dark_blue"]["primary"],
fill=THEMES["dark_blue"]["primary"])
# Title
dpg.add_text("OneTrainer", color=THEMES["dark_blue"]["accent"], tag="app_title")
dpg.add_spacer(width=20)
# Model type selector
dpg.add_text("Model Type:", color=THEMES["dark_blue"]["text_secondary"])
# Get model types if available
model_types = []
if HAS_MODULES:
for model_type in ModelType:
model_types.append(model_type.name)
else:
model_types = ["STABLE_DIFFUSION_15", "STABLE_DIFFUSION_XL", "PIXART_ALPHA"]
self.model_type_combo = dpg.add_combo(
items=model_types,
default_value=self.config.get("model_type", model_types[0] if model_types else ""),
callback=self.on_model_change,
width=200
)
dpg.add_spacer(width=20)
# Training method selector
dpg.add_text("Training Method:", color=THEMES["dark_blue"]["text_secondary"])
# Get training methods if available
training_methods = []
if HAS_MODULES:
for method in TrainingMethod:
training_methods.append(method.name)
else:
training_methods = ["LORA", "EMBEDDING", "FINETUNE"]
self.training_method_combo = dpg.add_combo(
items=training_methods,
default_value=self.config.get("training_method", training_methods[0] if training_methods else ""),
callback=self.on_training_method_change,
width=150
)
dpg.add_spacer(width=20)
# Preset selector
dpg.add_text("Preset:", color=THEMES["dark_blue"]["text_secondary"])
with dpg.group(horizontal=True):
self.preset_combo = dpg.add_combo(
items=self.presets,
default_value=self.presets[0] if self.presets else "",
width=200
)
# Add load button
dpg.add_button(
label="Load",
callback=self.on_load_preset,
width=50
)
# Add save button
dpg.add_button(
label="Save",
callback=self.on_save_preset,
width=50
)
dpg.add_spacer(width=20)
# Config buttons
dpg.add_button(
label="Load Config",
callback=self.on_load_config_button,
width=100
)
dpg.add_button(
label="Save Config",
callback=self.on_save_config_button,
width=100
)
def create_status_bar(self):
"""Create the status bar at the bottom"""
with dpg.group(horizontal=True, tag="status_bar"):
# Status label
dpg.add_text("Ready", tag="status_text")
dpg.add_spacer(width=20)
# Progress bar
dpg.add_text("Progress:")
self.progress_bar = dpg.add_progress_bar(default_value=0, width=200, tag="progress_bar")
self.progress_text = dpg.add_text("0/0", tag="progress_text")
def create_model_tab(self, parent):
"""Create the model tab"""
with dpg.group(parent=parent):
dpg.add_text("Model Settings", color=THEMES["dark_blue"]["accent"])
dpg.add_separator()
# Create a section for base model settings
with dpg.collapsing_header(label="Base Model", default_open=True):
# Model path
dpg.add_text("Model Path:")
with dpg.group(horizontal=True):
self.model_path_input = dpg.add_input_text(
default_value=self.config.get("model_path", ""),
width=500,
callback=lambda s, a: self.update_config("model_path", a)
)
browse_button = dpg.add_button(label="...", width=30)
# Set up browse button callback
def browse_model():
with dpg.file_dialog(
label="Select Model File",
callback=lambda s, a: self._handle_model_file_selected(a),
width=700,
height=400
):
pass
dpg.set_item_callback(browse_button, browse_model)
# Model format
dpg.add_text("Model Format:")
self.model_format_combo = dpg.add_combo(
items=["diffusers", "safetensors", "ckpt", "auto"],
default_value=self.config.get("model_format", "diffusers"),
callback=lambda s, a: self.update_config("model_format", a),
width=300
)
# Precision
dpg.add_text("Precision:")
precision_combo = dpg.add_combo(
items=["fp16", "fp32", "bf16"],
default_value=self.config.get("precision", "fp16"),
callback=lambda s, a: self.update_config("precision", a),
width=300
)
# VRAM options
with dpg.collapsing_header(label="VRAM Options", default_open=False):
vram_options = [
("Enable xformers", "use_xformers", self.config.get("use_xformers", True)),
("Enable attention slicing", "attention_slicing", self.config.get("attention_slicing", False)),
("Enable gradient checkpointing", "gradient_checkpointing", self.config.get("gradient_checkpointing", True)),
("Enable memory efficient attention", "memory_efficient_attention", self.config.get("memory_efficient_attention", True)),
("Use FP8 kernels (requires xformers)", "use_fp8_kernels", self.config.get("use_fp8_kernels", False)),
("Off-load CPU", "offload_cpu", self.config.get("offload_cpu", False))
]
for label, key, default_value in vram_options:
dpg.add_checkbox(
label=label,
default_value=default_value,
callback=lambda s, a, k=key: self.update_config(k, a)
)
# Device selection
dpg.add_text("Device:")
device_combo = dpg.add_combo(
items=["cuda", "cpu"] + (["mps"] if sys.platform == "darwin" else []),
default_value=self.config.get("device", "cuda"),
callback=lambda s, a: self.update_config("device", a),
width=300
)
# VAE section
with dpg.collapsing_header(label="VAE Settings", default_open=False):
# VAE path
dpg.add_text("VAE Path (optional):")
with dpg.group(horizontal=True):
self.vae_path_input = dpg.add_input_text(
default_value=self.config.get("vae_path", ""),
width=500,
callback=lambda s, a: self.update_config("vae_path", a)
)
browse_button = dpg.add_button(label="...", width=30)
# Set up browse button callback
def browse_vae():
with dpg.file_dialog(
label="Select VAE File",
callback=lambda s, a: self._handle_vae_file_selected(a),
width=700,
height=400
):
pass
dpg.set_item_callback(browse_button, browse_vae)
# Scale factor for VAE
dpg.add_text("VAE Scale Factor:")
vae_scale = dpg.add_slider_float(
default_value=self.config.get("vae_scale_factor", 0.18215),
min_value=0.0,
max_value=1.0,
format="%.5f",
callback=lambda s, a: self.update_config("vae_scale_factor", a),
width=300
)
# Model variants section
with dpg.collapsing_header(label="Model Variants", default_open=False):
dpg.add_text("This section is for special model variants that require additional configuration.")
# Inpainting checkbox
dpg.add_checkbox(
label="Inpainting model",
default_value=self.config.get("is_inpainting", False),
callback=lambda s, a: self.update_config("is_inpainting", a)
)
# SD v2 depth checkbox
dpg.add_checkbox(
label="SD v2 Depth model",
default_value=self.config.get("is_depth", False),
callback=lambda s, a: self.update_config("is_depth", a)
)
# SDXL refiner checkbox
dpg.add_checkbox(
label="SDXL Refiner model",
default_value=self.config.get("is_refiner", False),
callback=lambda s, a: self.update_config("is_refiner", a)
)
def _handle_model_file_selected(self, app_data):
"""Handle model file selection from file dialog"""
if "file_path_name" in app_data:
path = app_data["file_path_name"]
dpg.set_value(self.model_path_input, path)
self.update_config("model_path", path)
# Auto-detect model format from extension
if path.endswith(".safetensors"):
dpg.set_value(self.model_format_combo, "safetensors")
self.update_config("model_format", "safetensors")
elif path.endswith(".ckpt"):
dpg.set_value(self.model_format_combo, "ckpt")
self.update_config("model_format", "ckpt")
elif os.path.isdir(path):
dpg.set_value(self.model_format_combo, "diffusers")
self.update_config("model_format", "diffusers")
def _handle_vae_file_selected(self, app_data):
"""Handle VAE file selection from file dialog"""
if "file_path_name" in app_data:
path = app_data["file_path_name"]
dpg.set_value(self.vae_path_input, path)
self.update_config("vae_path", path)
def create_training_tab(self, parent):
"""Create the training tab"""
with dpg.group(parent=parent):
dpg.add_text("Training Settings", color=THEMES["dark_blue"]["accent"])
dpg.add_separator()
# Training parameters section
with dpg.collapsing_header(label="Training Parameters", default_open=True):
# Learning rate
dpg.add_text("Learning Rate:")
lr_input = dpg.add_input_float(
default_value=self.config.get("learning_rate", 0.0001),
format="%.6f",
callback=lambda s, a: self.update_config("learning_rate", a),
width=300
)
# Batch size
dpg.add_text("Batch Size:")
batch_input = dpg.add_input_int(
default_value=self.config.get("batch_size", 1),
callback=lambda s, a: self.update_config("batch_size", a),
width=300
)
# Max train steps
dpg.add_text("Max Train Steps:")
steps_input = dpg.add_input_int(
default_value=self.config.get("max_train_steps", 1000),
callback=lambda s, a: self.update_config("max_train_steps", a),
width=300
)
# Gradient accumulation steps
dpg.add_text("Gradient Accumulation Steps:")
grad_accum_input = dpg.add_input_int(
default_value=self.config.get("gradient_accumulation_steps", 1),
callback=lambda s, a: self.update_config("gradient_accumulation_steps", a),
width=300
)
# Mixed precision
dpg.add_text("Mixed Precision:")
mixed_precision_combo = dpg.add_combo(
items=["no", "fp16", "bf16"],
default_value=self.config.get("mixed_precision", "fp16"),
callback=lambda s, a: self.update_config("mixed_precision", a),
width=300
)
# Save checkpoints
dpg.add_text("Save Every N Steps:")
save_steps_input = dpg.add_input_int(
default_value=self.config.get("save_every_n_steps", 100),
callback=lambda s, a: self.update_config("save_every_n_steps", a),
width=300
)
# Optimizer section
with dpg.collapsing_header(label="Optimizer Settings", default_open=True):
# Optimizer type
dpg.add_text("Optimizer:")
# Get optimizer types
optimizer_types = []
if HAS_MODULES:
for optimizer in Optimizer:
optimizer_types.append(optimizer.name)
else:
optimizer_types = ["AdamW", "AdamW8bit", "Lion", "Lion8bit", "SGD"]
optimizer_combo = dpg.add_combo(
items=optimizer_types,
default_value=self.config.get("optimizer", "AdamW8bit"),
callback=lambda s, a: self.update_config("optimizer", a),
width=300
)
# Weight decay
dpg.add_text("Weight Decay:")
weight_decay_input = dpg.add_input_float(
default_value=self.config.get("weight_decay", 0.01),
format="%.4f",
callback=lambda s, a: self.update_config("weight_decay", a),
width=300
)
# Max gradient norm
dpg.add_text("Max Gradient Norm:")
max_grad_norm_input = dpg.add_input_float(
default_value=self.config.get("max_grad_norm", 1.0),
format="%.2f",
callback=lambda s, a: self.update_config("max_grad_norm", a),
width=300
)
# Scheduler section
with dpg.collapsing_header(label="Learning Rate Scheduler", default_open=True):
# Scheduler type
dpg.add_text("Scheduler:")
# Get scheduler types
scheduler_types = []
if HAS_MODULES:
for scheduler in LearningRateScheduler:
scheduler_types.append(scheduler.name)
else:
scheduler_types = ["constant", "cosine", "linear", "polynomial"]
scheduler_combo = dpg.add_combo(
items=scheduler_types,
default_value=self.config.get("scheduler", "cosine"),
callback=lambda s, a: self.update_config("scheduler", a),
width=300
)
# Warmup steps
dpg.add_text("Warmup Steps:")
warmup_steps_input = dpg.add_input_int(
default_value=self.config.get("warmup_steps", 100),
callback=lambda s, a: self.update_config("warmup_steps", a),
width=300
)
# Warmup ratio
dpg.add_text("Warmup Ratio:")
warmup_ratio_input = dpg.add_input_float(
default_value=self.config.get("warmup_ratio", 0.1),
format="%.3f",
callback=lambda s, a: self.update_config("warmup_ratio", a),
width=300
)
# Noise scheduler section
with dpg.collapsing_header(label="Noise Scheduler", default_open=False):
# Noise scheduler type
dpg.add_text("Noise Scheduler Type:")
# Get noise scheduler types
noise_scheduler_types = []
if HAS_MODULES:
for scheduler in NoiseScheduler:
noise_scheduler_types.append(scheduler.name)
else:
noise_scheduler_types = ["ddpm", "ddim", "pndm", "lms", "euler", "euler_ancestral"]
noise_scheduler_combo = dpg.add_combo(
items=noise_scheduler_types,
default_value=self.config.get("noise_scheduler", "ddpm"),
callback=lambda s, a: self.update_config("noise_scheduler", a),
width=300
)
# Prediction type
dpg.add_text("Prediction Type:")
prediction_type_combo = dpg.add_combo(
items=["epsilon", "v_prediction", "sample"],
default_value=self.config.get("prediction_type", "epsilon"),
callback=lambda s, a: self.update_config("prediction_type", a),
width=300
)
# Snr gamma
dpg.add_text("SNR Gamma:")
snr_gamma_input = dpg.add_input_float(
default_value=self.config.get("snr_gamma", 5.0),
format="%.1f",
callback=lambda s, a: self.update_config("snr_gamma", a),
width=300
)
# Training controls
with dpg.group(horizontal=True):
# Start training button
self.train_button = dpg.add_button(
label="Start Training",
callback=self.on_start_training,
width=150,
height=40
)
# Stop training button
self.stop_button = dpg.add_button(
label="Stop Training",
callback=self.on_stop_training,
width=150,
height=40,
enabled=False
)
def create_lora_tab(self, parent):
"""Create the LoRA tab"""
with dpg.group(parent=parent):
dpg.add_text("LoRA Settings", color=THEMES["dark_blue"]["accent"])
dpg.add_separator()
# Main LoRA parameters section
with dpg.collapsing_header(label="Core LoRA Parameters", default_open=True):
# LoRA Rank
dpg.add_text("LoRA Rank:")
lora_rank_input = dpg.add_input_int(
default_value=self.config.get("lora_rank", 32),
callback=lambda s, a: self.update_config("lora_rank", a),
width=300
)
# LoRA Alpha
dpg.add_text("LoRA Alpha:")
lora_alpha_input = dpg.add_input_float(
default_value=self.config.get("lora_alpha", 32.0),
callback=lambda s, a: self.update_config("lora_alpha", a),
width=300
)
# Dropout
dpg.add_text("Dropout:")
lora_dropout_input = dpg.add_slider_float(
default_value=self.config.get("lora_dropout", 0.0),
min_value=0.0,
max_value=0.5,
format="%.2f",
callback=lambda s, a: self.update_config("lora_dropout", a),
width=300
)
# Target modules
dpg.add_text("Target Modules:")
target_modules_input = dpg.add_input_text(
default_value=self.config.get("target_modules", ""),
hint="q_proj,k_proj,v_proj,out_proj",
callback=lambda s, a: self.update_config("target_modules", a),
width=500
)
# Target layers
dpg.add_text("Target Layers:")
target_layers_input = dpg.add_input_text(
default_value=self.config.get("target_layers", ""),
hint="down_blocks,mid_block,up_blocks",
callback=lambda s, a: self.update_config("target_layers", a),
width=500
)
# Advanced LoRA section
with dpg.collapsing_header(label="Advanced LoRA Settings", default_open=False):
# Network weights
dpg.add_text("Pretrained Network Weights (optional):")
with dpg.group(horizontal=True):
self.network_weights_input = dpg.add_input_text(
default_value=self.config.get("network_weights", ""),
width=500,
callback=lambda s, a: self.update_config("network_weights", a)
)
browse_button = dpg.add_button(label="...", width=30)
# Set up browse button callback
def browse_weights():
with dpg.file_dialog(
label="Select Network Weights File",
callback=lambda s, a: self._handle_weights_file_selected(a),
width=700,
height=400
):
pass
dpg.set_item_callback(browse_button, browse_weights)
# Scale option
dpg.add_checkbox(
label="Scale LoRA weights",
default_value=self.config.get("scale_lora_weights", True),
callback=lambda s, a: self.update_config("scale_lora_weights", a)
)
# LoRA type (LyCORIS)
dpg.add_text("LoRA Type (LyCORIS):")
lora_type_combo = dpg.add_combo(
items=["lora", "loha", "lokr", "locon", "ia3", "dylora"],
default_value=self.config.get("lora_type", "lora"),
callback=lambda s, a: self.update_config("lora_type", a),
width=300
)
# LoCon / LoKr options
dpg.add_text("LoKr Decomposition Types:")
decomp_type_combo = dpg.add_combo(
items=["tucker", "svd", "full"],
default_value=self.config.get("decomposition_type", "tucker"),
callback=lambda s, a: self.update_config("decomposition_type", a),
width=300
)
# LoHa options
dpg.add_text("LoHa Hadamard Config:")
with dpg.group(horizontal=True):
use_hadamard_checkbox = dpg.add_checkbox(
label="Use Hadamard Product",
default_value=self.config.get("use_hadamard", True),
callback=lambda s, a: self.update_config("use_hadamard", a)
)
hadamard_dim_input = dpg.add_input_int(
default_value=self.config.get("hadamard_dim", 4),
callback=lambda s, a: self.update_config("hadamard_dim", a),
width=100
)
# LoRA target layers section
with dpg.collapsing_header(label="Model-Specific Settings", default_open=False):
dpg.add_text("Target specific parts of the model:")
# Text encoder enable/disable
dpg.add_checkbox(
label="Apply to Text Encoder",
default_value=self.config.get("train_text_encoder", True),
callback=lambda s, a: self.update_config("train_text_encoder", a)
)
# Text encoder 2 enable/disable (for SDXL)
dpg.add_checkbox(
label="Apply to Text Encoder 2 (SDXL)",
default_value=self.config.get("train_text_encoder_2", True),
callback=lambda s, a: self.update_config("train_text_encoder_2", a)
)
# UNet enable/disable
dpg.add_checkbox(
label="Apply to UNet",
default_value=self.config.get("train_unet", True),
callback=lambda s, a: self.update_config("train_unet", a)
)
# Different rank for text encoder
dpg.add_checkbox(
label="Use different rank for text encoder",
default_value=self.config.get("use_different_text_encoder_rank", False),
callback=lambda s, a: self.update_config("use_different_text_encoder_rank", a)
)
# Text encoder rank
dpg.add_text("Text Encoder Rank:")
text_encoder_rank_input = dpg.add_input_int(
default_value=self.config.get("text_encoder_rank", 4),
callback=lambda s, a: self.update_config("text_encoder_rank", a),
width=300
)
def _handle_weights_file_selected(self, app_data):
"""Handle weights file selection from file dialog"""
if "file_path_name" in app_data:
path = app_data["file_path_name"]
dpg.set_value(self.network_weights_input, path)
self.update_config("network_weights", path)
def create_concept_tab(self, parent):
"""Create the concept tab"""
with dpg.group(parent=parent):
dpg.add_text("Concept Settings", color=THEMES["dark_blue"]["accent"])
dpg.add_separator()
# Main concept section
with dpg.collapsing_header(label="Concept Definition", default_open=True):
# Concept parameters
dpg.add_text("Concept Name:")
self.concept_name_input = dpg.add_input_text(
default_value=self.config.get("concept_name", "my_concept"),
width=300,
callback=lambda s, a: self.update_config("concept_name", a)
)
dpg.add_text("Image Directory:")
with dpg.group(horizontal=True):
self.image_dir_input = dpg.add_input_text(
default_value=self.config.get("image_dir", ""),
width=500,
callback=lambda s, a: self.update_config("image_dir", a)
)
browse_button = dpg.add_button(label="...", width=30)
# Set up browse button callback
def browse_dir():
with dpg.file_dialog(
label="Select Image Directory",
directory_selector=True,
callback=lambda s, a: self._handle_image_dir_selected(a),
width=700,
height=400
):
pass
dpg.set_item_callback(browse_button, browse_dir)
# Trigger words section
dpg.add_text("Trigger Words:")
self.trigger_words_input = dpg.add_input_text(
default_value=self.config.get("trigger_words", ""),
width=500,
callback=lambda s, a: self.update_config("trigger_words", a)
)
# Instance prompt - for Dreambooth-style training
dpg.add_text("Instance Prompt:")
instance_prompt_input = dpg.add_input_text(
default_value=self.config.get("instance_prompt", "a photo of sks"),
width=500,
callback=lambda s, a: self.update_config("instance_prompt", a)
)
# Class prompt - for Dreambooth-style training
dpg.add_text("Class Prompt:")
class_prompt_input = dpg.add_input_text(
default_value=self.config.get("class_prompt", "a photo of"),
width=500,
callback=lambda s, a: self.update_config("class_prompt", a)
)
# Image preprocessing section
with dpg.collapsing_header(label="Image Preprocessing", default_open=True):
# Resolution
dpg.add_text("Resolution:")
with dpg.group(horizontal=True):
dpg.add_input_int(
default_value=self.config.get("resolution_width", 512),
width=145,
callback=lambda s, a: self.update_config("resolution_width", a)
)
dpg.add_text("x")
dpg.add_input_int(
default_value=self.config.get("resolution_height", 512),
width=145,
callback=lambda s, a: self.update_config("resolution_height", a)
)
# Image preprocessing options
preprocessing_options = [
("Center crop", "center_crop", self.config.get("center_crop", True)),
("Random crop", "random_crop", self.config.get("random_crop", False)),
("Random flip", "random_flip", self.config.get("random_flip", True)),
("Remove background", "remove_background", self.config.get("remove_background", False)),
("Auto face crop", "auto_face_crop", self.config.get("auto_face_crop", False)),
("Improve captions", "improve_captions", self.config.get("improve_captions", False))
]
for label, key, default_value in preprocessing_options:
dpg.add_checkbox(
label=label,
default_value=default_value,
callback=lambda s, a, k=key: self.update_config(k, a)
)
# Caption extension
dpg.add_text("Caption File Extension:")
caption_ext_combo = dpg.add_combo(
items=[".txt", ".caption"],
default_value=self.config.get("caption_extension", ".txt"),
callback=lambda s, a: self.update_config("caption_extension", a),
width=300
)
# Class images section (for regularization)
with dpg.collapsing_header(label="Class/Regularization Images", default_open=False):
# Use class/regularization images checkbox
dpg.add_checkbox(
label="Use class/regularization images",
default_value=self.config.get("use_class_images", False),
callback=lambda s, a: self.update_config("use_class_images", a)
)
# Class images directory
dpg.add_text("Class Images Directory:")
with dpg.group(horizontal=True):
self.class_dir_input = dpg.add_input_text(
default_value=self.config.get("class_dir", ""),
width=500,
callback=lambda s, a: self.update_config("class_dir", a)
)
browse_button = dpg.add_button(label="...", width=30)
# Set up browse button callback
def browse_class_dir():
with dpg.file_dialog(
label="Select Class Images Directory",
directory_selector=True,
callback=lambda s, a: self._handle_class_dir_selected(a),
width=700,
height=400
):
pass
dpg.set_item_callback(browse_button, browse_class_dir)
# Number of class images
dpg.add_text("Number of Class Images:")
num_class_images_input = dpg.add_input_int(
default_value=self.config.get("num_class_images", 100),
callback=lambda s, a: self.update_config("num_class_images", a),
width=300
)
# Class prompt for auto-generation
dpg.add_text("Auto-generation Class Prompt:")
auto_class_prompt_input = dpg.add_input_text(
default_value=self.config.get("auto_class_prompt", "a photo of a person"),
width=500,
callback=lambda s, a: self.update_config("auto_class_prompt", a)
)
# Advanced concept options
with dpg.collapsing_header(label="Advanced Options", default_open=False):
# Concept weights
dpg.add_text("Concept Weight:")
concept_weight_slider = dpg.add_slider_float(
default_value=self.config.get("concept_weight", 1.0),