forked from kohya-ss/sd-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain_dualnetwork.py
1361 lines (1184 loc) · 66.5 KB
/
train_dualnetwork.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
# import importlib
# import argparse
# import gc
# import math
# import os
# import random
# import time
# import json
# from importlib_metadata import metadata
# from tqdm import tqdm
# import torch
# from accelerate import Accelerator
# from accelerate.utils import set_seed
# import diffusers
# from diffusers import DDPMScheduler
# from torch.utils.tensorboard import SummaryWriter
# import library.train_util as train_util
# from library.train_util import DreamBoothDataset, FineTuningDataset
from torch.nn.parallel import DistributedDataParallel as DDP
import importlib
import argparse
import gc
import math
import os
import random
import time
import json
import toml
from multiprocessing import Value
from tqdm import tqdm
import torch
from accelerate import Accelerator
from accelerate.utils import set_seed
from diffusers import DDPMScheduler
from torch.utils.tensorboard import SummaryWriter
import library.train_util as train_util
from library.train_util import (
DreamBoothDataset,
)
import library.config_util as config_util
from library.config_util import (
ConfigSanitizer,
BlueprintGenerator,
)
import library.custom_train_functions as custom_train_functions
from library.custom_train_functions import apply_snr_weight
"""
temp config place
"""
train_data_dir_2 = "/home/chenkaizheng/data/diffusion_data/dreambooth_3/lora_data/with_tag/nohead_jiaocha_newnew"
reg_data_dir_2 = ""
logging_dir_2 = "log_locon2"
log_prefix_2 = ""
kld_weight_value = 0.000005 # 还是偏大
model_path_2 = "/home/chenkaizheng/codes/vscode/waifu/webui_new/stable-diffusion-webui/models/Stable-diffusion/v1-5-pruned-emaonly.ckpt"
resolution = "512,512"
network_dim = 64
network_alpha = 64
network_module = "networks.lora"
ANNEAL_EPOCH = 16 # 15轮前进行正常训练
def collate_fn(examples):
return examples[0]
# def generate_step_logs(args: argparse.Namespace, current_loss, avr_loss, lr_scheduler):
# logs = {"loss/current": current_loss, "loss/average": avr_loss}
# if args.network_train_unet_only:
# logs["lr/unet"] = lr_scheduler.get_last_lr()[0]
# elif args.network_train_text_encoder_only:
# logs["lr/textencoder"] = lr_scheduler.get_last_lr()[0]
# else:
# logs["lr/textencoder"] = lr_scheduler.get_last_lr()[0]
# logs["lr/unet"] = lr_scheduler.get_last_lr()[-1] # may be same to textencoder
# return logs
# TODO 他のスクリプトと共通化する
def generate_step_logs(args: argparse.Namespace, current_loss, avr_loss, lr_scheduler):
logs = {"loss/current": current_loss, "loss/average": avr_loss}
if args.network_train_unet_only:
logs["lr/unet"] = float(lr_scheduler.get_last_lr()[0])
elif args.network_train_text_encoder_only:
logs["lr/textencoder"] = float(lr_scheduler.get_last_lr()[0])
else:
logs["lr/textencoder"] = float(lr_scheduler.get_last_lr()[0])
logs["lr/unet"] = float(lr_scheduler.get_last_lr()[-1]) # may be same to textencoder
if args.optimizer_type.lower() == "DAdaptation".lower(): # tracking d*lr value of unet.
logs["lr/d*lr"] = lr_scheduler.optimizers[-1].param_groups[0]["d"] * lr_scheduler.optimizers[-1].param_groups[0]["lr"]
return logs
def prepare_accelerator(args: argparse.Namespace):
if args.logging_dir_2 is None:
log_with = None
logging_dir = None
else:
log_with = "tensorboard"
log_prefix = "" if args.log_prefix_2 is None else args.log_prefix_2
logging_dir = args.logging_dir_2 + "/" + log_prefix + time.strftime('%Y%m%d%H%M%S', time.localtime())
accelerator = Accelerator(gradient_accumulation_steps=args.gradient_accumulation_steps, mixed_precision=args.mixed_precision,
log_with=log_with, logging_dir=logging_dir)
# accelerateの互換性問題を解決する
accelerator_0_15 = True
try:
accelerator.unwrap_model("dummy", True)
print("Using accelerator 0.15.0 or above.")
except TypeError:
accelerator_0_15 = False
def unwrap_model(model):
if accelerator_0_15:
return accelerator.unwrap_model(model, True)
return accelerator.unwrap_model(model)
return accelerator, unwrap_model
# Monkeypatch newer get_scheduler() function overridng current version of diffusers.optimizer.get_scheduler
# code is taken from https://github.com/huggingface/diffusers diffusers.optimizer, commit d87cc15977b87160c30abaace3894e802ad9e1e6
# Which is a newer release of diffusers than currently packaged with sd-scripts
# This code can be removed when newer diffusers version (v0.12.1 or greater) is tested and implemented to sd-scripts
from typing import Optional, Union
from torch.optim import Optimizer
from diffusers.optimization import SchedulerType, TYPE_TO_SCHEDULER_FUNCTION
def get_scheduler_fix(
name: Union[str, SchedulerType],
optimizer: Optimizer,
num_warmup_steps: Optional[int] = None,
num_training_steps: Optional[int] = None,
num_cycles: int = 1,
power: float = 1.0,
):
"""
Unified API to get any scheduler from its name.
Args:
name (`str` or `SchedulerType`):
The name of the scheduler to use.
optimizer (`torch.optim.Optimizer`):
The optimizer that will be used during training.
num_warmup_steps (`int`, *optional*):
The number of warmup steps to do. This is not required by all schedulers (hence the argument being
optional), the function will raise an error if it's unset and the scheduler type requires it.
num_training_steps (`int``, *optional*):
The number of training steps to do. This is not required by all schedulers (hence the argument being
optional), the function will raise an error if it's unset and the scheduler type requires it.
num_cycles (`int`, *optional*):
The number of hard restarts used in `COSINE_WITH_RESTARTS` scheduler.
power (`float`, *optional*, defaults to 1.0):
Power factor. See `POLYNOMIAL` scheduler
last_epoch (`int`, *optional*, defaults to -1):
The index of the last epoch when resuming training.
"""
name = SchedulerType(name)
schedule_func = TYPE_TO_SCHEDULER_FUNCTION[name]
if name == SchedulerType.CONSTANT:
return schedule_func(optimizer)
# All other schedulers require `num_warmup_steps`
if num_warmup_steps is None:
raise ValueError(f"{name} requires `num_warmup_steps`, please provide that argument.")
if name == SchedulerType.CONSTANT_WITH_WARMUP:
return schedule_func(optimizer, num_warmup_steps=num_warmup_steps)
# All other schedulers require `num_training_steps`
if num_training_steps is None:
raise ValueError(f"{name} requires `num_training_steps`, please provide that argument.")
if name == SchedulerType.COSINE_WITH_RESTARTS:
return schedule_func(
optimizer, num_warmup_steps=num_warmup_steps, num_training_steps=num_training_steps, num_cycles=num_cycles
)
if name == SchedulerType.POLYNOMIAL:
return schedule_func(
optimizer, num_warmup_steps=num_warmup_steps, num_training_steps=num_training_steps, power=power
)
return schedule_func(optimizer, num_warmup_steps=num_warmup_steps, num_training_steps=num_training_steps)
def train(args):
# 初始化summary_writer
locon_writer = SummaryWriter(log_dir='./log_dual_lora')
# todo 是否重建session id
session_id = random.randint(0, 2**32)
training_started_at = time.time()
train_util.verify_training_args(args)
train_util.prepare_dataset_args(args, True)
cache_latents = args.cache_latents
use_dreambooth_method = args.in_json is None
use_user_config = args.dataset_config is not None
if args.seed is not None:
set_seed(args.seed)
# 准备两个tokenizer
tokenizer1 = train_util.load_tokenizer(args)
tokenizer2 = train_util.load_tokenizer(args)
# データセットを準備する
blueprint_generator_1 = BlueprintGenerator(ConfigSanitizer(True, True, True))
blueprint_generator_2 = BlueprintGenerator(ConfigSanitizer(True, True, True))
# TODO:暂时不需要
if use_user_config:
print(f"Load dataset config from {args.dataset_config}")
user_config = config_util.load_user_config(args.dataset_config)
ignored = ["train_data_dir", "reg_data_dir", "in_json"]
if any(getattr(args, attr) is not None for attr in ignored):
print(
"ignore following options because config file is found: {0} / 設定ファイルが利用されるため以下のオプションは無視されます: {0}".format(
", ".join(ignored)
)
)
else:
if use_dreambooth_method:
print("Use DreamBooth method.")
user_config_1 = {
"datasets": [
{"subsets": config_util.generate_dreambooth_subsets_config_by_subdirs(args.train_data_dir, args.reg_data_dir)}
]
}
user_config_2 = {
"datasets": [
{"subsets": config_util.generate_dreambooth_subsets_config_by_subdirs(args.train_data_dir_2, args.reg_data_dir_2)}
]
}
else:
print("Train with captions.")
user_config = {
"datasets": [
{
"subsets": [
{
"image_dir": args.train_data_dir,
"metadata_file": args.in_json,
}
]
}
]
}
blueprint_1 = blueprint_generator_1.generate(user_config_1, args, tokenizer=tokenizer1)
train_dataset_group_1 = config_util.generate_dataset_group_by_blueprint(blueprint_1.dataset_group)
blueprint_2 = blueprint_generator_2.generate(user_config_2, args, tokenizer=tokenizer2)
train_dataset_group_2 = config_util.generate_dataset_group_by_blueprint(blueprint_2.dataset_group)
current_epoch = Value('i',0)
current_step = Value('i',0)
ds_for_collater_1 = train_dataset_group_1 if args.max_data_loader_n_workers == 0 else None
collater_1 = train_util.collater_class(current_epoch,current_step, ds_for_collater_1)
ds_for_collater_2 = train_dataset_group_2 if args.max_data_loader_n_workers == 0 else None
collater_2 = train_util.collater_class(current_epoch,current_step, ds_for_collater_2)
# if use_dreambooth_method:
# print("Use DreamBooth method.")
# train_dataset_1 = DreamBoothDataset(args.train_batch_size, args.train_data_dir, args.reg_data_dir,
# tokenizer1, args.max_token_length, args.caption_extension, args.shuffle_caption, args.keep_tokens,
# args.resolution, args.enable_bucket, args.min_bucket_reso, args.max_bucket_reso, args.prior_loss_weight,
# args.flip_aug, args.color_aug, args.face_crop_aug_range, args.random_crop, args.debug_dataset)
# train_dataset_2 = DreamBoothDataset(args.train_batch_size, train_data_dir_2, reg_data_dir_2,
# tokenizer2, args.max_token_length, args.caption_extension, args.shuffle_caption, args.keep_tokens,
# args.resolution, args.enable_bucket, args.min_bucket_reso, args.max_bucket_reso, args.prior_loss_weight,
# args.flip_aug, args.color_aug, args.face_crop_aug_range, args.random_crop, args.debug_dataset)
# else:
# print("Train with captions.")
# train_dataset_1 = FineTuningDataset(args.in_json, args.train_batch_size, args.train_data_dir,
# tokenizer1, args.max_token_length, args.shuffle_caption, args.keep_tokens,
# args.resolution, args.enable_bucket, args.min_bucket_reso, args.max_bucket_reso,
# args.flip_aug, args.color_aug, args.face_crop_aug_range, args.random_crop,
# args.dataset_repeats, args.debug_dataset)
# train_dataset_2 = FineTuningDataset(args.in_json, args.train_batch_size, train_data_dir_2,
# tokenizer2, args.max_token_length, args.shuffle_caption, args.keep_tokens,
# args.resolution, args.enable_bucket, args.min_bucket_reso, args.max_bucket_reso,
# args.flip_aug, args.color_aug, args.face_crop_aug_range, args.random_crop,
# args.dataset_repeats, args.debug_dataset)
# train_dataset_1.make_buckets()
# train_dataset_2.make_buckets()
# if args.debug_dataset:
# train_util.debug_dataset(train_dataset_1)
# return
# if len(train_dataset_1) == 0:
# print("No data found in dataset1. Please verify arguments / 画像がありません。引数指定を確認してください")
# return
# if len(train_dataset_2) == 0:
# print("No data found in dataset2. Please verify arguments / 画像がありません。引数指定を確認してください")
# return
if args.debug_dataset:
train_util.debug_dataset(train_dataset_group_1)
train_util.debug_dataset(train_dataset_group_2)
return
if len(train_dataset_group_1) == 0:
print(
"No data found. Please verify arguments (train_data_dir must be the parent of folders with images) / 画像がありません。引数指定を確認してください(train_data_dirには画像があるフォルダではなく、画像があるフォルダの親フォルダを指定する必要があります)"
)
return
if len(train_dataset_group_2) == 0:
print(
"No data found. Please verify arguments (train_data_dir_2 must be the parent of folders with images) / 画像がありません。引数指定を確認してください(train_data_dirには画像があるフォルダではなく、画像があるフォルダの親フォルダを指定する必要があります)"
)
return
if cache_latents:
assert (
train_dataset_group_1.is_latent_cacheable()
), "when caching latents, either color_aug or random_crop cannot be used / latentをキャッシュするときはcolor_augとrandom_cropは使えません"
assert (
train_dataset_group_2.is_latent_cacheable()
), "when caching latents, either color_aug or random_crop cannot be used / latentをキャッシュするときはcolor_augとrandom_cropは使えません"
# acceleratorを準備する
print("prepare accelerator")
accelerator_1, unwrap_model_1 = train_util.prepare_accelerator(args)
accelerator_2, unwrap_model_2 = prepare_accelerator(args)
is_main_process = accelerator_2.is_main_process
# mixed precisionに対応した型を用意しておき適宜castする
# 可以共用
weight_dtype, save_dtype = train_util.prepare_dtype(args)
# モデルを読み込む
# 分别读取模型
text_encoder_1, vae_1, unet_1, _ = train_util.load_target_model(args, weight_dtype)
text_encoder_2, vae_2, unet_2, _ = train_util.load_target_model(args, weight_dtype)
# モデルに xformers とか memory efficient attention を組み込む
train_util.replace_unet_modules(unet_1, args.mem_eff_attn, args.xformers)
train_util.replace_unet_modules(unet_2, args.mem_eff_attn, args.xformers)
# 学習を準備する
if cache_latents:
vae_1.to(accelerator_1.device, dtype=weight_dtype)
vae_1.requires_grad_(False)
vae_1.eval()
with torch.no_grad():
train_dataset_group_1.cache_latents(vae_1)
vae_1.to("cpu")
if torch.cuda.is_available():
torch.cuda.empty_cache()
# vae原则上可以公用
# vae_2.to(accelerator.device, dtype=weight_dtype)
# vae_2.requires_grad_(False)
# vae_2.eval()
# with torch.no_grad():
# train_dataset_1.cache_latents(vae_1)
# vae_2.to("cpu")
# if torch.cuda.is_available():
# torch.cuda.empty_cache()
gc.collect()
# prepare network
print("import network module:", args.network_module)
# can be used publicly
network_module = importlib.import_module(args.network_module)
net_kwargs = {}
if args.network_args is not None:
for net_arg in args.network_args:
key, value = net_arg.split('=')
net_kwargs[key] = value
# if a new network is added in future, add if ~ then blocks for each network (;'∀')
# 创建了两个lora
network_1 = network_module.create_network(1.0, args.network_dim, args.network_alpha, vae_1, text_encoder_1, unet_1, **net_kwargs)
network_2 = network_module.create_network(1.0, args.network_dim, args.network_alpha, vae_1, text_encoder_2, unet_2, **net_kwargs)
if network_1 is None:
return
# 选择加载模型,目前先不整这个
# 将network_1设置为冻结模型
if args.network_weights is not None:
print("load network weights from:", args.network_weights)
network_1.load_weights(args.network_weights)
train_unet = not args.network_train_text_encoder_only
train_text_encoder = not args.network_train_unet_only
network_1.apply_to(text_encoder_1, unet_1, train_text_encoder, train_unet)
network_2.apply_to(text_encoder_2, unet_2, train_text_encoder, train_unet)
if args.gradient_checkpointing:
unet_1.enable_gradient_checkpointing()
text_encoder_1.gradient_checkpointing_enable()
network_1.enable_gradient_checkpointing() # may have no effect
unet_2.enable_gradient_checkpointing()
text_encoder_2.gradient_checkpointing_enable()
network_2.enable_gradient_checkpointing()
# 学習に必要なクラスを準備する
print("prepare optimizer, data loader etc.")
# 8-bit Adamを使う
if args.use_8bit_adam:
try:
import bitsandbytes as bnb
except ImportError:
raise ImportError("No bitsand bytes / bitsandbytesがインストールされていないようです")
print("use 8-bit Adam optimizer")
optimizer_class = bnb.optim.AdamW8bit
else:
optimizer_class = torch.optim.AdamW
trainable_params_1 = network_1.prepare_optimizer_params(args.text_encoder_lr, args.unet_lr)
trainable_params_2 = network_2.prepare_optimizer_params(args.text_encoder_lr, args.unet_lr)
optimizer_name_1, optimizer_args_1, optimizer_1 = train_util.get_optimizer(args, trainable_params_1)
optimizer_name_2, optimizer_args_2, optimizer_2 = train_util.get_optimizer(args, trainable_params_2)
# dataloaderを準備する
# DataLoaderのプロセス数:0はメインプロセスになる
n_workers = min(args.max_data_loader_n_workers, os.cpu_count() - 1) # cpu_count-1 ただし最大で指定された数まで
train_dataloader_1 = torch.utils.data.DataLoader(
train_dataset_group_1,
batch_size=1,
shuffle=False,
collate_fn=collater_1,
num_workers=n_workers,
persistent_workers=args.persistent_data_loader_workers
)
train_dataloader_2 = torch.utils.data.DataLoader(
train_dataset_group_2,
batch_size=1,
shuffle=False,
collate_fn=collater_2,
num_workers=n_workers,
persistent_workers=args.persistent_data_loader_workers
)
# 学習ステップ数を計算する
if args.max_train_epochs is not None:
# args.max_train_steps = args.max_train_epochs * len(train_dataloader_1)
# print(f"override steps. steps for {args.max_train_epochs} epochs is / 指定エポックまでのステップ数: {args.max_train_steps}")
args.max_train_steps = args.max_train_epochs * math.ceil(len(train_dataloader_1) / accelerator_1.num_processes / args.gradient_accumulation_steps)
if is_main_process:
print(f"override steps. steps for {args.max_train_epochs} epochs is / 指定エポックまでのステップ数: {args.max_train_steps}")
# lr schedulerを用意する
# lr_scheduler = diffusers.optimization.get_scheduler(
# 看起来感觉可以共用
# 啊啊啊,并不能共用
# lr_scheduler_1 = get_scheduler_fix(
# args.lr_scheduler, optimizer_1, num_warmup_steps=args.lr_warmup_steps,
# num_training_steps=args.max_train_steps * args.gradient_accumulation_steps,
# num_cycles=args.lr_scheduler_num_cycles, power=args.lr_scheduler_power)
# lr_scheduler_2 = get_scheduler_fix(
# args.lr_scheduler, optimizer_2, num_warmup_steps=args.lr_warmup_steps,
# num_training_steps=args.max_train_steps * args.gradient_accumulation_steps,
# num_cycles=args.lr_scheduler_num_cycles, power=args.lr_scheduler_power)
lr_scheduler_1 = train_util.get_scheduler_fix(args, optimizer_1, accelerator_1.num_processes)
lr_scheduler_2 = train_util.get_scheduler_fix(args, optimizer_2, accelerator_2.num_processes)
# 実験的機能:勾配も含めたfp16学習を行う モデル全体をfp16にする
if args.full_fp16:
assert args.mixed_precision == "fp16", "full_fp16 requires mixed precision='fp16' / full_fp16を使う場合はmixed_precision='fp16'を指定してください。"
print("enable full fp16 training.")
network_1.to(weight_dtype)
network_2.to(weight_dtype)
# acceleratorがなんかよろしくやってくれるらしい
if train_unet and train_text_encoder:
unet_1, text_encoder_1, network_1, optimizer_1, train_dataloader_1, lr_scheduler_1 = accelerator_1.prepare(
unet_1, text_encoder_1, network_1, optimizer_1, train_dataloader_1, lr_scheduler_1)
unet_2, text_encoder_2, network_2, optimizer_2, train_dataloader_2, lr_scheduler_2 = accelerator_2.prepare(
unet_2, text_encoder_2, network_2, optimizer_2, train_dataloader_2, lr_scheduler_2)
elif train_unet:
unet_1, network_1, optimizer_1, train_dataloader_1, lr_scheduler_1 = accelerator_1.prepare(
unet_1, network_1, optimizer_1, train_dataloader_1, lr_scheduler_1)
unet_2, network_2, optimizer_2, train_dataloader_2, lr_scheduler_2 = accelerator_2.prepare(
unet_2, network_2, optimizer_2, train_dataloader_2, lr_scheduler_2)
elif train_text_encoder:
text_encoder_1, network_1, optimizer_1, train_dataloader_1, lr_scheduler_1 = accelerator_1.prepare(
text_encoder_1, network_1, optimizer_1, train_dataloader_1, lr_scheduler_1)
text_encoder_2, network_2, optimizer_2, train_dataloader_2, lr_scheduler_2 = accelerator_2.prepare(
text_encoder_2, network_2, optimizer_2, train_dataloader_2, lr_scheduler_2)
else:
network_1, optimizer_1, train_dataloader_1, lr_scheduler_1 = accelerator_1.prepare(
network_1, optimizer_1, train_dataloader_1, lr_scheduler_1)
network_2, optimizer_2, train_dataloader_2, lr_scheduler_2 = accelerator_2.prepare(
network_2, optimizer_2, train_dataloader_2, lr_scheduler_2)
# 将网络固定住
unet_1.requires_grad_(False)
unet_1.to(accelerator_1.device, dtype=weight_dtype)
unet_2.requires_grad_(False)
unet_2.to(accelerator_2.device, dtype=weight_dtype)
text_encoder_1.requires_grad_(False)
text_encoder_1.to(accelerator_1.device, dtype=weight_dtype)
text_encoder_2.requires_grad_(False)
text_encoder_2.to(accelerator_2.device, dtype=weight_dtype)
if args.gradient_checkpointing: # according to TI example in Diffusers, train is required
unet_1.train()
text_encoder_1.train()
unet_2.train()
text_encoder_2.train()
# set top parameter requires_grad = True for gradient checkpointing works
if type(text_encoder_1) == DDP:
text_encoder_1.module.text_model.embeddings.requires_grad_(True)
else:
text_encoder_1.text_model.embeddings.requires_grad_(True)
# text_encoder_1.text_model.embeddings.requires_grad_(True)
# text_encoder_2.text_model.embeddings.requires_grad_(True)
if type(text_encoder_2) == DDP:
text_encoder_2.module.text_model.embeddings.requires_grad_(True)
else:
text_encoder_2.text_model.embeddings.requires_grad_(True)
else:
unet_1.eval()
unet_2.eval()
text_encoder_1.eval()
text_encoder_2.eval()
# support DistributedDataParallel
if type(text_encoder_1) == DDP:
text_encoder_1 = text_encoder_1.module
unet_1 = unet_1.module
network_1 = network_1.module
if type(text_encoder_2) == DDP:
text_encoder_2 = text_encoder_2.module
unet_2 = unet_2.module
network_2 = network_2.module
network_1.prepare_grad_etc(text_encoder_1, unet_1)
network_2.prepare_grad_etc(text_encoder_2, unet_2)
if not cache_latents:
# 原则上vae可以共用
vae_1.requires_grad_(False)
vae_1.eval()
vae_1.to(accelerator_1.device, dtype=weight_dtype)
# vae_2.requires_grad_(False)
# vae_2.eval()
# vae_2.to(accelerator_2.device, dtype=weight_dtype)
# 実験的機能:勾配も含めたfp16学習を行う PyTorchにパッチを当ててfp16でのgrad scaleを有効にする
if args.full_fp16:
train_util.patch_accelerator_for_fp16_training(accelerator_1)
train_util.patch_accelerator_for_fp16_training(accelerator_2)
# resumeする
if args.resume is not None:
print(f"resume training from state: {args.resume}")
accelerator_1.load_state(args.resume)
accelerator_2.load_state(args.resume)
# epoch数を計算する
# 软限定,两个训练模型的图片数量需要一致,这样的话此参数可以共用
num_update_steps_per_epoch = math.ceil(len(train_dataloader_1) / args.gradient_accumulation_steps)
num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
if (args.save_n_epoch_ratio is not None) and (args.save_n_epoch_ratio > 0):
args.save_every_n_epochs = math.floor(num_train_epochs / args.save_n_epoch_ratio) or 1
# 学習する
total_batch_size = args.train_batch_size * accelerator_1.num_processes * args.gradient_accumulation_steps
# print("running training / 学習開始")
# print(f" num train images * repeats / 学習画像の数×繰り返し回数: {train_dataset_group_1.num_train_images}")
# print(f" num reg images / 正則化画像の数: {train_dataset_group_2.num_reg_images}")
# print(f" num batches per epoch / 1epochのバッチ数: {len(train_dataloader_1)}")
# print(f" num epochs / epoch数: {num_train_epochs}")
# print(f" net2 num train images * repeats / 学習画像の数×繰り返し回数: {train_dataset_group_2.num_train_images}")
# print(f" net2 num reg images / 正則化画像の数: {train_dataset_group_2.num_reg_images}")
# print(f" net2 num batches per epoch / 1epochのバッチ数: {len(train_dataloader_2)}")
# print(f" net2 num epochs / epoch数: {num_train_epochs}")
# print(f" batch size per device / バッチサイズ: {args.train_batch_size}")
# print(f" total train batch size (with parallel & distributed & accumulation) / 総バッチサイズ(並列学習、勾配合計含む): {total_batch_size}")
# print(f" gradient accumulation steps / 勾配を合計するステップ数 = {args.gradient_accumulation_steps}")
# print(f" total optimization steps / 学習ステップ数: {args.max_train_steps}")
# metadata_1 = {
# "ss_session_id": session_id, # random integer indicating which group of epochs the model came from
# "ss_training_started_at": training_started_at, # unix timestamp
# "ss_output_name": args.output_name,
# "ss_learning_rate": args.learning_rate,
# "ss_text_encoder_lr": args.text_encoder_lr,
# "ss_unet_lr": args.unet_lr,
# "ss_num_train_images": train_dataset_group_1.num_train_images, # includes repeating
# "ss_num_reg_images": train_dataset_group_1.num_reg_images,
# "ss_num_batches_per_epoch": len(train_dataloader_1),
# "ss_num_epochs": num_train_epochs,
# "ss_batch_size_per_device": args.train_batch_size,
# "ss_total_batch_size": total_batch_size,
# "ss_gradient_checkpointing": args.gradient_checkpointing,
# "ss_gradient_accumulation_steps": args.gradient_accumulation_steps,
# "ss_max_train_steps": args.max_train_steps,
# "ss_lr_warmup_steps": args.lr_warmup_steps,
# "ss_lr_scheduler": args.lr_scheduler,
# "ss_network_module": args.network_module,
# "ss_network_dim": args.network_dim, # None means default because another network than LoRA may have another default dim
# "ss_network_alpha": args.network_alpha, # some networks may not use this value
# "ss_mixed_precision": args.mixed_precision,
# "ss_full_fp16": bool(args.full_fp16),
# "ss_v2": bool(args.v2),
# "ss_resolution": args.resolution,
# "ss_clip_skip": args.clip_skip,
# "ss_max_token_length": args.max_token_length,
# "ss_color_aug": bool(args.color_aug),
# "ss_flip_aug": bool(args.flip_aug),
# "ss_random_crop": bool(args.random_crop),
# "ss_shuffle_caption": bool(args.shuffle_caption),
# "ss_cache_latents": bool(args.cache_latents),
# "ss_enable_bucket": bool(train_dataset_group_1.enable_bucket),
# "ss_min_bucket_reso": train_dataset_group_1.min_bucket_reso,
# "ss_max_bucket_reso": train_dataset_group_1.max_bucket_reso,
# "ss_seed": args.seed,
# "ss_keep_tokens": args.keep_tokens,
# "ss_dataset_dirs": json.dumps(train_dataset_group_1.dataset_dirs_info),
# "ss_reg_dataset_dirs": json.dumps(train_dataset_group_1.reg_dataset_dirs_info),
# "ss_bucket_info": json.dumps(train_dataset_group_1.bucket_info),
# "ss_training_comment": args.training_comment # will not be updated after training
# }
# metadata_2 = {
# "ss_session_id": session_id, # random integer indicating which group of epochs the model came from
# "ss_training_started_at": training_started_at, # unix timestamp
# "ss_output_name": args.output_name,
# "ss_learning_rate": args.learning_rate,
# "ss_text_encoder_lr": args.text_encoder_lr,
# "ss_unet_lr": args.unet_lr,
# "ss_num_train_images": train_dataset_group_2.num_train_images, # includes repeating
# "ss_num_reg_images": train_dataset_group_2.num_reg_images,
# "ss_num_batches_per_epoch": len(train_dataloader_2),
# "ss_num_epochs": num_train_epochs,
# "ss_batch_size_per_device": args.train_batch_size,
# "ss_total_batch_size": total_batch_size,
# "ss_gradient_checkpointing": args.gradient_checkpointing,
# "ss_gradient_accumulation_steps": args.gradient_accumulation_steps,
# "ss_max_train_steps": args.max_train_steps,
# "ss_lr_warmup_steps": args.lr_warmup_steps,
# "ss_lr_scheduler": args.lr_scheduler,
# "ss_network_module": args.network_module,
# "ss_network_dim": args.network_dim, # None means default because another network than LoRA may have another default dim
# "ss_network_alpha": args.network_alpha, # some networks may not use this value
# "ss_mixed_precision": args.mixed_precision,
# "ss_full_fp16": bool(args.full_fp16),
# "ss_v2": bool(args.v2),
# "ss_resolution": args.resolution,
# "ss_clip_skip": args.clip_skip,
# "ss_max_token_length": args.max_token_length,
# "ss_color_aug": bool(args.color_aug),
# "ss_flip_aug": bool(args.flip_aug),
# "ss_random_crop": bool(args.random_crop),
# "ss_shuffle_caption": bool(args.shuffle_caption),
# "ss_cache_latents": bool(args.cache_latents),
# "ss_enable_bucket": bool(train_dataset_group_2.enable_bucket),
# "ss_min_bucket_reso": train_dataset_group_2.min_bucket_reso,
# "ss_max_bucket_reso": train_dataset_group_2.max_bucket_reso,
# "ss_seed": args.seed,
# "ss_keep_tokens": args.keep_tokens,
# "ss_dataset_dirs": json.dumps(train_dataset_group_2.dataset_dirs_info),
# "ss_reg_dataset_dirs": json.dumps(train_dataset_group_2.reg_dataset_dirs_info),
# "ss_bucket_info": json.dumps(train_dataset_group_2.bucket_info),
# "ss_training_comment": args.training_comment # will not be updated after training
# }
# uncomment if another network is added
# for key, value in net_kwargs.items():
# metadata["ss_arg_" + key] = value
# # 共用pretrained model
# if args.pretrained_model_name_or_path is not None and args.pretrained_model_name_or_path_2 is not None:
# sd_model_name_1 = args.pretrained_model_name_or_path
# sd_model_name_2 = args.pretrained_model_name_or_path_2
# if os.path.exists(sd_model_name_1) and os.path.exists(sd_model_name_2):
# metadata_1["ss_sd_model_hash"] = train_util.model_hash(sd_model_name_1)
# metadata_1["ss_new_sd_model_hash"] = train_util.calculate_sha256(sd_model_name_1)
# metadata_2["ss_sd_model_hash"] = train_util.model_hash(sd_model_name_2)
# metadata_2["ss_new_sd_model_hash"] = train_util.calculate_sha256(sd_model_name_2)
# sd_model_name_1 = os.path.basename(sd_model_name_1)
# sd_model_name_2 = os.path.basename(sd_model_name_2)
# metadata_1["ss_sd_model_name"] = sd_model_name_1
# metadata_2["ss_sd_model_name"] = sd_model_name_2
# if args.vae is not None:
# vae_name = args.vae
# if os.path.exists(vae_name):
# metadata_1["ss_vae_hash"] = train_util.model_hash(vae_name)
# metadata_1["ss_new_vae_hash"] = train_util.calculate_sha256(vae_name)
# metadata_2["ss_vae_hash"] = train_util.model_hash(vae_name)
# metadata_2["ss_new_vae_hash"] = train_util.calculate_sha256(vae_name)
# vae_name = os.path.basename(vae_name)
# metadata_1["ss_vae_name"] = vae_name
# metadata_2["ss_vae_name"] = vae_name
# metadata_1 = {k: str(v) for k, v in metadata_1.items()}
# metadata_2 = {k: str(v) for k, v in metadata_2.items()}
if is_main_process:
print("running training / 学習開始")
print(f" num train images * repeats / 学習画像の数×繰り返し回数: {train_dataset_group_1.num_train_images}")
print(f" num reg images / 正則化画像の数: {train_dataset_group_1.num_reg_images}")
print(f" num batches per epoch / 1epochのバッチ数: {len(train_dataloader_1)}")
print(f" num epochs / epoch数: {num_train_epochs}")
print(f" batch size per device / バッチサイズ: {', '.join([str(d.batch_size) for d in train_dataset_group_2.datasets])}")
print(f" num train images * repeats / 学習画像の数×繰り返し回数: {train_dataset_group_2.num_train_images}")
print(f" num reg images / 正則化画像の数: {train_dataset_group_2.num_reg_images}")
print(f" num batches per epoch / 1epochのバッチ数: {len(train_dataloader_2)}")
print(f" batch size per device / バッチサイズ: {', '.join([str(d.batch_size) for d in train_dataset_group_2.datasets])}")
# print(f" total train batch size (with parallel & distributed & accumulation) / 総バッチサイズ(並列学習、勾配合計含む): {total_batch_size}")
print(f" gradient accumulation steps / 勾配を合計するステップ数 = {args.gradient_accumulation_steps}")
print(f" total optimization steps / 学習ステップ数: {args.max_train_steps}")
# TODO refactor metadata creation and move to util
metadata_1 = {
"ss_session_id": session_id, # random integer indicating which group of epochs the model came from
"ss_training_started_at": training_started_at, # unix timestamp
"ss_output_name": args.output_name,
"ss_learning_rate": args.learning_rate,
"ss_text_encoder_lr": args.text_encoder_lr,
"ss_unet_lr": args.unet_lr,
"ss_num_train_images": train_dataset_group_1.num_train_images,
"ss_num_reg_images": train_dataset_group_1.num_reg_images,
"ss_num_batches_per_epoch": len(train_dataloader_1),
"ss_num_epochs": num_train_epochs,
"ss_gradient_checkpointing": args.gradient_checkpointing,
"ss_gradient_accumulation_steps": args.gradient_accumulation_steps,
"ss_max_train_steps": args.max_train_steps,
"ss_lr_warmup_steps": args.lr_warmup_steps,
"ss_lr_scheduler": args.lr_scheduler,
"ss_network_module": args.network_module,
"ss_network_dim": args.network_dim, # None means default because another network than LoRA may have another default dim
"ss_network_alpha": args.network_alpha, # some networks may not use this value
"ss_mixed_precision": args.mixed_precision,
"ss_full_fp16": bool(args.full_fp16),
"ss_v2": bool(args.v2),
"ss_clip_skip": args.clip_skip,
"ss_max_token_length": args.max_token_length,
"ss_cache_latents": bool(args.cache_latents),
"ss_seed": args.seed,
"ss_lowram": args.lowram,
"ss_noise_offset": args.noise_offset,
"ss_training_comment": args.training_comment, # will not be updated after training
"ss_sd_scripts_commit_hash": train_util.get_git_revision_hash(),
"ss_optimizer": optimizer_name_1 + (f"({optimizer_args_1})" if len(optimizer_args_1) > 0 else ""),
"ss_max_grad_norm": args.max_grad_norm,
"ss_caption_dropout_rate": args.caption_dropout_rate,
"ss_caption_dropout_every_n_epochs": args.caption_dropout_every_n_epochs,
"ss_caption_tag_dropout_rate": args.caption_tag_dropout_rate,
"ss_face_crop_aug_range": args.face_crop_aug_range,
"ss_prior_loss_weight": args.prior_loss_weight,
}
metadata_2 = {
"ss_session_id": session_id, # random integer indicating which group of epochs the model came from
"ss_training_started_at": training_started_at, # unix timestamp
"ss_output_name": args.output_name,
"ss_learning_rate": args.learning_rate,
"ss_text_encoder_lr": args.text_encoder_lr,
"ss_unet_lr": args.unet_lr,
"ss_num_train_images": train_dataset_group_2.num_train_images,
"ss_num_reg_images": train_dataset_group_2.num_reg_images,
"ss_num_batches_per_epoch": len(train_dataloader_2),
"ss_num_epochs": num_train_epochs,
"ss_gradient_checkpointing": args.gradient_checkpointing,
"ss_gradient_accumulation_steps": args.gradient_accumulation_steps,
"ss_max_train_steps": args.max_train_steps,
"ss_lr_warmup_steps": args.lr_warmup_steps,
"ss_lr_scheduler": args.lr_scheduler,
"ss_network_module": args.network_module,
"ss_network_dim": args.network_dim, # None means default because another network than LoRA may have another default dim
"ss_network_alpha": args.network_alpha, # some networks may not use this value
"ss_mixed_precision": args.mixed_precision,
"ss_full_fp16": bool(args.full_fp16),
"ss_v2": bool(args.v2),
"ss_clip_skip": args.clip_skip,
"ss_max_token_length": args.max_token_length,
"ss_cache_latents": bool(args.cache_latents),
"ss_seed": args.seed,
"ss_lowram": args.lowram,
"ss_noise_offset": args.noise_offset,
"ss_training_comment": args.training_comment, # will not be updated after training
"ss_sd_scripts_commit_hash": train_util.get_git_revision_hash(),
"ss_optimizer": optimizer_name_2 + (f"({optimizer_args_2})" if len(optimizer_args_2) > 0 else ""),
"ss_max_grad_norm": args.max_grad_norm,
"ss_caption_dropout_rate": args.caption_dropout_rate,
"ss_caption_dropout_every_n_epochs": args.caption_dropout_every_n_epochs,
"ss_caption_tag_dropout_rate": args.caption_tag_dropout_rate,
"ss_face_crop_aug_range": args.face_crop_aug_range,
"ss_prior_loss_weight": args.prior_loss_weight,
}
if use_user_config:
# save metadata of multiple datasets
# NOTE: pack "ss_datasets" value as json one time
# or should also pack nested collections as json?
datasets_metadata = []
tag_frequency = {} # merge tag frequency for metadata editor
dataset_dirs_info = {} # merge subset dirs for metadata editor
for dataset in train_dataset_group.datasets:
is_dreambooth_dataset = isinstance(dataset, DreamBoothDataset)
dataset_metadata = {
"is_dreambooth": is_dreambooth_dataset,
"batch_size_per_device": dataset.batch_size,
"num_train_images": dataset.num_train_images, # includes repeating
"num_reg_images": dataset.num_reg_images,
"resolution": (dataset.width, dataset.height),
"enable_bucket": bool(dataset.enable_bucket),
"min_bucket_reso": dataset.min_bucket_reso,
"max_bucket_reso": dataset.max_bucket_reso,
"tag_frequency": dataset.tag_frequency,
"bucket_info": dataset.bucket_info,
}
subsets_metadata = []
for subset in dataset.subsets:
subset_metadata = {
"img_count": subset.img_count,
"num_repeats": subset.num_repeats,
"color_aug": bool(subset.color_aug),
"flip_aug": bool(subset.flip_aug),
"random_crop": bool(subset.random_crop),
"shuffle_caption": bool(subset.shuffle_caption),
"keep_tokens": subset.keep_tokens,
}
image_dir_or_metadata_file = None
if subset.image_dir:
image_dir = os.path.basename(subset.image_dir)
subset_metadata["image_dir"] = image_dir
image_dir_or_metadata_file = image_dir
if is_dreambooth_dataset:
subset_metadata["class_tokens"] = subset.class_tokens
subset_metadata["is_reg"] = subset.is_reg
if subset.is_reg:
image_dir_or_metadata_file = None # not merging reg dataset
else:
metadata_file = os.path.basename(subset.metadata_file)
subset_metadata["metadata_file"] = metadata_file
image_dir_or_metadata_file = metadata_file # may overwrite
subsets_metadata.append(subset_metadata)
# merge dataset dir: not reg subset only
# TODO update additional-network extension to show detailed dataset config from metadata
if image_dir_or_metadata_file is not None:
# datasets may have a certain dir multiple times
v = image_dir_or_metadata_file
i = 2
while v in dataset_dirs_info:
v = image_dir_or_metadata_file + f" ({i})"
i += 1
image_dir_or_metadata_file = v
dataset_dirs_info[image_dir_or_metadata_file] = {"n_repeats": subset.num_repeats, "img_count": subset.img_count}
dataset_metadata["subsets"] = subsets_metadata
datasets_metadata.append(dataset_metadata)
# merge tag frequency:
for ds_dir_name, ds_freq_for_dir in dataset.tag_frequency.items():
# あるディレクトリが複数のdatasetで使用されている場合、一度だけ数える
# もともと繰り返し回数を指定しているので、キャプション内でのタグの出現回数と、それが学習で何度使われるかは一致しない
# なので、ここで複数datasetの回数を合算してもあまり意味はない
if ds_dir_name in tag_frequency:
continue
tag_frequency[ds_dir_name] = ds_freq_for_dir
metadata["ss_datasets"] = json.dumps(datasets_metadata)
metadata["ss_tag_frequency"] = json.dumps(tag_frequency)
metadata["ss_dataset_dirs"] = json.dumps(dataset_dirs_info)
else:
# conserving backward compatibility when using train_dataset_dir and reg_dataset_dir
assert (
len(train_dataset_group_1.datasets) == 1
), f"There should be a single dataset but {len(train_dataset_group_1.datasets)} found. This seems to be a bug. / データセットは1個だけ存在するはずですが、実際には{len(train_dataset_group.datasets)}個でした。プログラムのバグかもしれません。"
dataset_1 = train_dataset_group_1.datasets[0]
dataset_2 = train_dataset_group_2.datasets[0]
dataset_dirs_info_1 = {}
reg_dataset_dirs_info_1 = {}
dataset_dirs_info_2 = {}
reg_dataset_dirs_info_2 = {}
if use_dreambooth_method:
for subset in dataset_1.subsets:
info = reg_dataset_dirs_info_1 if subset.is_reg else dataset_dirs_info_1
info[os.path.basename(subset.image_dir)] = {"n_repeats": subset.num_repeats, "img_count": subset.img_count}
for subset in dataset_2.subsets:
info = reg_dataset_dirs_info_2 if subset.is_reg else dataset_dirs_info_2
info[os.path.basename(subset.image_dir)] = {"n_repeats": subset.num_repeats, "img_count": subset.img_count}
else:
for subset in dataset_1.subsets:
dataset_dirs_info_1[os.path.basename(subset.metadata_file)] = {
"n_repeats": subset.num_repeats,
"img_count": subset.img_count,
}
for subset in dataset_2.subsets:
dataset_dirs_info_2[os.path.basename(subset.metadata_file)] = {
"n_repeats": subset.num_repeats,
"img_count": subset.img_count,
}
metadata_1.update(
{
"ss_batch_size_per_device": args.train_batch_size,
"ss_total_batch_size": total_batch_size,
"ss_resolution": args.resolution,
"ss_color_aug": bool(args.color_aug),
"ss_flip_aug": bool(args.flip_aug),
"ss_random_crop": bool(args.random_crop),
"ss_shuffle_caption": bool(args.shuffle_caption),
"ss_enable_bucket": bool(dataset_1.enable_bucket),
"ss_bucket_no_upscale": bool(dataset_1.bucket_no_upscale),
"ss_min_bucket_reso": dataset_1.min_bucket_reso,
"ss_max_bucket_reso": dataset_1.max_bucket_reso,
"ss_keep_tokens": args.keep_tokens,
"ss_dataset_dirs": json.dumps(dataset_dirs_info_1),
"ss_reg_dataset_dirs": json.dumps(reg_dataset_dirs_info_1),
"ss_tag_frequency": json.dumps(dataset_1.tag_frequency),
"ss_bucket_info": json.dumps(dataset_1.bucket_info),
}
)
metadata_2.update(
{
"ss_batch_size_per_device": args.train_batch_size,
"ss_total_batch_size": total_batch_size,
"ss_resolution": args.resolution,
"ss_color_aug": bool(args.color_aug),
"ss_flip_aug": bool(args.flip_aug),
"ss_random_crop": bool(args.random_crop),
"ss_shuffle_caption": bool(args.shuffle_caption),
"ss_enable_bucket": bool(dataset_2.enable_bucket),
"ss_bucket_no_upscale": bool(dataset_2.bucket_no_upscale),
"ss_min_bucket_reso": dataset_2.min_bucket_reso,
"ss_max_bucket_reso": dataset_2.max_bucket_reso,
"ss_keep_tokens": args.keep_tokens,
"ss_dataset_dirs": json.dumps(dataset_dirs_info_1),
"ss_reg_dataset_dirs": json.dumps(reg_dataset_dirs_info_1),
"ss_tag_frequency": json.dumps(dataset_2.tag_frequency),
"ss_bucket_info": json.dumps(dataset_2.bucket_info),
}
)
# add extra args
if args.network_args:
metadata_1["ss_network_args"] = json.dumps(net_kwargs)
metadata_2["ss_network_args"] = json.dumps(net_kwargs)
# for key, value in net_kwargs.items():
# metadata["ss_arg_" + key] = value
# model name and hash
if args.pretrained_model_name_or_path is not None:
sd_model_name_1 = args.pretrained_model_name_or_path
sd_model_name_2 = args.pretrained_model_name_or_path_2
if os.path.exists(sd_model_name_1):
metadata_1["ss_sd_model_hash"] = train_util.model_hash(sd_model_name_1)
metadata_1["ss_new_sd_model_hash"] = train_util.calculate_sha256(sd_model_name_1)
sd_model_name_1 = os.path.basename(sd_model_name_1)
metadata_1["ss_sd_model_name"] = sd_model_name_1
if os.path.exists(sd_model_name_2):
metadata_2["ss_sd_model_hash"] = train_util.model_hash(sd_model_name_2)
metadata_2["ss_new_sd_model_hash"] = train_util.calculate_sha256(sd_model_name_2)
sd_model_name_2 = os.path.basename(sd_model_name_2)
metadata_2["ss_sd_model_name"] = sd_model_name_2
if args.vae is not None:
vae_name = args.vae
if os.path.exists(vae_name):
metadata_1["ss_vae_hash"] = train_util.model_hash(vae_name)
metadata_1["ss_new_vae_hash"] = train_util.calculate_sha256(vae_name)
vae_name = os.path.basename(vae_name)
metadata_1["ss_vae_name"] = vae_name
metadata_1 = {k: str(v) for k, v in metadata_1.items()}
metadata_2 = {k: str(v) for k, v in metadata_2.items()}
# make minimum metadata for filtering
minimum_keys = ["ss_network_module", "ss_network_dim", "ss_network_alpha", "ss_network_args"]
minimum_metadata = {}
for key in minimum_keys:
if key in metadata_1:
minimum_metadata[key] = metadata_1[key]
# 只弄一个进度条就够了,两个有点多