ACCC1380 commited on
Commit
19768bc
1 Parent(s): 92c64c5

Upload lora-scripts/sd-scripts/sdxl_train.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. lora-scripts/sd-scripts/sdxl_train.py +818 -0
lora-scripts/sd-scripts/sdxl_train.py ADDED
@@ -0,0 +1,818 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # training with captions
2
+
3
+ import argparse
4
+ import math
5
+ import os
6
+ from multiprocessing import Value
7
+ from typing import List
8
+ import toml
9
+
10
+ from tqdm import tqdm
11
+
12
+ import torch
13
+ from library.device_utils import init_ipex, clean_memory_on_device
14
+
15
+
16
+ init_ipex()
17
+
18
+ from accelerate.utils import set_seed
19
+ from diffusers import DDPMScheduler
20
+ from library import deepspeed_utils, sdxl_model_util
21
+
22
+ import library.train_util as train_util
23
+
24
+ from library.utils import setup_logging, add_logging_arguments
25
+
26
+ setup_logging()
27
+ import logging
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+ import library.config_util as config_util
32
+ import library.sdxl_train_util as sdxl_train_util
33
+ from library.config_util import (
34
+ ConfigSanitizer,
35
+ BlueprintGenerator,
36
+ )
37
+ import library.custom_train_functions as custom_train_functions
38
+ from library.custom_train_functions import (
39
+ apply_snr_weight,
40
+ prepare_scheduler_for_custom_training,
41
+ scale_v_prediction_loss_like_noise_prediction,
42
+ add_v_prediction_like_loss,
43
+ apply_debiased_estimation,
44
+ apply_masked_loss,
45
+ )
46
+ from library.sdxl_original_unet import SdxlUNet2DConditionModel
47
+
48
+
49
+ UNET_NUM_BLOCKS_FOR_BLOCK_LR = 23
50
+
51
+
52
+ def get_block_params_to_optimize(unet: SdxlUNet2DConditionModel, block_lrs: List[float]) -> List[dict]:
53
+ block_params = [[] for _ in range(len(block_lrs))]
54
+
55
+ for i, (name, param) in enumerate(unet.named_parameters()):
56
+ if name.startswith("time_embed.") or name.startswith("label_emb."):
57
+ block_index = 0 # 0
58
+ elif name.startswith("input_blocks."): # 1-9
59
+ block_index = 1 + int(name.split(".")[1])
60
+ elif name.startswith("middle_block."): # 10-12
61
+ block_index = 10 + int(name.split(".")[1])
62
+ elif name.startswith("output_blocks."): # 13-21
63
+ block_index = 13 + int(name.split(".")[1])
64
+ elif name.startswith("out."): # 22
65
+ block_index = 22
66
+ else:
67
+ raise ValueError(f"unexpected parameter name: {name}")
68
+
69
+ block_params[block_index].append(param)
70
+
71
+ params_to_optimize = []
72
+ for i, params in enumerate(block_params):
73
+ if block_lrs[i] == 0: # 0のときは学習しない do not optimize when lr is 0
74
+ continue
75
+ params_to_optimize.append({"params": params, "lr": block_lrs[i]})
76
+
77
+ return params_to_optimize
78
+
79
+
80
+ def append_block_lr_to_logs(block_lrs, logs, lr_scheduler, optimizer_type):
81
+ names = []
82
+ block_index = 0
83
+ while block_index < UNET_NUM_BLOCKS_FOR_BLOCK_LR + 2:
84
+ if block_index < UNET_NUM_BLOCKS_FOR_BLOCK_LR:
85
+ if block_lrs[block_index] == 0:
86
+ block_index += 1
87
+ continue
88
+ names.append(f"block{block_index}")
89
+ elif block_index == UNET_NUM_BLOCKS_FOR_BLOCK_LR:
90
+ names.append("text_encoder1")
91
+ elif block_index == UNET_NUM_BLOCKS_FOR_BLOCK_LR + 1:
92
+ names.append("text_encoder2")
93
+
94
+ block_index += 1
95
+
96
+ train_util.append_lr_to_logs_with_names(logs, lr_scheduler, optimizer_type, names)
97
+
98
+
99
+ def train(args):
100
+ train_util.verify_training_args(args)
101
+ train_util.prepare_dataset_args(args, True)
102
+ sdxl_train_util.verify_sdxl_training_args(args)
103
+ deepspeed_utils.prepare_deepspeed_args(args)
104
+ setup_logging(args, reset=True)
105
+
106
+ assert (
107
+ not args.weighted_captions
108
+ ), "weighted_captions is not supported currently / weighted_captionsは現在サポートされていません"
109
+ assert (
110
+ not args.train_text_encoder or not args.cache_text_encoder_outputs
111
+ ), "cache_text_encoder_outputs is not supported when training text encoder / text encoderを学習するときはcache_text_encoder_outputsはサポートされていません"
112
+
113
+ if args.block_lr:
114
+ block_lrs = [float(lr) for lr in args.block_lr.split(",")]
115
+ assert (
116
+ len(block_lrs) == UNET_NUM_BLOCKS_FOR_BLOCK_LR
117
+ ), f"block_lr must have {UNET_NUM_BLOCKS_FOR_BLOCK_LR} values / block_lrは{UNET_NUM_BLOCKS_FOR_BLOCK_LR}個の値を指定してください"
118
+ else:
119
+ block_lrs = None
120
+
121
+ cache_latents = args.cache_latents
122
+ use_dreambooth_method = args.in_json is None
123
+
124
+ if args.seed is not None:
125
+ set_seed(args.seed) # 乱数系列を初期化する
126
+
127
+ tokenizer1, tokenizer2 = sdxl_train_util.load_tokenizers(args)
128
+
129
+ # データセットを準備する
130
+ if args.dataset_class is None:
131
+ blueprint_generator = BlueprintGenerator(ConfigSanitizer(True, True, args.masked_loss, True))
132
+ if args.dataset_config is not None:
133
+ logger.info(f"Load dataset config from {args.dataset_config}")
134
+ user_config = config_util.load_user_config(args.dataset_config)
135
+ ignored = ["train_data_dir", "in_json"]
136
+ if any(getattr(args, attr) is not None for attr in ignored):
137
+ logger.warning(
138
+ "ignore following options because config file is found: {0} / 設定ファイルが利用されるため以下のオプションは無���されます: {0}".format(
139
+ ", ".join(ignored)
140
+ )
141
+ )
142
+ else:
143
+ if use_dreambooth_method:
144
+ logger.info("Using DreamBooth method.")
145
+ user_config = {
146
+ "datasets": [
147
+ {
148
+ "subsets": config_util.generate_dreambooth_subsets_config_by_subdirs(
149
+ args.train_data_dir, args.reg_data_dir
150
+ )
151
+ }
152
+ ]
153
+ }
154
+ else:
155
+ logger.info("Training with captions.")
156
+ user_config = {
157
+ "datasets": [
158
+ {
159
+ "subsets": [
160
+ {
161
+ "image_dir": args.train_data_dir,
162
+ "metadata_file": args.in_json,
163
+ }
164
+ ]
165
+ }
166
+ ]
167
+ }
168
+
169
+ blueprint = blueprint_generator.generate(user_config, args, tokenizer=[tokenizer1, tokenizer2])
170
+ train_dataset_group = config_util.generate_dataset_group_by_blueprint(blueprint.dataset_group)
171
+ else:
172
+ train_dataset_group = train_util.load_arbitrary_dataset(args, [tokenizer1, tokenizer2])
173
+
174
+ current_epoch = Value("i", 0)
175
+ current_step = Value("i", 0)
176
+ ds_for_collator = train_dataset_group if args.max_data_loader_n_workers == 0 else None
177
+ collator = train_util.collator_class(current_epoch, current_step, ds_for_collator)
178
+
179
+ train_dataset_group.verify_bucket_reso_steps(32)
180
+
181
+ if args.debug_dataset:
182
+ train_util.debug_dataset(train_dataset_group, True)
183
+ return
184
+ if len(train_dataset_group) == 0:
185
+ logger.error(
186
+ "No data found. Please verify the metadata file and train_data_dir option. / 画像がありません。メタデータおよびtrain_data_dirオプションを確認してください。"
187
+ )
188
+ return
189
+
190
+ if cache_latents:
191
+ assert (
192
+ train_dataset_group.is_latent_cacheable()
193
+ ), "when caching latents, either color_aug or random_crop cannot be used / latentをキャッシュするときはcolor_augとrandom_cropは使えません"
194
+
195
+ if args.cache_text_encoder_outputs:
196
+ assert (
197
+ train_dataset_group.is_text_encoder_output_cacheable()
198
+ ), "when caching text encoder output, either caption_dropout_rate, shuffle_caption, token_warmup_step or caption_tag_dropout_rate cannot be used / text encoderの出力をキャッシュするときはcaption_dropout_rate, shuffle_caption, token_warmup_step, caption_tag_dropout_rateは使えません"
199
+
200
+ # acceleratorを準備する
201
+ logger.info("prepare accelerator")
202
+ accelerator = train_util.prepare_accelerator(args)
203
+
204
+ # mixed precisionに対応した型を用意しておき適宜castする
205
+ weight_dtype, save_dtype = train_util.prepare_dtype(args)
206
+ vae_dtype = torch.float32 if args.no_half_vae else weight_dtype
207
+
208
+ # モデルを読み込む
209
+ (
210
+ load_stable_diffusion_format,
211
+ text_encoder1,
212
+ text_encoder2,
213
+ vae,
214
+ unet,
215
+ logit_scale,
216
+ ckpt_info,
217
+ ) = sdxl_train_util.load_target_model(args, accelerator, "sdxl", weight_dtype)
218
+ # logit_scale = logit_scale.to(accelerator.device, dtype=weight_dtype)
219
+
220
+ # verify load/save model formats
221
+ if load_stable_diffusion_format:
222
+ src_stable_diffusion_ckpt = args.pretrained_model_name_or_path
223
+ src_diffusers_model_path = None
224
+ else:
225
+ src_stable_diffusion_ckpt = None
226
+ src_diffusers_model_path = args.pretrained_model_name_or_path
227
+
228
+ if args.save_model_as is None:
229
+ save_stable_diffusion_format = load_stable_diffusion_format
230
+ use_safetensors = args.use_safetensors
231
+ else:
232
+ save_stable_diffusion_format = args.save_model_as.lower() == "ckpt" or args.save_model_as.lower() == "safetensors"
233
+ use_safetensors = args.use_safetensors or ("safetensors" in args.save_model_as.lower())
234
+ # assert save_stable_diffusion_format, "save_model_as must be ckpt or safetensors / save_model_asはckptかsafetensorsである必要があります"
235
+
236
+ # Diffusers版のxformers使用フラグを設定する関数
237
+ def set_diffusers_xformers_flag(model, valid):
238
+ def fn_recursive_set_mem_eff(module: torch.nn.Module):
239
+ if hasattr(module, "set_use_memory_efficient_attention_xformers"):
240
+ module.set_use_memory_efficient_attention_xformers(valid)
241
+
242
+ for child in module.children():
243
+ fn_recursive_set_mem_eff(child)
244
+
245
+ fn_recursive_set_mem_eff(model)
246
+
247
+ # モデルに xformers とか memory efficient attention を組み込む
248
+ if args.diffusers_xformers:
249
+ # もうU-Netを独自にしたので動かないけどVAEのxformersは動くはず
250
+ accelerator.print("Use xformers by Diffusers")
251
+ # set_diffusers_xformers_flag(unet, True)
252
+ set_diffusers_xformers_flag(vae, True)
253
+ else:
254
+ # Windows版のxformersはfloatで学習できなかったりするのでxformersを使わない設定も可能にしておく必要がある
255
+ accelerator.print("Disable Diffusers' xformers")
256
+ train_util.replace_unet_modules(unet, args.mem_eff_attn, args.xformers, args.sdpa)
257
+ if torch.__version__ >= "2.0.0": # PyTorch 2.0.0 以上対応のxformersなら以下が使える
258
+ vae.set_use_memory_efficient_attention_xformers(args.xformers)
259
+
260
+ # 学習を準備する
261
+ if cache_latents:
262
+ vae.to(accelerator.device, dtype=vae_dtype)
263
+ vae.requires_grad_(False)
264
+ vae.eval()
265
+ with torch.no_grad():
266
+ train_dataset_group.cache_latents(vae, args.vae_batch_size, args.cache_latents_to_disk, accelerator.is_main_process)
267
+ vae.to("cpu")
268
+ clean_memory_on_device(accelerator.device)
269
+
270
+ accelerator.wait_for_everyone()
271
+
272
+ # 学習を準備する:モデルを適切な状態にする
273
+ if args.gradient_checkpointing:
274
+ unet.enable_gradient_checkpointing()
275
+ train_unet = args.learning_rate > 0
276
+ train_text_encoder1 = False
277
+ train_text_encoder2 = False
278
+
279
+ if args.train_text_encoder:
280
+ # TODO each option for two text encoders?
281
+ accelerator.print("enable text encoder training")
282
+ if args.gradient_checkpointing:
283
+ text_encoder1.gradient_checkpointing_enable()
284
+ text_encoder2.gradient_checkpointing_enable()
285
+ lr_te1 = args.learning_rate_te1 if args.learning_rate_te1 is not None else args.learning_rate # 0 means not train
286
+ lr_te2 = args.learning_rate_te2 if args.learning_rate_te2 is not None else args.learning_rate # 0 means not train
287
+ train_text_encoder1 = lr_te1 > 0
288
+ train_text_encoder2 = lr_te2 > 0
289
+
290
+ # caching one text encoder output is not supported
291
+ if not train_text_encoder1:
292
+ text_encoder1.to(weight_dtype)
293
+ if not train_text_encoder2:
294
+ text_encoder2.to(weight_dtype)
295
+ text_encoder1.requires_grad_(train_text_encoder1)
296
+ text_encoder2.requires_grad_(train_text_encoder2)
297
+ text_encoder1.train(train_text_encoder1)
298
+ text_encoder2.train(train_text_encoder2)
299
+ else:
300
+ text_encoder1.to(weight_dtype)
301
+ text_encoder2.to(weight_dtype)
302
+ text_encoder1.requires_grad_(False)
303
+ text_encoder2.requires_grad_(False)
304
+ text_encoder1.eval()
305
+ text_encoder2.eval()
306
+
307
+ # TextEncoderの出力をキャッシュする
308
+ if args.cache_text_encoder_outputs:
309
+ # Text Encodes are eval and no grad
310
+ with torch.no_grad(), accelerator.autocast():
311
+ train_dataset_group.cache_text_encoder_outputs(
312
+ (tokenizer1, tokenizer2),
313
+ (text_encoder1, text_encoder2),
314
+ accelerator.device,
315
+ None,
316
+ args.cache_text_encoder_outputs_to_disk,
317
+ accelerator.is_main_process,
318
+ )
319
+ accelerator.wait_for_everyone()
320
+
321
+ if not cache_latents:
322
+ vae.requires_grad_(False)
323
+ vae.eval()
324
+ vae.to(accelerator.device, dtype=vae_dtype)
325
+
326
+ unet.requires_grad_(train_unet)
327
+ if not train_unet:
328
+ unet.to(accelerator.device, dtype=weight_dtype) # because of unet is not prepared
329
+
330
+ training_models = []
331
+ params_to_optimize = []
332
+ if train_unet:
333
+ training_models.append(unet)
334
+ if block_lrs is None:
335
+ params_to_optimize.append({"params": list(unet.parameters()), "lr": args.learning_rate})
336
+ else:
337
+ params_to_optimize.extend(get_block_params_to_optimize(unet, block_lrs))
338
+
339
+ if train_text_encoder1:
340
+ training_models.append(text_encoder1)
341
+ params_to_optimize.append({"params": list(text_encoder1.parameters()), "lr": args.learning_rate_te1 or args.learning_rate})
342
+ if train_text_encoder2:
343
+ training_models.append(text_encoder2)
344
+ params_to_optimize.append({"params": list(text_encoder2.parameters()), "lr": args.learning_rate_te2 or args.learning_rate})
345
+
346
+ # calculate number of trainable parameters
347
+ n_params = 0
348
+ for params in params_to_optimize:
349
+ for p in params["params"]:
350
+ n_params += p.numel()
351
+
352
+ accelerator.print(f"train unet: {train_unet}, text_encoder1: {train_text_encoder1}, text_encoder2: {train_text_encoder2}")
353
+ accelerator.print(f"number of models: {len(training_models)}")
354
+ accelerator.print(f"number of trainable parameters: {n_params}")
355
+
356
+ # 学習に必要なクラスを準備する
357
+ accelerator.print("prepare optimizer, data loader etc.")
358
+ _, _, optimizer = train_util.get_optimizer(args, trainable_params=params_to_optimize)
359
+
360
+ # dataloaderを準備する
361
+ # DataLoaderのプロセス数:0 は persistent_workers が使えないので注意
362
+ n_workers = min(args.max_data_loader_n_workers, os.cpu_count()) # cpu_count or max_data_loader_n_workers
363
+ train_dataloader = torch.utils.data.DataLoader(
364
+ train_dataset_group,
365
+ batch_size=1,
366
+ shuffle=True,
367
+ collate_fn=collator,
368
+ num_workers=n_workers,
369
+ persistent_workers=args.persistent_data_loader_workers,
370
+ )
371
+
372
+ # 学習ステップ数を計算する
373
+ if args.max_train_epochs is not None:
374
+ args.max_train_steps = args.max_train_epochs * math.ceil(
375
+ len(train_dataloader) / accelerator.num_processes / args.gradient_accumulation_steps
376
+ )
377
+ accelerator.print(
378
+ f"override steps. steps for {args.max_train_epochs} epochs is / 指定エポックまでのステップ数: {args.max_train_steps}"
379
+ )
380
+
381
+ # データセット側にも学習ステップを送信
382
+ train_dataset_group.set_max_train_steps(args.max_train_steps)
383
+
384
+ # lr schedulerを用意する
385
+ lr_scheduler = train_util.get_scheduler_fix(args, optimizer, accelerator.num_processes)
386
+
387
+ # 実験的機能:勾配も含めたfp16/bf16学習を行う モデル全体をfp16/bf16にする
388
+ if args.full_fp16:
389
+ assert (
390
+ args.mixed_precision == "fp16"
391
+ ), "full_fp16 requires mixed precision='fp16' / full_fp16を使う場合はmixed_precision='fp16'を指定してください。"
392
+ accelerator.print("enable full fp16 training.")
393
+ unet.to(weight_dtype)
394
+ text_encoder1.to(weight_dtype)
395
+ text_encoder2.to(weight_dtype)
396
+ elif args.full_bf16:
397
+ assert (
398
+ args.mixed_precision == "bf16"
399
+ ), "full_bf16 requires mixed precision='bf16' / full_bf16を使う場合はmixed_precision='bf16'を指定してください。"
400
+ accelerator.print("enable full bf16 training.")
401
+ unet.to(weight_dtype)
402
+ text_encoder1.to(weight_dtype)
403
+ text_encoder2.to(weight_dtype)
404
+
405
+ # freeze last layer and final_layer_norm in te1 since we use the output of the penultimate layer
406
+ if train_text_encoder1:
407
+ text_encoder1.text_model.encoder.layers[-1].requires_grad_(False)
408
+ text_encoder1.text_model.final_layer_norm.requires_grad_(False)
409
+
410
+ if args.deepspeed:
411
+ ds_model = deepspeed_utils.prepare_deepspeed_model(
412
+ args,
413
+ unet=unet if train_unet else None,
414
+ text_encoder1=text_encoder1 if train_text_encoder1 else None,
415
+ text_encoder2=text_encoder2 if train_text_encoder2 else None,
416
+ )
417
+ # most of ZeRO stage uses optimizer partitioning, so we have to prepare optimizer and ds_model at the same time. # pull/1139#issuecomment-1986790007
418
+ ds_model, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
419
+ ds_model, optimizer, train_dataloader, lr_scheduler
420
+ )
421
+ training_models = [ds_model]
422
+
423
+ else:
424
+ # acceleratorがなんかよろしくやってくれるらしい
425
+ if train_unet:
426
+ unet = accelerator.prepare(unet)
427
+ if train_text_encoder1:
428
+ text_encoder1 = accelerator.prepare(text_encoder1)
429
+ if train_text_encoder2:
430
+ text_encoder2 = accelerator.prepare(text_encoder2)
431
+ optimizer, train_dataloader, lr_scheduler = accelerator.prepare(optimizer, train_dataloader, lr_scheduler)
432
+
433
+ # TextEncoderの出力をキャッシュするときにはCPUへ移動する
434
+ if args.cache_text_encoder_outputs:
435
+ # move Text Encoders for sampling images. Text Encoder doesn't work on CPU with fp16
436
+ text_encoder1.to("cpu", dtype=torch.float32)
437
+ text_encoder2.to("cpu", dtype=torch.float32)
438
+ clean_memory_on_device(accelerator.device)
439
+ else:
440
+ # make sure Text Encoders are on GPU
441
+ text_encoder1.to(accelerator.device)
442
+ text_encoder2.to(accelerator.device)
443
+
444
+ # 実験的機能:勾配も含めたfp16学習を行う PyTorchにパッチを当ててfp16でのgrad scaleを有効にする
445
+ if args.full_fp16:
446
+ # During deepseed training, accelerate not handles fp16/bf16|mixed precision directly via scaler. Let deepspeed engine do.
447
+ # -> But we think it's ok to patch accelerator even if deepspeed is enabled.
448
+ train_util.patch_accelerator_for_fp16_training(accelerator)
449
+
450
+ # resumeする
451
+ train_util.resume_from_local_or_hf_if_specified(accelerator, args)
452
+
453
+ # epoch数を計算する
454
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
455
+ num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
456
+ if (args.save_n_epoch_ratio is not None) and (args.save_n_epoch_ratio > 0):
457
+ args.save_every_n_epochs = math.floor(num_train_epochs / args.save_n_epoch_ratio) or 1
458
+
459
+ # 学習する
460
+ # total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
461
+ accelerator.print("running training / 学習開始")
462
+ accelerator.print(f" num examples / サンプル数: {train_dataset_group.num_train_images}")
463
+ accelerator.print(f" num batches per epoch / 1epochのバッチ数: {len(train_dataloader)}")
464
+ accelerator.print(f" num epochs / epoch数: {num_train_epochs}")
465
+ accelerator.print(
466
+ f" batch size per device / バッチサイズ: {', '.join([str(d.batch_size) for d in train_dataset_group.datasets])}"
467
+ )
468
+ # accelerator.print(
469
+ # f" total train batch size (with parallel & distributed & accumulation) / 総バッチサイズ(並列学習、勾配合計含む): {total_batch_size}"
470
+ # )
471
+ accelerator.print(f" gradient accumulation steps / 勾配を合計するステップ数 = {args.gradient_accumulation_steps}")
472
+ accelerator.print(f" total optimization steps / 学習ステップ数: {args.max_train_steps}")
473
+
474
+ progress_bar = tqdm(range(args.max_train_steps), smoothing=0, disable=not accelerator.is_local_main_process, desc="steps")
475
+ global_step = 0
476
+
477
+ noise_scheduler = DDPMScheduler(
478
+ beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", num_train_timesteps=1000, clip_sample=False
479
+ )
480
+ prepare_scheduler_for_custom_training(noise_scheduler, accelerator.device)
481
+ if args.zero_terminal_snr:
482
+ custom_train_functions.fix_noise_scheduler_betas_for_zero_terminal_snr(noise_scheduler)
483
+
484
+ if accelerator.is_main_process:
485
+ init_kwargs = {}
486
+ if args.wandb_run_name:
487
+ init_kwargs["wandb"] = {"name": args.wandb_run_name}
488
+ if args.log_tracker_config is not None:
489
+ init_kwargs = toml.load(args.log_tracker_config)
490
+ accelerator.init_trackers("finetuning" if args.log_tracker_name is None else args.log_tracker_name, init_kwargs=init_kwargs)
491
+
492
+ # For --sample_at_first
493
+ sdxl_train_util.sample_images(
494
+ accelerator, args, 0, global_step, accelerator.device, vae, [tokenizer1, tokenizer2], [text_encoder1, text_encoder2], unet
495
+ )
496
+
497
+ loss_recorder = train_util.LossRecorder()
498
+ for epoch in range(num_train_epochs):
499
+ accelerator.print(f"\nepoch {epoch+1}/{num_train_epochs}")
500
+ current_epoch.value = epoch + 1
501
+
502
+ for m in training_models:
503
+ m.train()
504
+
505
+ for step, batch in enumerate(train_dataloader):
506
+ current_step.value = global_step
507
+ with accelerator.accumulate(*training_models):
508
+ if "latents" in batch and batch["latents"] is not None:
509
+ latents = batch["latents"].to(accelerator.device).to(dtype=weight_dtype)
510
+ else:
511
+ with torch.no_grad():
512
+ # latentに変換
513
+ latents = vae.encode(batch["images"].to(vae_dtype)).latent_dist.sample().to(weight_dtype)
514
+
515
+ # NaNが含まれていれば警告を表示し0に置き換える
516
+ if torch.any(torch.isnan(latents)):
517
+ accelerator.print("NaN found in latents, replacing with zeros")
518
+ latents = torch.nan_to_num(latents, 0, out=latents)
519
+ latents = latents * sdxl_model_util.VAE_SCALE_FACTOR
520
+
521
+ if "text_encoder_outputs1_list" not in batch or batch["text_encoder_outputs1_list"] is None:
522
+ input_ids1 = batch["input_ids"]
523
+ input_ids2 = batch["input_ids2"]
524
+ with torch.set_grad_enabled(args.train_text_encoder):
525
+ # Get the text embedding for conditioning
526
+ # TODO support weighted captions
527
+ # if args.weighted_captions:
528
+ # encoder_hidden_states = get_weighted_text_embeddings(
529
+ # tokenizer,
530
+ # text_encoder,
531
+ # batch["captions"],
532
+ # accelerator.device,
533
+ # args.max_token_length // 75 if args.max_token_length else 1,
534
+ # clip_skip=args.clip_skip,
535
+ # )
536
+ # else:
537
+ input_ids1 = input_ids1.to(accelerator.device)
538
+ input_ids2 = input_ids2.to(accelerator.device)
539
+ # unwrap_model is fine for models not wrapped by accelerator
540
+ encoder_hidden_states1, encoder_hidden_states2, pool2 = train_util.get_hidden_states_sdxl(
541
+ args.max_token_length,
542
+ input_ids1,
543
+ input_ids2,
544
+ tokenizer1,
545
+ tokenizer2,
546
+ text_encoder1,
547
+ text_encoder2,
548
+ None if not args.full_fp16 else weight_dtype,
549
+ accelerator=accelerator,
550
+ )
551
+ else:
552
+ encoder_hidden_states1 = batch["text_encoder_outputs1_list"].to(accelerator.device).to(weight_dtype)
553
+ encoder_hidden_states2 = batch["text_encoder_outputs2_list"].to(accelerator.device).to(weight_dtype)
554
+ pool2 = batch["text_encoder_pool2_list"].to(accelerator.device).to(weight_dtype)
555
+
556
+ # # verify that the text encoder outputs are correct
557
+ # ehs1, ehs2, p2 = train_util.get_hidden_states_sdxl(
558
+ # args.max_token_length,
559
+ # batch["input_ids"].to(text_encoder1.device),
560
+ # batch["input_ids2"].to(text_encoder1.device),
561
+ # tokenizer1,
562
+ # tokenizer2,
563
+ # text_encoder1,
564
+ # text_encoder2,
565
+ # None if not args.full_fp16 else weight_dtype,
566
+ # )
567
+ # b_size = encoder_hidden_states1.shape[0]
568
+ # assert ((encoder_hidden_states1.to("cpu") - ehs1.to(dtype=weight_dtype)).abs().max() > 1e-2).sum() <= b_size * 2
569
+ # assert ((encoder_hidden_states2.to("cpu") - ehs2.to(dtype=weight_dtype)).abs().max() > 1e-2).sum() <= b_size * 2
570
+ # assert ((pool2.to("cpu") - p2.to(dtype=weight_dtype)).abs().max() > 1e-2).sum() <= b_size * 2
571
+ # logger.info("text encoder outputs verified")
572
+
573
+ # get size embeddings
574
+ orig_size = batch["original_sizes_hw"]
575
+ crop_size = batch["crop_top_lefts"]
576
+ target_size = batch["target_sizes_hw"]
577
+ embs = sdxl_train_util.get_size_embeddings(orig_size, crop_size, target_size, accelerator.device).to(weight_dtype)
578
+
579
+ # concat embeddings
580
+ vector_embedding = torch.cat([pool2, embs], dim=1).to(weight_dtype)
581
+ text_embedding = torch.cat([encoder_hidden_states1, encoder_hidden_states2], dim=2).to(weight_dtype)
582
+
583
+ # Sample noise, sample a random timestep for each image, and add noise to the latents,
584
+ # with noise offset and/or multires noise if specified
585
+ noise, noisy_latents, timesteps, huber_c = train_util.get_noise_noisy_latents_and_timesteps(args, noise_scheduler, latents)
586
+
587
+ noisy_latents = noisy_latents.to(weight_dtype) # TODO check why noisy_latents is not weight_dtype
588
+
589
+ # Predict the noise residual
590
+ with accelerator.autocast():
591
+ noise_pred = unet(noisy_latents, timesteps, text_embedding, vector_embedding)
592
+
593
+ target = noise
594
+
595
+ if (
596
+ args.min_snr_gamma
597
+ or args.scale_v_pred_loss_like_noise_pred
598
+ or args.v_pred_like_loss
599
+ or args.debiased_estimation_loss
600
+ or args.masked_loss
601
+ ):
602
+ # do not mean over batch dimension for snr weight or scale v-pred loss
603
+ loss = train_util.conditional_loss(noise_pred.float(), target.float(), reduction="none", loss_type=args.loss_type, huber_c=huber_c)
604
+ if args.masked_loss:
605
+ loss = apply_masked_loss(loss, batch)
606
+ loss = loss.mean([1, 2, 3])
607
+
608
+ if args.min_snr_gamma:
609
+ loss = apply_snr_weight(loss, timesteps, noise_scheduler, args.min_snr_gamma)
610
+ if args.scale_v_pred_loss_like_noise_pred:
611
+ loss = scale_v_prediction_loss_like_noise_prediction(loss, timesteps, noise_scheduler)
612
+ if args.v_pred_like_loss:
613
+ loss = add_v_prediction_like_loss(loss, timesteps, noise_scheduler, args.v_pred_like_loss)
614
+ if args.debiased_estimation_loss:
615
+ loss = apply_debiased_estimation(loss, timesteps, noise_scheduler)
616
+
617
+ loss = loss.mean() # mean over batch dimension
618
+ else:
619
+ loss = train_util.conditional_loss(noise_pred.float(), target.float(), reduction="mean", loss_type=args.loss_type, huber_c=huber_c)
620
+
621
+ accelerator.backward(loss)
622
+ if accelerator.sync_gradients and args.max_grad_norm != 0.0:
623
+ params_to_clip = []
624
+ for m in training_models:
625
+ params_to_clip.extend(m.parameters())
626
+ accelerator.clip_grad_norm_(params_to_clip, args.max_grad_norm)
627
+
628
+ optimizer.step()
629
+ lr_scheduler.step()
630
+ optimizer.zero_grad(set_to_none=True)
631
+
632
+ # Checks if the accelerator has performed an optimization step behind the scenes
633
+ if accelerator.sync_gradients:
634
+ progress_bar.update(1)
635
+ global_step += 1
636
+
637
+ sdxl_train_util.sample_images(
638
+ accelerator,
639
+ args,
640
+ None,
641
+ global_step,
642
+ accelerator.device,
643
+ vae,
644
+ [tokenizer1, tokenizer2],
645
+ [text_encoder1, text_encoder2],
646
+ unet,
647
+ )
648
+
649
+ # 指定ステップごとにモデルを保存
650
+ if args.save_every_n_steps is not None and global_step % args.save_every_n_steps == 0:
651
+ accelerator.wait_for_everyone()
652
+ if accelerator.is_main_process:
653
+ src_path = src_stable_diffusion_ckpt if save_stable_diffusion_format else src_diffusers_model_path
654
+ sdxl_train_util.save_sd_model_on_epoch_end_or_stepwise(
655
+ args,
656
+ False,
657
+ accelerator,
658
+ src_path,
659
+ save_stable_diffusion_format,
660
+ use_safetensors,
661
+ save_dtype,
662
+ epoch,
663
+ num_train_epochs,
664
+ global_step,
665
+ accelerator.unwrap_model(text_encoder1),
666
+ accelerator.unwrap_model(text_encoder2),
667
+ accelerator.unwrap_model(unet),
668
+ vae,
669
+ logit_scale,
670
+ ckpt_info,
671
+ )
672
+
673
+ current_loss = loss.detach().item() # 平均なのでbatch sizeは関係ないはず
674
+ if args.logging_dir is not None:
675
+ logs = {"loss": current_loss}
676
+ if block_lrs is None:
677
+ train_util.append_lr_to_logs(logs, lr_scheduler, args.optimizer_type, including_unet=train_unet)
678
+ else:
679
+ append_block_lr_to_logs(block_lrs, logs, lr_scheduler, args.optimizer_type) # U-Net is included in block_lrs
680
+
681
+ accelerator.log(logs, step=global_step)
682
+
683
+ loss_recorder.add(epoch=epoch, step=step, loss=current_loss)
684
+ avr_loss: float = loss_recorder.moving_average
685
+ logs = {"avr_loss": avr_loss} # , "lr": lr_scheduler.get_last_lr()[0]}
686
+ progress_bar.set_postfix(**logs)
687
+
688
+ if global_step >= args.max_train_steps:
689
+ break
690
+
691
+ if args.logging_dir is not None:
692
+ logs = {"loss/epoch": loss_recorder.moving_average}
693
+ accelerator.log(logs, step=epoch + 1)
694
+
695
+ accelerator.wait_for_everyone()
696
+
697
+ if args.save_every_n_epochs is not None:
698
+ if accelerator.is_main_process:
699
+ src_path = src_stable_diffusion_ckpt if save_stable_diffusion_format else src_diffusers_model_path
700
+ sdxl_train_util.save_sd_model_on_epoch_end_or_stepwise(
701
+ args,
702
+ True,
703
+ accelerator,
704
+ src_path,
705
+ save_stable_diffusion_format,
706
+ use_safetensors,
707
+ save_dtype,
708
+ epoch,
709
+ num_train_epochs,
710
+ global_step,
711
+ accelerator.unwrap_model(text_encoder1),
712
+ accelerator.unwrap_model(text_encoder2),
713
+ accelerator.unwrap_model(unet),
714
+ vae,
715
+ logit_scale,
716
+ ckpt_info,
717
+ )
718
+
719
+ sdxl_train_util.sample_images(
720
+ accelerator,
721
+ args,
722
+ epoch + 1,
723
+ global_step,
724
+ accelerator.device,
725
+ vae,
726
+ [tokenizer1, tokenizer2],
727
+ [text_encoder1, text_encoder2],
728
+ unet,
729
+ )
730
+
731
+ is_main_process = accelerator.is_main_process
732
+ # if is_main_process:
733
+ unet = accelerator.unwrap_model(unet)
734
+ text_encoder1 = accelerator.unwrap_model(text_encoder1)
735
+ text_encoder2 = accelerator.unwrap_model(text_encoder2)
736
+
737
+ accelerator.end_training()
738
+
739
+ if args.save_state or args.save_state_on_train_end:
740
+ train_util.save_state_on_train_end(args, accelerator)
741
+
742
+ del accelerator # この後メモリを使うのでこれは消す
743
+
744
+ if is_main_process:
745
+ src_path = src_stable_diffusion_ckpt if save_stable_diffusion_format else src_diffusers_model_path
746
+ sdxl_train_util.save_sd_model_on_train_end(
747
+ args,
748
+ src_path,
749
+ save_stable_diffusion_format,
750
+ use_safetensors,
751
+ save_dtype,
752
+ epoch,
753
+ global_step,
754
+ text_encoder1,
755
+ text_encoder2,
756
+ unet,
757
+ vae,
758
+ logit_scale,
759
+ ckpt_info,
760
+ )
761
+ logger.info("model saved.")
762
+
763
+
764
+ def setup_parser() -> argparse.ArgumentParser:
765
+ parser = argparse.ArgumentParser()
766
+
767
+ add_logging_arguments(parser)
768
+ train_util.add_sd_models_arguments(parser)
769
+ train_util.add_dataset_arguments(parser, True, True, True)
770
+ train_util.add_training_arguments(parser, False)
771
+ train_util.add_masked_loss_arguments(parser)
772
+ deepspeed_utils.add_deepspeed_arguments(parser)
773
+ train_util.add_sd_saving_arguments(parser)
774
+ train_util.add_optimizer_arguments(parser)
775
+ config_util.add_config_arguments(parser)
776
+ custom_train_functions.add_custom_train_arguments(parser)
777
+ sdxl_train_util.add_sdxl_training_arguments(parser)
778
+
779
+ parser.add_argument(
780
+ "--learning_rate_te1",
781
+ type=float,
782
+ default=None,
783
+ help="learning rate for text encoder 1 (ViT-L) / text encoder 1 (ViT-L)の学習率",
784
+ )
785
+ parser.add_argument(
786
+ "--learning_rate_te2",
787
+ type=float,
788
+ default=None,
789
+ help="learning rate for text encoder 2 (BiG-G) / text encoder 2 (BiG-G)の学習率",
790
+ )
791
+
792
+ parser.add_argument(
793
+ "--diffusers_xformers", action="store_true", help="use xformers by diffusers / Diffusersでxformersを使用する"
794
+ )
795
+ parser.add_argument("--train_text_encoder", action="store_true", help="train text encoder / text encoderも学習する")
796
+ parser.add_argument(
797
+ "--no_half_vae",
798
+ action="store_true",
799
+ help="do not use fp16/bf16 VAE in mixed precision (use float VAE) / mixed precisionでも fp16/bf16 VAEを使わずfloat VAEを使う",
800
+ )
801
+ parser.add_argument(
802
+ "--block_lr",
803
+ type=str,
804
+ default=None,
805
+ help=f"learning rates for each block of U-Net, comma-separated, {UNET_NUM_BLOCKS_FOR_BLOCK_LR} values / "
806
+ + f"U-Netの各ブロックの学習率、カンマ区切り、{UNET_NUM_BLOCKS_FOR_BLOCK_LR}個の値",
807
+ )
808
+ return parser
809
+
810
+
811
+ if __name__ == "__main__":
812
+ parser = setup_parser()
813
+
814
+ args = parser.parse_args()
815
+ train_util.verify_command_line_training_args(args)
816
+ args = train_util.read_config_from_file(args, parser)
817
+
818
+ train(args)