argylegargoyle123 commited on
Commit
81c7085
1 Parent(s): 4e4c632

Upload 3 files

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