-
-
Notifications
You must be signed in to change notification settings - Fork 283
/
train_dreambooth.py
1874 lines (1645 loc) · 85.1 KB
/
train_dreambooth.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
# Borrowed heavily from https://github.com/bmaltais/kohya_ss/blob/master/train_db.py and
# https://github.com/ShivamShrirao/diffusers/tree/main/examples/dreambooth
# With some custom bits sprinkled in and some stuff from OG diffusers as well.
import itertools
import json
import logging
import math
import os
import shutil
import time
import traceback
from contextlib import ExitStack
from decimal import Decimal
from pathlib import Path
import safetensors.torch
import tomesd
import torch
import torch.backends.cuda
import torch.backends.cudnn
import torch.nn.functional as F
from accelerate import Accelerator
from accelerate.utils.random import set_seed as set_seed2
from diffusers import (
AutoencoderKL,
DiffusionPipeline,
UNet2DConditionModel,
DEISMultistepScheduler,
UniPCMultistepScheduler, StableDiffusionXLPipeline, StableDiffusionPipeline
)
from diffusers.loaders import LoraLoaderMixin
from diffusers.models.attention_processor import LoRAAttnProcessor2_0, LoRAAttnProcessor
from diffusers.training_utils import unet_lora_state_dict
from diffusers.utils import logging as dl
from diffusers.utils.torch_utils import randn_tensor
from torch.cuda.profiler import profile
from torch.utils.data import Dataset
from transformers import AutoTokenizer
from dreambooth import shared
from dreambooth.dataclasses.prompt_data import PromptData
from dreambooth.dataclasses.train_result import TrainResult
from dreambooth.dataset.bucket_sampler import BucketSampler
from dreambooth.dataset.sample_dataset import SampleDataset
from dreambooth.deis_velocity import get_velocity
from dreambooth.diff_lora_to_sd_lora import convert_diffusers_to_kohya_lora
from dreambooth.diff_to_sd import compile_checkpoint, copy_diffusion_model
from dreambooth.diff_to_sdxl import compile_checkpoint as compile_checkpoint_xl
from dreambooth.memory import find_executable_batch_size
from dreambooth.optimization import UniversalScheduler, get_optimizer, get_noise_scheduler
from dreambooth.shared import status
from dreambooth.utils.gen_utils import generate_classifiers, generate_dataset
from dreambooth.utils.image_utils import db_save_image, get_scheduler_class
from dreambooth.utils.model_utils import (
unload_system_models,
import_model_class_from_model_name_or_path,
safe_unpickle_disabled,
xformerify,
torch2ify
)
from dreambooth.utils.text_utils import encode_hidden_state, save_token_counts
from dreambooth.utils.utils import (cleanup, printm, verify_locon_installed,
patch_accelerator_for_fp16_training)
from dreambooth.webhook import send_training_update
from dreambooth.xattention import optim_to
from helpers.ema_model import EMAModel
from helpers.log_parser import LogParser
from helpers.mytqdm import mytqdm
from lora_diffusion.lora import (
set_lora_requires_grad,
)
try:
import wandb
# Disable annoying wandb popup?
wandb.config.auto_init = False
except:
pass
logger = logging.getLogger(__name__)
# define a Handler which writes DEBUG messages or higher to the sys.stderr
dl.set_verbosity_error()
last_samples = []
last_prompts = []
class ConditionalAccumulator:
def __init__(self, accelerator, *encoders):
self.accelerator = accelerator
self.encoders = encoders
self.stack = ExitStack()
def __enter__(self):
for encoder in self.encoders:
if encoder is not None:
self.stack.enter_context(self.accelerator.accumulate(encoder))
return self
def __exit__(self, exc_type, exc_value, traceback):
self.stack.__exit__(exc_type, exc_value, traceback)
def text_encoder_lora_state_dict(text_encoder):
state_dict = {}
def text_encoder_attn_modules(text_encoder):
from transformers import CLIPTextModel, CLIPTextModelWithProjection
attn_modules = []
if isinstance(text_encoder, (CLIPTextModel, CLIPTextModelWithProjection)):
for i, layer in enumerate(text_encoder.text_model.encoder.layers):
name = f"text_model.encoder.layers.{i}.self_attn"
mod = layer.self_attn
attn_modules.append((name, mod))
return attn_modules
for name, module in text_encoder_attn_modules(text_encoder):
for k, v in module.q_proj.lora_linear_layer.state_dict().items():
state_dict[f"{name}.q_proj.lora_linear_layer.{k}"] = v
for k, v in module.k_proj.lora_linear_layer.state_dict().items():
state_dict[f"{name}.k_proj.lora_linear_layer.{k}"] = v
for k, v in module.v_proj.lora_linear_layer.state_dict().items():
state_dict[f"{name}.v_proj.lora_linear_layer.{k}"] = v
for k, v in module.out_proj.lora_linear_layer.state_dict().items():
state_dict[f"{name}.out_proj.lora_linear_layer.{k}"] = v
return state_dict
def check_and_patch_scheduler(scheduler_class):
if not hasattr(scheduler_class, 'get_velocity'):
logger.debug(f"Adding 'get_velocity' method to {scheduler_class.__name__}...")
scheduler_class.get_velocity = get_velocity
try:
check_and_patch_scheduler(DEISMultistepScheduler)
check_and_patch_scheduler(UniPCMultistepScheduler)
except:
logger.warning("Exception while adding 'get_velocity' method to the schedulers.")
export_diffusers = False
user_model_dir = ""
def set_seed(deterministic: bool):
if deterministic:
torch.backends.cudnn.deterministic = True
seed = 0
set_seed2(seed)
else:
torch.backends.cudnn.deterministic = False
to_delete = []
def clean_global_state():
for check in to_delete:
if check:
try:
obj_name = check.__name__
del check
# Log the name of the thing deleted
logger.debug(f"Deleted {obj_name}")
except:
pass
def current_prior_loss(args, current_epoch):
if not args.prior_loss_scale:
return args.prior_loss_weight
if not args.prior_loss_target:
args.prior_loss_target = 150
if not args.prior_loss_weight_min:
args.prior_loss_weight_min = 0.1
if current_epoch >= args.prior_loss_target:
return args.prior_loss_weight_min
percentage_completed = current_epoch / args.prior_loss_target
prior = (
args.prior_loss_weight * (1 - percentage_completed)
+ args.prior_loss_weight_min * percentage_completed
)
printm(f"Prior: {prior}")
return prior
def stop_profiler(profiler):
if profiler is not None:
try:
logger.debug("Stopping profiler.")
profiler.stop()
except:
pass
def main(class_gen_method: str = "Native Diffusers", user: str = None) -> TrainResult:
"""
@param class_gen_method: Image Generation Library.
@param user: User to send training updates to (for new UI)
@return: TrainResult
"""
args = shared.db_model_config
status_handler = None
logging_dir = Path(args.model_dir, "logging")
global export_diffusers, user_model_dir
try:
from core.handlers.status import StatusHandler
from core.handlers.config import ConfigHandler
from core.handlers.models import ModelHandler
mh = ModelHandler(user_name=user)
status_handler = StatusHandler(user_name=user, target="dreamProgress")
export_diffusers = True
user_model_dir = mh.user_path
logger.debug(f"Export diffusers: {export_diffusers}, diffusers dir: {user_model_dir}")
shared.status_handler = status_handler
logger.debug(f"Loaded config: {args.__dict__}")
except:
pass
log_parser = LogParser()
def update_status(data: dict):
if status_handler is not None:
if "iterations_per_second" in data:
data = {"status": json.dumps(data)}
status_handler.update(items=data)
result = TrainResult
result.config = args
set_seed(args.deterministic)
@find_executable_batch_size(
starting_batch_size=args.train_batch_size,
starting_grad_size=args.gradient_accumulation_steps,
logging_dir=logging_dir,
cleanup_function=clean_global_state()
)
def inner_loop(train_batch_size: int, gradient_accumulation_steps: int, profiler: profile):
text_encoder = None
text_encoder_two = None
global last_samples
global last_prompts
stop_text_percentage = args.stop_text_encoder
if not args.train_unet:
stop_text_percentage = 1
n_workers = 0
args.max_token_length = int(args.max_token_length)
if not args.pad_tokens and args.max_token_length > 75:
logger.warning("Cannot raise token length limit above 75 when pad_tokens=False")
verify_locon_installed(args)
precision = args.mixed_precision if not shared.force_cpu else "no"
weight_dtype = torch.float32
if precision == "fp16":
weight_dtype = torch.float16
elif precision == "bf16":
weight_dtype = torch.bfloat16
try:
accelerator = Accelerator(
gradient_accumulation_steps=gradient_accumulation_steps,
mixed_precision=precision,
log_with="all",
project_dir=logging_dir,
cpu=shared.force_cpu,
)
run_name = "dreambooth.events"
max_log_size = 250 * 1024 # specify the maximum log size
except Exception as e:
if "AcceleratorState" in str(e):
msg = "Change in precision detected, please restart the webUI entirely to use new precision."
else:
msg = f"Exception initializing accelerator: {e}"
logger.warning(msg)
result.msg = msg
result.config = args
stop_profiler(profiler)
return result
# This is the secondary status bar
pbar2 = mytqdm(
disable=not accelerator.is_local_main_process,
position=1,
user=user,
target="dreamProgress",
index=1
)
# Currently, it's not possible to do gradient accumulation when training two models with
# accelerate.accumulate This will be enabled soon in accelerate. For now, we don't allow gradient
# accumulation when training two models.
# TODO (patil-suraj): Remove this check when gradient accumulation with two models is enabled in accelerate.
if (
stop_text_percentage != 0
and gradient_accumulation_steps > 1
and accelerator.num_processes > 1
):
msg = (
"Gradient accumulation is not supported when training the text encoder in distributed training. "
"Please set gradient_accumulation_steps to 1. This feature will be supported in the future. Text "
"encoder training will be disabled."
)
logger.warning(msg)
status.textinfo = msg
update_status({"status": msg})
stop_text_percentage = 0
pretrained_path = args.get_pretrained_model_name_or_path()
logger.debug(f"Pretrained path: {pretrained_path}")
count, instance_prompts, class_prompts = generate_classifiers(
args, class_gen_method=class_gen_method, accelerator=accelerator, ui=False, pbar=pbar2
)
save_token_counts(args, instance_prompts, 10)
if status.interrupted:
result.msg = "Training interrupted."
stop_profiler(profiler)
return result
num_components = 5
if args.model_type == "SDXL":
num_components = 7
pbar2.reset(num_components)
pbar2.set_description("Loading model components...")
pbar2.set_postfix(refresh=True)
if class_gen_method == "Native Diffusers" and count > 0:
unload_system_models()
def create_vae():
vae_path = (
args.pretrained_vae_name_or_path
if args.pretrained_vae_name_or_path
else args.get_pretrained_model_name_or_path()
)
with safe_unpickle_disabled():
new_vae = AutoencoderKL.from_pretrained(
vae_path,
subfolder=None if args.pretrained_vae_name_or_path else "vae",
revision=args.revision,
)
new_vae.requires_grad_(False)
new_vae.to(accelerator.device, dtype=weight_dtype)
return new_vae
with safe_unpickle_disabled():
# Load the tokenizer
pbar2.set_description("Loading tokenizer...")
pbar2.update()
pbar2.set_postfix(refresh=True)
tokenizer = AutoTokenizer.from_pretrained(
os.path.join(pretrained_path, "tokenizer"),
revision=args.revision,
use_fast=False,
)
tokenizer_two = None
if args.model_type == "SDXL":
pbar2.set_description("Loading tokenizer 2...")
pbar2.update()
pbar2.set_postfix(refresh=True)
tokenizer_two = AutoTokenizer.from_pretrained(
os.path.join(pretrained_path, "tokenizer_2"),
revision=args.revision,
use_fast=False,
)
# import correct text encoder class
text_encoder_cls = import_model_class_from_model_name_or_path(
args.get_pretrained_model_name_or_path(), args.revision
)
pbar2.set_description("Loading text encoder...")
pbar2.update()
pbar2.set_postfix(refresh=True)
# Load models and create wrapper for stable diffusion
text_encoder = text_encoder_cls.from_pretrained(
args.get_pretrained_model_name_or_path(),
subfolder="text_encoder",
revision=args.revision,
torch_dtype=torch.float32,
)
if args.model_type == "SDXL":
# import correct text encoder class
text_encoder_cls_two = import_model_class_from_model_name_or_path(
args.get_pretrained_model_name_or_path(), args.revision, subfolder="text_encoder_2"
)
pbar2.set_description("Loading text encoder 2...")
pbar2.update()
pbar2.set_postfix(refresh=True)
# Load models and create wrapper for stable diffusion
text_encoder_two = text_encoder_cls_two.from_pretrained(
args.get_pretrained_model_name_or_path(),
subfolder="text_encoder_2",
revision=args.revision,
torch_dtype=torch.float32,
)
printm("Created tenc")
pbar2.set_description("Loading VAE...")
pbar2.update()
vae = create_vae()
printm("Created vae")
pbar2.set_description("Loading unet...")
pbar2.update()
unet = UNet2DConditionModel.from_pretrained(
args.get_pretrained_model_name_or_path(),
subfolder="unet",
revision=args.revision,
torch_dtype=torch.float32,
)
if args.attention == "xformers" and not shared.force_cpu:
xformerify(unet, use_lora=args.use_lora)
xformerify(vae, use_lora=args.use_lora)
unet = torch2ify(unet)
if args.full_mixed_precision:
if args.mixed_precision == "fp16":
patch_accelerator_for_fp16_training(accelerator)
unet.to(accelerator.device, dtype=weight_dtype)
else:
# Check that all trainable models are in full precision
low_precision_error_string = (
"Please make sure to always have all model weights in full float32 precision when starting training - "
"even if doing mixed precision training. copy of the weights should still be float32."
)
if accelerator.unwrap_model(unet).dtype != torch.float32:
logger.warning(
f"Unet loaded as datatype {accelerator.unwrap_model(unet).dtype}. {low_precision_error_string}"
)
if (
args.stop_text_encoder != 0
and accelerator.unwrap_model(text_encoder).dtype != torch.float32
):
logger.warning(
f"Text encoder loaded as datatype {accelerator.unwrap_model(text_encoder).dtype}."
f" {low_precision_error_string}"
)
if (
args.stop_text_encoder != 0
and accelerator.unwrap_model(text_encoder_two).dtype != torch.float32
):
logger.warning(
f"Text encoder loaded as datatype {accelerator.unwrap_model(text_encoder_two).dtype}."
f" {low_precision_error_string}"
)
if args.gradient_checkpointing:
if args.train_unet:
unet.enable_gradient_checkpointing()
if stop_text_percentage != 0:
text_encoder.gradient_checkpointing_enable()
if args.model_type == "SDXL":
text_encoder_two.gradient_checkpointing_enable()
if args.use_lora:
# We need to enable gradients on an input for gradient checkpointing to work
# This will not be optimized because it is not a param to optimizer
text_encoder.text_model.embeddings.position_embedding.requires_grad_(True)
if args.model_type == "SDXL":
text_encoder_two.text_model.embeddings.position_embedding.requires_grad_(True)
else:
text_encoder.to(accelerator.device, dtype=weight_dtype)
if args.model_type == "SDXL":
text_encoder_two.to(accelerator.device, dtype=weight_dtype)
ema_model = None
if args.use_ema:
if os.path.exists(
os.path.join(
args.get_pretrained_model_name_or_path(),
"ema_unet",
"diffusion_pytorch_model.safetensors",
)
):
ema_unet = UNet2DConditionModel.from_pretrained(
args.get_pretrained_model_name_or_path(),
subfolder="ema_unet",
revision=args.revision,
torch_dtype=weight_dtype,
)
if args.attention == "xformers" and not shared.force_cpu:
xformerify(ema_unet, use_lora=args.use_lora)
ema_model = EMAModel(
ema_unet, device=accelerator.device, dtype=weight_dtype
)
del ema_unet
else:
ema_model = EMAModel(
unet, device=accelerator.device, dtype=weight_dtype
)
# Create shared unet/tenc learning rate variables
learning_rate = args.learning_rate
txt_learning_rate = args.txt_learning_rate
if args.use_lora:
learning_rate = args.lora_learning_rate
txt_learning_rate = args.lora_txt_learning_rate
if args.use_lora or not args.train_unet:
unet.requires_grad_(False)
unet_lora_params = None
if args.use_lora:
pbar2.reset(1)
pbar2.set_description("Loading LoRA...")
# now we will add new LoRA weights to the attention layers
# Set correct lora layers
unet_lora_attn_procs = {}
unet_lora_params = []
rank = args.lora_unet_rank
for name, attn_processor in unet.attn_processors.items():
cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
hidden_size = None
if name.startswith("mid_block"):
hidden_size = unet.config.block_out_channels[-1]
elif name.startswith("up_blocks"):
block_id = int(name[len("up_blocks.")])
hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
elif name.startswith("down_blocks"):
block_id = int(name[len("down_blocks.")])
hidden_size = unet.config.block_out_channels[block_id]
lora_attn_processor_class = (
LoRAAttnProcessor2_0 if hasattr(F, "scaled_dot_product_attention") else LoRAAttnProcessor
)
if hidden_size is None:
logger.warning(f"Could not find hidden size for {name}. Skipping...")
continue
module = lora_attn_processor_class(
hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, rank=rank
)
unet_lora_attn_procs[name] = module
unet_lora_params.extend(module.parameters())
unet.set_attn_processor(unet_lora_attn_procs)
# The text encoder comes from 🤗 transformers, so we cannot directly modify it.
# So, instead, we monkey-patch the forward calls of its attention-blocks.
if stop_text_percentage != 0:
# ensure that dtype is float32, even if rest of the model that isn't trained is loaded in fp16
text_encoder_lora_params = LoraLoaderMixin._modify_text_encoder(
text_encoder, dtype=torch.float32, rank=args.lora_txt_rank
)
if args.model_type == "SDXL":
text_encoder_lora_params_two = LoraLoaderMixin._modify_text_encoder(
text_encoder_two, dtype=torch.float32, rank=args.lora_txt_rank
)
params_to_optimize = (
itertools.chain(unet_lora_params, text_encoder_lora_params, text_encoder_lora_params_two))
else:
params_to_optimize = (itertools.chain(unet_lora_params, text_encoder_lora_params))
else:
params_to_optimize = unet_lora_params
# Load LoRA weights if specified
if args.lora_model_name is not None and args.lora_model_name != "":
logger.debug(f"Load lora from {args.lora_model_name}")
lora_state_dict, network_alphas = LoraLoaderMixin.lora_state_dict(args.lora_model_name)
LoraLoaderMixin.load_lora_into_unet(lora_state_dict, network_alphas=network_alphas, unet=unet)
LoraLoaderMixin.load_lora_into_text_encoder(
lora_state_dict, network_alphas=network_alphas, text_encoder=text_encoder)
if text_encoder_two is not None:
LoraLoaderMixin.load_lora_into_text_encoder(
lora_state_dict, network_alphas=network_alphas, text_encoder=text_encoder_two)
elif stop_text_percentage != 0:
if args.train_unet:
if args.model_type == "SDXL":
params_to_optimize = itertools.chain(unet.parameters(), text_encoder.parameters(),
text_encoder_two.parameters())
else:
params_to_optimize = itertools.chain(unet.parameters(), text_encoder.parameters())
else:
if args.model_type == "SDXL":
params_to_optimize = itertools.chain(text_encoder.parameters(), text_encoder_two.parameters())
else:
params_to_optimize = itertools.chain(text_encoder.parameters())
else:
params_to_optimize = unet.parameters()
optimizer = get_optimizer(args.optimizer, learning_rate, args.weight_decay, params_to_optimize)
if len(optimizer.param_groups) > 1:
try:
optimizer.param_groups[1]["weight_decay"] = args.tenc_weight_decay
optimizer.param_groups[1]["grad_clip_norm"] = args.tenc_grad_clip_norm
except:
logger.warning("Exception setting tenc weight decay")
traceback.print_exc()
if len(optimizer.param_groups) > 2:
try:
optimizer.param_groups[2]["weight_decay"] = args.tenc_weight_decay
optimizer.param_groups[2]["grad_clip_norm"] = args.tenc_grad_clip_norm
except:
logger.warning("Exception setting tenc weight decay")
traceback.print_exc()
noise_scheduler = get_noise_scheduler(args)
global to_delete
to_delete = [unet, text_encoder, text_encoder_two, tokenizer, tokenizer_two, optimizer, vae]
def cleanup_memory():
try:
if unet:
del unet
if text_encoder:
del text_encoder
if text_encoder_two:
del text_encoder_two
if tokenizer:
del tokenizer
if tokenizer_two:
del tokenizer_two
if optimizer:
del optimizer
if train_dataloader:
del train_dataloader
if train_dataset:
del train_dataset
if lr_scheduler:
del lr_scheduler
if vae:
del vae
if unet_lora_params:
del unet_lora_params
except:
pass
cleanup(True)
if args.cache_latents:
vae.to(accelerator.device, dtype=weight_dtype)
vae.requires_grad_(False)
vae.eval()
if status.interrupted:
result.msg = "Training interrupted."
stop_profiler(profiler)
return result
printm("Loading dataset...")
pbar2.reset()
pbar2.set_description("Loading dataset")
with_prior_preservation = False
tokenizers = [tokenizer] if tokenizer_two is None else [tokenizer, tokenizer_two]
text_encoders = [text_encoder] if text_encoder_two is None else [text_encoder, text_encoder_two]
train_dataset = generate_dataset(
model_name=args.model_name,
instance_prompts=instance_prompts,
class_prompts=class_prompts,
batch_size=args.train_batch_size,
tokenizer=tokenizers,
text_encoder=text_encoders,
accelerator=accelerator,
vae=vae if args.cache_latents else None,
debug=False,
model_dir=args.model_dir,
max_token_length=args.max_token_length,
pbar=pbar2
)
if train_dataset.class_count > 0:
with_prior_preservation = True
pbar2.reset()
printm("Dataset loaded.")
tokenizer_max_length = tokenizer.model_max_length
if args.cache_latents:
printm("Unloading vae.")
del vae
# Preserve reference to vae for later checks
vae = None
# TODO: Try unloading tokenizers here?
del tokenizer
if tokenizer_two is not None:
del tokenizer_two
tokenizer = None
tokenizer2 = None
if status.interrupted:
result.msg = "Training interrupted."
stop_profiler(profiler)
return result
if train_dataset.__len__ == 0:
msg = "Please provide a directory with actual images in it."
logger.warning(msg)
status.textinfo = msg
update_status({"status": status})
cleanup_memory()
result.msg = msg
result.config = args
stop_profiler(profiler)
return result
def collate_fn_db(examples):
input_ids = [example["input_ids"] for example in examples]
pixel_values = [example["image"] for example in examples]
types = [example["is_class"] for example in examples]
weights = [
current_prior_loss_weight if example["is_class"] else 1.0
for example in examples
]
loss_avg = 0
for weight in weights:
loss_avg += weight
loss_avg /= len(weights)
pixel_values = torch.stack(pixel_values)
if not args.cache_latents:
pixel_values = pixel_values.to(
memory_format=torch.contiguous_format
).float()
input_ids = torch.cat(input_ids, dim=0)
batch_data = {
"input_ids": input_ids,
"images": pixel_values,
"types": types,
"loss_avg": loss_avg,
}
if "input_ids2" in examples[0]:
input_ids_2 = [example["input_ids2"] for example in examples]
input_ids_2 = torch.stack(input_ids_2)
batch_data["input_ids2"] = input_ids_2
batch_data["original_sizes_hw"] = torch.stack(
[torch.LongTensor(x["original_sizes_hw"]) for x in examples])
batch_data["crop_top_lefts"] = torch.stack(
[torch.LongTensor(x["crop_top_lefts"]) for x in examples])
batch_data["target_sizes_hw"] = torch.stack(
[torch.LongTensor(x["target_sizes_hw"]) for x in examples])
return batch_data
def collate_fn_sdxl(examples):
input_ids = [example["input_ids"] for example in examples if not example["is_class"]]
pixel_values = [example["image"] for example in examples if not example["is_class"]]
add_text_embeds = [example["instance_added_cond_kwargs"]["text_embeds"] for example in examples if
not example["is_class"]]
add_time_ids = [example["instance_added_cond_kwargs"]["time_ids"] for example in examples if
not example["is_class"]]
# Concat class and instance examples for prior preservation.
# We do this to avoid doing two forward passes.
if with_prior_preservation:
input_ids += [example["input_ids"] for example in examples if example["is_class"]]
pixel_values += [example["image"] for example in examples if example["is_class"]]
add_text_embeds += [example["instance_added_cond_kwargs"]["text_embeds"] for example in examples if
example["is_class"]]
add_time_ids += [example["instance_added_cond_kwargs"]["time_ids"] for example in examples if
example["is_class"]]
pixel_values = torch.stack(pixel_values)
pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float()
input_ids = torch.cat(input_ids, dim=0)
add_text_embeds = torch.cat(add_text_embeds, dim=0)
add_time_ids = torch.cat(add_time_ids, dim=0)
batch = {
"input_ids": input_ids,
"images": pixel_values,
"unet_added_conditions": {"text_embeds": add_text_embeds, "time_ids": add_time_ids},
}
return batch
sampler = BucketSampler(train_dataset, train_batch_size)
collate_fn = collate_fn_db
if args.model_type == "SDXL":
collate_fn = collate_fn_sdxl
train_dataloader = torch.utils.data.DataLoader(
train_dataset,
batch_size=1,
batch_sampler=sampler,
collate_fn=collate_fn,
num_workers=n_workers,
)
max_train_steps = args.num_train_epochs * len(train_dataset)
# This is separate, because optimizer.step is only called once per "step" in training, so it's not
# affected by batch size
sched_train_steps = args.num_train_epochs * train_dataset.num_train_images
lr_scale_pos = args.lr_scale_pos
if class_prompts:
lr_scale_pos *= 2
lr_scheduler = UniversalScheduler(
name=args.lr_scheduler,
optimizer=optimizer,
num_warmup_steps=args.lr_warmup_steps,
total_training_steps=sched_train_steps,
min_lr=args.learning_rate_min,
total_epochs=args.num_train_epochs,
num_cycles=args.lr_cycles,
power=args.lr_power,
factor=args.lr_factor,
scale_pos=lr_scale_pos,
unet_lr=learning_rate,
tenc_lr=txt_learning_rate,
)
# create ema, fix OOM
if args.use_ema:
if stop_text_percentage != 0:
(
ema_model.model,
unet,
text_encoder,
optimizer,
train_dataloader,
lr_scheduler,
) = accelerator.prepare(
ema_model.model,
unet,
text_encoder,
optimizer,
train_dataloader,
lr_scheduler,
)
else:
(
ema_model.model,
unet,
optimizer,
train_dataloader,
lr_scheduler,
) = accelerator.prepare(
ema_model.model, unet, optimizer, train_dataloader, lr_scheduler
)
else:
if stop_text_percentage != 0:
(
unet,
text_encoder,
optimizer,
train_dataloader,
lr_scheduler,
) = accelerator.prepare(
unet, text_encoder, optimizer, train_dataloader, lr_scheduler
)
else:
unet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
unet, optimizer, train_dataloader, lr_scheduler
)
if not args.cache_latents and vae is not None:
vae.to(accelerator.device, dtype=weight_dtype)
if stop_text_percentage == 0:
text_encoder.to(accelerator.device, dtype=weight_dtype)
# Afterwards we recalculate our number of training epochs
# We need to initialize the trackers we use, and also store our configuration.
# The trackers will initialize automatically on the main process.
if accelerator.is_main_process:
accelerator.init_trackers("dreambooth")
# Train!
total_batch_size = (
train_batch_size * accelerator.num_processes * gradient_accumulation_steps
)
max_train_epochs = args.num_train_epochs
# we calculate our number of tenc training epochs
text_encoder_epochs = round(max_train_epochs * stop_text_percentage)
global_step = 0
global_epoch = 0
session_epoch = 0
first_epoch = 0
resume_step = 0
last_model_save = 0
last_image_save = 0
resume_from_checkpoint = False
new_hotness = os.path.join(
args.model_dir, "checkpoints", f"checkpoint-{args.snapshot}"
)
if os.path.exists(new_hotness):
logger.debug(f"Resuming from checkpoint {new_hotness}")
try:
import modules.shared
no_safe = modules.shared.cmd_opts.disable_safe_unpickle
modules.shared.cmd_opts.disable_safe_unpickle = True
except:
no_safe = False
try:
import modules.shared
accelerator.load_state(new_hotness)
modules.shared.cmd_opts.disable_safe_unpickle = no_safe
global_step = resume_step = args.revision
resume_from_checkpoint = True
first_epoch = args.lifetime_epoch
global_epoch = args.lifetime_epoch
except Exception as lex:
logger.warning(f"Exception loading checkpoint: {lex}")
logger.debug(" ***** Running training *****")
if shared.force_cpu:
logger.debug(f" TRAINING WITH CPU ONLY")
logger.debug(f" Num batches each epoch = {len(train_dataset) // train_batch_size}")
logger.debug(f" Num Epochs = {max_train_epochs}")
logger.debug(f" Batch Size Per Device = {train_batch_size}")
logger.debug(f" Gradient Accumulation steps = {gradient_accumulation_steps}")
logger.debug(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
logger.debug(f" Text Encoder Epochs: {text_encoder_epochs}")
logger.debug(f" Total optimization steps = {sched_train_steps}")
logger.debug(f" Total training steps = {max_train_steps}")
logger.debug(f" Resuming from checkpoint: {resume_from_checkpoint}")
logger.debug(f" First resume epoch: {first_epoch}")
logger.debug(f" First resume step: {resume_step}")
logger.debug(f" Lora: {args.use_lora}, Optimizer: {args.optimizer}, Prec: {precision}")
logger.debug(f" Gradient Checkpointing: {args.gradient_checkpointing}")
logger.debug(f" EMA: {args.use_ema}")
logger.debug(f" UNET: {args.train_unet}")
logger.debug(f" Freeze CLIP Normalization Layers: {args.freeze_clip_normalization}")
logger.debug(f" LR{' (Lora)' if args.use_lora else ''}: {learning_rate}")
if stop_text_percentage > 0:
logger.debug(f" Tenc LR{' (Lora)' if args.use_lora else ''}: {txt_learning_rate}")
logger.debug(f" V2: {args.v2}")
os.environ.__setattr__("CUDA_LAUNCH_BLOCKING", 1)
def check_save(is_epoch_check=False):
nonlocal last_model_save
nonlocal last_image_save
save_model_interval = args.save_embedding_every
save_image_interval = args.save_preview_every
save_completed = session_epoch >= max_train_epochs
save_canceled = status.interrupted
save_image = False
save_model = False
save_lora = False
if not save_canceled and not save_completed:
# Check to see if the number of epochs since last save is gt the interval
if 0 < save_model_interval <= session_epoch - last_model_save:
save_model = True
if args.use_lora:
save_lora = True
last_model_save = session_epoch
# Repeat for sample images
if 0 < save_image_interval <= session_epoch - last_image_save:
save_image = True
last_image_save = session_epoch
else:
logger.debug("\nSave completed/canceled.")
if global_step > 0:
save_image = True
save_model = True
if args.use_lora:
save_lora = True
save_snapshot = False
if is_epoch_check:
if shared.status.do_save_samples:
save_image = True
shared.status.do_save_samples = False
if shared.status.do_save_model:
if args.use_lora:
save_lora = True
save_model = True
shared.status.do_save_model = False
save_checkpoint = False
if save_model:
if save_canceled:
if global_step > 0: