kawaimasa commited on
Commit
5f19913
1 Parent(s): 0c59db7

Upload 2 files

Browse files
test_edm2_weighting/sdxl_train.py ADDED
@@ -0,0 +1,961 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 group in params_to_optimize:
349
+ for p in group["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
+
359
+ if args.fused_optimizer_groups:
360
+ # fused backward pass: https://pytorch.org/tutorials/intermediate/optimizer_step_in_backward_tutorial.html
361
+ # Instead of creating an optimizer for all parameters as in the tutorial, we create an optimizer for each group of parameters.
362
+ # This balances memory usage and management complexity.
363
+
364
+ # calculate total number of parameters
365
+ n_total_params = sum(len(params["params"]) for params in params_to_optimize)
366
+ params_per_group = math.ceil(n_total_params / args.fused_optimizer_groups)
367
+
368
+ # split params into groups, keeping the learning rate the same for all params in a group
369
+ # this will increase the number of groups if the learning rate is different for different params (e.g. U-Net and text encoders)
370
+ grouped_params = []
371
+ param_group = []
372
+ param_group_lr = -1
373
+ for group in params_to_optimize:
374
+ lr = group["lr"]
375
+ for p in group["params"]:
376
+ # if the learning rate is different for different params, start a new group
377
+ if lr != param_group_lr:
378
+ if param_group:
379
+ grouped_params.append({"params": param_group, "lr": param_group_lr})
380
+ param_group = []
381
+ param_group_lr = lr
382
+
383
+ param_group.append(p)
384
+
385
+ # if the group has enough parameters, start a new group
386
+ if len(param_group) == params_per_group:
387
+ grouped_params.append({"params": param_group, "lr": param_group_lr})
388
+ param_group = []
389
+ param_group_lr = -1
390
+
391
+ if param_group:
392
+ grouped_params.append({"params": param_group, "lr": param_group_lr})
393
+
394
+ # prepare optimizers for each group
395
+ optimizers = []
396
+ for group in grouped_params:
397
+ _, _, optimizer = train_util.get_optimizer(args, trainable_params=[group])
398
+ optimizers.append(optimizer)
399
+ optimizer = optimizers[0] # avoid error in the following code
400
+
401
+ logger.info(f"using {len(optimizers)} optimizers for fused optimizer groups")
402
+
403
+ else:
404
+ _, _, optimizer = train_util.get_optimizer(args, trainable_params=params_to_optimize)
405
+
406
+ # dataloaderを準備する
407
+ # DataLoaderのプロセス数:0 は persistent_workers が使えないので注意
408
+ n_workers = min(args.max_data_loader_n_workers, os.cpu_count()) # cpu_count or max_data_loader_n_workers
409
+ train_dataloader = torch.utils.data.DataLoader(
410
+ train_dataset_group,
411
+ batch_size=1,
412
+ shuffle=True,
413
+ collate_fn=collator,
414
+ num_workers=n_workers,
415
+ persistent_workers=args.persistent_data_loader_workers,
416
+ )
417
+
418
+ # 学習ステップ数を計算する
419
+ if args.max_train_epochs is not None:
420
+ args.max_train_steps = args.max_train_epochs * math.ceil(
421
+ len(train_dataloader) / accelerator.num_processes / args.gradient_accumulation_steps
422
+ )
423
+ accelerator.print(
424
+ f"override steps. steps for {args.max_train_epochs} epochs is / 指定エポックまでのステップ数: {args.max_train_steps}"
425
+ )
426
+
427
+ # データセット側にも学習ステップを送信
428
+ train_dataset_group.set_max_train_steps(args.max_train_steps)
429
+
430
+ # lr schedulerを用意する
431
+ if args.fused_optimizer_groups:
432
+ # prepare lr schedulers for each optimizer
433
+ lr_schedulers = [train_util.get_scheduler_fix(args, optimizer, accelerator.num_processes) for optimizer in optimizers]
434
+ lr_scheduler = lr_schedulers[0] # avoid error in the following code
435
+ else:
436
+ lr_scheduler = train_util.get_scheduler_fix(args, optimizer, accelerator.num_processes)
437
+
438
+ # 実験的機能:勾配も含めたfp16/bf16学習を行う モデル全体をfp16/bf16にする
439
+ if args.full_fp16:
440
+ assert (
441
+ args.mixed_precision == "fp16"
442
+ ), "full_fp16 requires mixed precision='fp16' / full_fp16を使う場合はmixed_precision='fp16'を指定してください。"
443
+ accelerator.print("enable full fp16 training.")
444
+ unet.to(weight_dtype)
445
+ text_encoder1.to(weight_dtype)
446
+ text_encoder2.to(weight_dtype)
447
+ elif args.full_bf16:
448
+ assert (
449
+ args.mixed_precision == "bf16"
450
+ ), "full_bf16 requires mixed precision='bf16' / full_bf16を使う場合はmixed_precision='bf16'を指定してください。"
451
+ accelerator.print("enable full bf16 training.")
452
+ unet.to(weight_dtype)
453
+ text_encoder1.to(weight_dtype)
454
+ text_encoder2.to(weight_dtype)
455
+
456
+ # freeze last layer and final_layer_norm in te1 since we use the output of the penultimate layer
457
+ if train_text_encoder1:
458
+ text_encoder1.text_model.encoder.layers[-1].requires_grad_(False)
459
+ text_encoder1.text_model.final_layer_norm.requires_grad_(False)
460
+
461
+ if args.deepspeed:
462
+ ds_model = deepspeed_utils.prepare_deepspeed_model(
463
+ args,
464
+ unet=unet if train_unet else None,
465
+ text_encoder1=text_encoder1 if train_text_encoder1 else None,
466
+ text_encoder2=text_encoder2 if train_text_encoder2 else None,
467
+ )
468
+ # most of ZeRO stage uses optimizer partitioning, so we have to prepare optimizer and ds_model at the same time. # pull/1139#issuecomment-1986790007
469
+ ds_model, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
470
+ ds_model, optimizer, train_dataloader, lr_scheduler
471
+ )
472
+ training_models = [ds_model]
473
+
474
+ else:
475
+ # acceleratorがなんかよろしくやってくれるらしい
476
+ if train_unet:
477
+ unet = accelerator.prepare(unet)
478
+ if train_text_encoder1:
479
+ text_encoder1 = accelerator.prepare(text_encoder1)
480
+ if train_text_encoder2:
481
+ text_encoder2 = accelerator.prepare(text_encoder2)
482
+ optimizer, train_dataloader, lr_scheduler = accelerator.prepare(optimizer, train_dataloader, lr_scheduler)
483
+
484
+ # TextEncoderの出力をキャッシュするときにはCPUへ移動する
485
+ if args.cache_text_encoder_outputs:
486
+ # move Text Encoders for sampling images. Text Encoder doesn't work on CPU with fp16
487
+ text_encoder1.to("cpu", dtype=torch.float32)
488
+ text_encoder2.to("cpu", dtype=torch.float32)
489
+ clean_memory_on_device(accelerator.device)
490
+ else:
491
+ # make sure Text Encoders are on GPU
492
+ text_encoder1.to(accelerator.device)
493
+ text_encoder2.to(accelerator.device)
494
+
495
+ # 実験的機能:勾配も含めたfp16学習を行う PyTorchにパッチを当ててfp16でのgrad scaleを有効にする
496
+ if args.full_fp16:
497
+ # During deepseed training, accelerate not handles fp16/bf16|mixed precision directly via scaler. Let deepspeed engine do.
498
+ # -> But we think it's ok to patch accelerator even if deepspeed is enabled.
499
+ train_util.patch_accelerator_for_fp16_training(accelerator)
500
+
501
+ # resumeする
502
+ train_util.resume_from_local_or_hf_if_specified(accelerator, args)
503
+
504
+ if args.fused_backward_pass:
505
+ # use fused optimizer for backward pass: other optimizers will be supported in the future
506
+ import library.adafactor_fused
507
+
508
+ library.adafactor_fused.patch_adafactor_fused(optimizer)
509
+ for param_group in optimizer.param_groups:
510
+ for parameter in param_group["params"]:
511
+ if parameter.requires_grad:
512
+
513
+ def __grad_hook(tensor: torch.Tensor, param_group=param_group):
514
+ if accelerator.sync_gradients and args.max_grad_norm != 0.0:
515
+ accelerator.clip_grad_norm_(tensor, args.max_grad_norm)
516
+ optimizer.step_param(tensor, param_group)
517
+ tensor.grad = None
518
+
519
+ parameter.register_post_accumulate_grad_hook(__grad_hook)
520
+
521
+ elif args.fused_optimizer_groups:
522
+ # prepare for additional optimizers and lr schedulers
523
+ for i in range(1, len(optimizers)):
524
+ optimizers[i] = accelerator.prepare(optimizers[i])
525
+ lr_schedulers[i] = accelerator.prepare(lr_schedulers[i])
526
+
527
+ # counters are used to determine when to step the optimizer
528
+ global optimizer_hooked_count
529
+ global num_parameters_per_group
530
+ global parameter_optimizer_map
531
+
532
+ optimizer_hooked_count = {}
533
+ num_parameters_per_group = [0] * len(optimizers)
534
+ parameter_optimizer_map = {}
535
+
536
+ for opt_idx, optimizer in enumerate(optimizers):
537
+ for param_group in optimizer.param_groups:
538
+ for parameter in param_group["params"]:
539
+ if parameter.requires_grad:
540
+
541
+ def optimizer_hook(parameter: torch.Tensor):
542
+ if accelerator.sync_gradients and args.max_grad_norm != 0.0:
543
+ accelerator.clip_grad_norm_(parameter, args.max_grad_norm)
544
+
545
+ i = parameter_optimizer_map[parameter]
546
+ optimizer_hooked_count[i] += 1
547
+ if optimizer_hooked_count[i] == num_parameters_per_group[i]:
548
+ optimizers[i].step()
549
+ optimizers[i].zero_grad(set_to_none=True)
550
+
551
+ parameter.register_post_accumulate_grad_hook(optimizer_hook)
552
+ parameter_optimizer_map[parameter] = opt_idx
553
+ num_parameters_per_group[opt_idx] += 1
554
+
555
+ # epoch数を計算する
556
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
557
+ num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
558
+ if (args.save_n_epoch_ratio is not None) and (args.save_n_epoch_ratio > 0):
559
+ args.save_every_n_epochs = math.floor(num_train_epochs / args.save_n_epoch_ratio) or 1
560
+
561
+ # 学習する
562
+ # total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
563
+ accelerator.print("running training / 学習開始")
564
+ accelerator.print(f" num examples / サンプル数: {train_dataset_group.num_train_images}")
565
+ accelerator.print(f" num batches per epoch / 1epochのバッチ数: {len(train_dataloader)}")
566
+ accelerator.print(f" num epochs / epoch数: {num_train_epochs}")
567
+ accelerator.print(
568
+ f" batch size per device / バッチサイズ: {', '.join([str(d.batch_size) for d in train_dataset_group.datasets])}"
569
+ )
570
+ # accelerator.print(
571
+ # f" total train batch size (with parallel & distributed & accumulation) / 総バッチサイズ(並列学習、勾配合計含む): {total_batch_size}"
572
+ # )
573
+ accelerator.print(f" gradient accumulation steps / 勾配を合計するステップ数 = {args.gradient_accumulation_steps}")
574
+ accelerator.print(f" total optimization steps / 学習ステップ数: {args.max_train_steps}")
575
+
576
+ progress_bar = tqdm(range(args.max_train_steps), smoothing=0, disable=not accelerator.is_local_main_process, desc="steps")
577
+ global_step = 0
578
+
579
+ noise_scheduler = DDPMScheduler(
580
+ beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", num_train_timesteps=1000, clip_sample=False
581
+ )
582
+ # prepare_scheduler_for_custom_training(noise_scheduler, accelerator.device)
583
+
584
+ if args.zero_terminal_snr:
585
+ custom_train_functions.fix_noise_scheduler_betas_for_zero_terminal_snr(noise_scheduler)
586
+
587
+ prepare_scheduler_for_custom_training(noise_scheduler, accelerator.device)
588
+
589
+ if args.zero_terminal_snr:
590
+ custom_train_functions.fix_noise_scheduler_betas_for_zero_terminal_snr(noise_scheduler)
591
+ edm2_weighting = __import__('t').EDM2WeightingWrapper(noise_scheduler=noise_scheduler)
592
+ if accelerator.is_main_process:
593
+ init_kwargs = {}
594
+ if args.wandb_run_name:
595
+ init_kwargs["wandb"] = {"name": args.wandb_run_name}
596
+ if args.log_tracker_config is not None:
597
+ init_kwargs = toml.load(args.log_tracker_config)
598
+ accelerator.init_trackers(
599
+ "finetuning" if args.log_tracker_name is None else args.log_tracker_name,
600
+ config=train_util.get_sanitized_config_or_none(args),
601
+ init_kwargs=init_kwargs,
602
+ )
603
+
604
+ # For --sample_at_first
605
+ sdxl_train_util.sample_images(
606
+ accelerator, args, 0, global_step, accelerator.device, vae, [tokenizer1, tokenizer2], [text_encoder1, text_encoder2], unet
607
+ )
608
+
609
+ loss_recorder = train_util.LossRecorder()
610
+ for epoch in range(num_train_epochs):
611
+ accelerator.print(f"\nepoch {epoch+1}/{num_train_epochs}")
612
+ current_epoch.value = epoch + 1
613
+
614
+ for m in training_models:
615
+ m.train()
616
+
617
+ for step, batch in enumerate(train_dataloader):
618
+ current_step.value = global_step
619
+
620
+ if args.fused_optimizer_groups:
621
+ optimizer_hooked_count = {i: 0 for i in range(len(optimizers))} # reset counter for each step
622
+
623
+ with accelerator.accumulate(*training_models):
624
+ if "latents" in batch and batch["latents"] is not None:
625
+ latents = batch["latents"].to(accelerator.device).to(dtype=weight_dtype)
626
+ else:
627
+ with torch.no_grad():
628
+ # latentに変換
629
+ latents = vae.encode(batch["images"].to(vae_dtype)).latent_dist.sample().to(weight_dtype)
630
+
631
+ # NaNが含まれていれば警告を表示し0に置き換える
632
+ if torch.any(torch.isnan(latents)):
633
+ accelerator.print("NaN found in latents, replacing with zeros")
634
+ latents = torch.nan_to_num(latents, 0, out=latents)
635
+ latents = latents * sdxl_model_util.VAE_SCALE_FACTOR
636
+
637
+ if "text_encoder_outputs1_list" not in batch or batch["text_encoder_outputs1_list"] is None:
638
+ input_ids1 = batch["input_ids"]
639
+ input_ids2 = batch["input_ids2"]
640
+ with torch.set_grad_enabled(args.train_text_encoder):
641
+ # Get the text embedding for conditioning
642
+ # TODO support weighted captions
643
+ # if args.weighted_captions:
644
+ # encoder_hidden_states = get_weighted_text_embeddings(
645
+ # tokenizer,
646
+ # text_encoder,
647
+ # batch["captions"],
648
+ # accelerator.device,
649
+ # args.max_token_length // 75 if args.max_token_length else 1,
650
+ # clip_skip=args.clip_skip,
651
+ # )
652
+ # else:
653
+ input_ids1 = input_ids1.to(accelerator.device)
654
+ input_ids2 = input_ids2.to(accelerator.device)
655
+ # unwrap_model is fine for models not wrapped by accelerator
656
+ encoder_hidden_states1, encoder_hidden_states2, pool2 = train_util.get_hidden_states_sdxl(
657
+ args.max_token_length,
658
+ input_ids1,
659
+ input_ids2,
660
+ tokenizer1,
661
+ tokenizer2,
662
+ text_encoder1,
663
+ text_encoder2,
664
+ None if not args.full_fp16 else weight_dtype,
665
+ accelerator=accelerator,
666
+ )
667
+ else:
668
+ encoder_hidden_states1 = batch["text_encoder_outputs1_list"].to(accelerator.device).to(weight_dtype)
669
+ encoder_hidden_states2 = batch["text_encoder_outputs2_list"].to(accelerator.device).to(weight_dtype)
670
+ pool2 = batch["text_encoder_pool2_list"].to(accelerator.device).to(weight_dtype)
671
+
672
+ # # verify that the text encoder outputs are correct
673
+ # ehs1, ehs2, p2 = train_util.get_hidden_states_sdxl(
674
+ # args.max_token_length,
675
+ # batch["input_ids"].to(text_encoder1.device),
676
+ # batch["input_ids2"].to(text_encoder1.device),
677
+ # tokenizer1,
678
+ # tokenizer2,
679
+ # text_encoder1,
680
+ # text_encoder2,
681
+ # None if not args.full_fp16 else weight_dtype,
682
+ # )
683
+ # b_size = encoder_hidden_states1.shape[0]
684
+ # assert ((encoder_hidden_states1.to("cpu") - ehs1.to(dtype=weight_dtype)).abs().max() > 1e-2).sum() <= b_size * 2
685
+ # assert ((encoder_hidden_states2.to("cpu") - ehs2.to(dtype=weight_dtype)).abs().max() > 1e-2).sum() <= b_size * 2
686
+ # assert ((pool2.to("cpu") - p2.to(dtype=weight_dtype)).abs().max() > 1e-2).sum() <= b_size * 2
687
+ # logger.info("text encoder outputs verified")
688
+
689
+ # get size embeddings
690
+ orig_size = batch["original_sizes_hw"]
691
+ crop_size = batch["crop_top_lefts"]
692
+ target_size = batch["target_sizes_hw"]
693
+ embs = sdxl_train_util.get_size_embeddings(orig_size, crop_size, target_size, accelerator.device).to(weight_dtype)
694
+
695
+ # concat embeddings
696
+ vector_embedding = torch.cat([pool2, embs], dim=1).to(weight_dtype)
697
+ text_embedding = torch.cat([encoder_hidden_states1, encoder_hidden_states2], dim=2).to(weight_dtype)
698
+
699
+ # Sample noise, sample a random timestep for each image, and add noise to the latents,
700
+ # with noise offset and/or multires noise if specified
701
+ noise, noisy_latents, timesteps, huber_c = train_util.get_noise_noisy_latents_and_timesteps(
702
+ args, noise_scheduler, latents
703
+ )
704
+
705
+ noisy_latents = noisy_latents.to(weight_dtype) # TODO check why noisy_latents is not weight_dtype
706
+
707
+ # Predict the noise residual
708
+ with accelerator.autocast():
709
+ noise_pred = unet(noisy_latents, timesteps, text_embedding, vector_embedding)
710
+
711
+ if args.v_parameterization:
712
+ # v-parameterization training
713
+ target = noise_scheduler.get_velocity(latents, noise, timesteps)
714
+ else:
715
+ target = noise
716
+
717
+ if (
718
+ args.min_snr_gamma
719
+ or args.scale_v_pred_loss_like_noise_pred
720
+ or args.v_pred_like_loss
721
+ or args.debiased_estimation_loss
722
+ or args.masked_loss
723
+ ):
724
+ # do not mean over batch dimension for snr weight or scale v-pred loss
725
+ loss = train_util.conditional_loss(
726
+ noise_pred.float(), target.float(), reduction="none", loss_type=args.loss_type, huber_c=huber_c
727
+ )
728
+ if args.masked_loss or ("alpha_masks" in batch and batch["alpha_masks"] is not None):
729
+ loss = apply_masked_loss(loss, batch)
730
+ loss = loss.mean([1, 2, 3])
731
+
732
+ if args.min_snr_gamma:
733
+ loss = apply_snr_weight(loss, timesteps, noise_scheduler, args.min_snr_gamma, args.v_parameterization)
734
+ if args.scale_v_pred_loss_like_noise_pred:
735
+ loss = scale_v_prediction_loss_like_noise_prediction(loss, timesteps, noise_scheduler)
736
+ if args.v_pred_like_loss:
737
+ loss = add_v_prediction_like_loss(loss, timesteps, noise_scheduler, args.v_pred_like_loss)
738
+ if args.debiased_estimation_loss:
739
+ loss = apply_debiased_estimation(loss, timesteps, noise_scheduler, args.v_parameterization)
740
+ loss = edm2_weighting(loss, timesteps)
741
+ # print(f"Loss after edm2_weighting: {loss.shape}")
742
+ loss = loss.mean() # mean over batch dimension
743
+ else:
744
+ loss = train_util.conditional_loss(noise_pred.float(), target.float(), reduction="none", loss_type=args.loss_type, huber_c=huber_c)
745
+ loss = loss.mean([1, 2, 3])
746
+ loss = edm2_weighting(loss, timesteps)
747
+ loss = loss.mean()
748
+
749
+ accelerator.backward(loss)
750
+
751
+ if not (args.fused_backward_pass or args.fused_optimizer_groups):
752
+ if accelerator.sync_gradients and args.max_grad_norm != 0.0:
753
+ params_to_clip = []
754
+ for m in training_models:
755
+ params_to_clip.extend(m.parameters())
756
+ accelerator.clip_grad_norm_(params_to_clip, args.max_grad_norm)
757
+
758
+ optimizer.step()
759
+ lr_scheduler.step()
760
+ optimizer.zero_grad(set_to_none=True)
761
+ else:
762
+ # optimizer.step() and optimizer.zero_grad() are called in the optimizer hook
763
+ lr_scheduler.step()
764
+ if args.fused_optimizer_groups:
765
+ for i in range(1, len(optimizers)):
766
+ lr_schedulers[i].step()
767
+
768
+ # Checks if the accelerator has performed an optimization step behind the scenes
769
+ if accelerator.sync_gradients:
770
+ progress_bar.update(1)
771
+ global_step += 1
772
+
773
+ sdxl_train_util.sample_images(
774
+ accelerator,
775
+ args,
776
+ None,
777
+ global_step,
778
+ accelerator.device,
779
+ vae,
780
+ [tokenizer1, tokenizer2],
781
+ [text_encoder1, text_encoder2],
782
+ unet,
783
+ )
784
+
785
+ # 指定ステップごとにモデルを保存
786
+ if args.save_every_n_steps is not None and global_step % args.save_every_n_steps == 0:
787
+ accelerator.wait_for_everyone()
788
+ if accelerator.is_main_process:
789
+ edm2_weighting.save_model(f"learned-loss-weights-{epoch + 1}.sft")
790
+ src_path = src_stable_diffusion_ckpt if save_stable_diffusion_format else src_diffusers_model_path
791
+ sdxl_train_util.save_sd_model_on_epoch_end_or_stepwise(
792
+ args,
793
+ False,
794
+ accelerator,
795
+ src_path,
796
+ save_stable_diffusion_format,
797
+ use_safetensors,
798
+ save_dtype,
799
+ epoch,
800
+ num_train_epochs,
801
+ global_step,
802
+ accelerator.unwrap_model(text_encoder1),
803
+ accelerator.unwrap_model(text_encoder2),
804
+ accelerator.unwrap_model(unet),
805
+ vae,
806
+ logit_scale,
807
+ ckpt_info,
808
+ )
809
+
810
+ current_loss = loss.detach().item() # 平均なのでbatch sizeは関係ないはず
811
+ if args.logging_dir is not None:
812
+ logs = {"loss": current_loss}
813
+ if block_lrs is None:
814
+ train_util.append_lr_to_logs(logs, lr_scheduler, args.optimizer_type, including_unet=train_unet)
815
+ else:
816
+ append_block_lr_to_logs(block_lrs, logs, lr_scheduler, args.optimizer_type) # U-Net is included in block_lrs
817
+
818
+ accelerator.log(logs, step=global_step)
819
+
820
+ loss_recorder.add(epoch=epoch, step=step, loss=current_loss)
821
+ avr_loss: float = loss_recorder.moving_average
822
+ logs = {"avr_loss": avr_loss} # , "lr": lr_scheduler.get_last_lr()[0]}
823
+ progress_bar.set_postfix(**logs)
824
+
825
+ if global_step >= args.max_train_steps:
826
+ break
827
+
828
+ if args.logging_dir is not None:
829
+ logs = {"loss/epoch": loss_recorder.moving_average}
830
+ accelerator.log(logs, step=epoch + 1)
831
+
832
+ accelerator.wait_for_everyone()
833
+
834
+ if args.save_every_n_epochs is not None:
835
+ if accelerator.is_main_process:
836
+ src_path = src_stable_diffusion_ckpt if save_stable_diffusion_format else src_diffusers_model_path
837
+ sdxl_train_util.save_sd_model_on_epoch_end_or_stepwise(
838
+ args,
839
+ True,
840
+ accelerator,
841
+ src_path,
842
+ save_stable_diffusion_format,
843
+ use_safetensors,
844
+ save_dtype,
845
+ epoch,
846
+ num_train_epochs,
847
+ global_step,
848
+ accelerator.unwrap_model(text_encoder1),
849
+ accelerator.unwrap_model(text_encoder2),
850
+ accelerator.unwrap_model(unet),
851
+ vae,
852
+ logit_scale,
853
+ ckpt_info,
854
+ )
855
+
856
+ sdxl_train_util.sample_images(
857
+ accelerator,
858
+ args,
859
+ epoch + 1,
860
+ global_step,
861
+ accelerator.device,
862
+ vae,
863
+ [tokenizer1, tokenizer2],
864
+ [text_encoder1, text_encoder2],
865
+ unet,
866
+ )
867
+
868
+ is_main_process = accelerator.is_main_process
869
+ # if is_main_process:
870
+ unet = accelerator.unwrap_model(unet)
871
+ text_encoder1 = accelerator.unwrap_model(text_encoder1)
872
+ text_encoder2 = accelerator.unwrap_model(text_encoder2)
873
+
874
+ accelerator.end_training()
875
+
876
+ if args.save_state or args.save_state_on_train_end:
877
+ train_util.save_state_on_train_end(args, accelerator)
878
+
879
+ del accelerator # この後メモリを使うのでこれは消す
880
+
881
+ if is_main_process:
882
+ src_path = src_stable_diffusion_ckpt if save_stable_diffusion_format else src_diffusers_model_path
883
+ sdxl_train_util.save_sd_model_on_train_end(
884
+ args,
885
+ src_path,
886
+ save_stable_diffusion_format,
887
+ use_safetensors,
888
+ save_dtype,
889
+ epoch,
890
+ global_step,
891
+ text_encoder1,
892
+ text_encoder2,
893
+ unet,
894
+ vae,
895
+ logit_scale,
896
+ ckpt_info,
897
+ )
898
+ logger.info("model saved.")
899
+
900
+
901
+ def setup_parser() -> argparse.ArgumentParser:
902
+ parser = argparse.ArgumentParser()
903
+
904
+ add_logging_arguments(parser)
905
+ train_util.add_sd_models_arguments(parser)
906
+ train_util.add_dataset_arguments(parser, True, True, True)
907
+ train_util.add_training_arguments(parser, False)
908
+ train_util.add_masked_loss_arguments(parser)
909
+ deepspeed_utils.add_deepspeed_arguments(parser)
910
+ train_util.add_sd_saving_arguments(parser)
911
+ train_util.add_optimizer_arguments(parser)
912
+ config_util.add_config_arguments(parser)
913
+ custom_train_functions.add_custom_train_arguments(parser)
914
+ sdxl_train_util.add_sdxl_training_arguments(parser)
915
+
916
+ parser.add_argument(
917
+ "--learning_rate_te1",
918
+ type=float,
919
+ default=None,
920
+ help="learning rate for text encoder 1 (ViT-L) / text encoder 1 (ViT-L)の学習率",
921
+ )
922
+ parser.add_argument(
923
+ "--learning_rate_te2",
924
+ type=float,
925
+ default=None,
926
+ help="learning rate for text encoder 2 (BiG-G) / text encoder 2 (BiG-G)の学習率",
927
+ )
928
+
929
+ parser.add_argument(
930
+ "--diffusers_xformers", action="store_true", help="use xformers by diffusers / Diffusersでxformersを使用する"
931
+ )
932
+ parser.add_argument("--train_text_encoder", action="store_true", help="train text encoder / text encoderも学習する")
933
+ parser.add_argument(
934
+ "--no_half_vae",
935
+ action="store_true",
936
+ help="do not use fp16/bf16 VAE in mixed precision (use float VAE) / mixed precisionでも fp16/bf16 VAEを使わずfloat VAEを使う",
937
+ )
938
+ parser.add_argument(
939
+ "--block_lr",
940
+ type=str,
941
+ default=None,
942
+ help=f"learning rates for each block of U-Net, comma-separated, {UNET_NUM_BLOCKS_FOR_BLOCK_LR} values / "
943
+ + f"U-Netの各ブロックの学習率、カンマ区切り、{UNET_NUM_BLOCKS_FOR_BLOCK_LR}個の値",
944
+ )
945
+ parser.add_argument(
946
+ "--fused_optimizer_groups",
947
+ type=int,
948
+ default=None,
949
+ help="number of optimizers for fused backward pass and optimizer step / fused backward passとoptimizer stepのためのoptimizer数",
950
+ )
951
+ return parser
952
+
953
+
954
+ if __name__ == "__main__":
955
+ parser = setup_parser()
956
+
957
+ args = parser.parse_args()
958
+ train_util.verify_command_line_training_args(args)
959
+ args = train_util.read_config_from_file(args, parser)
960
+
961
+ train(args)
test_edm2_weighting/t.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import numpy as np
4
+
5
+ from safetensors.torch import load_model, save_model
6
+
7
+
8
+ def normalize(x: torch.Tensor, dim=None, eps=1e-4) -> torch.Tensor:
9
+ if dim is None:
10
+ dim = list(range(1, x.ndim))
11
+ norm = torch.linalg.vector_norm(
12
+ x, dim=dim, keepdim=True, dtype=torch.float32) # type: torch.Tensor
13
+ norm = torch.add(eps, norm, alpha=np.sqrt(norm.numel() / x.numel()))
14
+ norm_detached = norm.detach().to(x.dtype) # Detach and cast to x's dtype
15
+ return x / norm_detached
16
+ # return x / norm.to(x.dtype)
17
+
18
+
19
+ class FourierFeatureExtractor(nn.Module):
20
+ def __init__(self, num_channels, bandwidth=1):
21
+ super().__init__()
22
+ self.register_buffer('freqs', 2 * torch.pi *
23
+ torch.randn(num_channels) * bandwidth)
24
+ self.register_buffer('phases', 2 * torch.pi * torch.rand(num_channels))
25
+ self.sqrt_two = torch.sqrt(torch.tensor(2))
26
+
27
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
28
+ y = x.to(torch.float32)
29
+ y = y.ger(self.freqs.to(torch.float32))
30
+ y = y + self.phases.to(torch.float32) # type: torch.Tensor
31
+ y = y.cos() * self.sqrt_two
32
+ return y.to(x.dtype)
33
+
34
+
35
+ class NormalizedLinearLayer(nn.Module):
36
+ def __init__(self, in_channels, out_channels, kernel):
37
+ super().__init__()
38
+ self.out_channels = out_channels
39
+ self.weight = nn.Parameter(torch.randn(
40
+ out_channels, in_channels, *kernel))
41
+
42
+ def forward(self, x: torch.Tensor, gain=1) -> torch.Tensor:
43
+ w = self.weight.to(torch.float32)
44
+ if self.training:
45
+ with torch.no_grad():
46
+ self.weight.copy_(normalize(w)) # forced weight normalization
47
+ w = normalize(w) # traditional weight normalization
48
+ # type: torch.Tensor # magnitude-preserving scaling
49
+ w = w * (gain / np.sqrt(w[0].numel()))
50
+ w = w.to(x.dtype)
51
+ if w.ndim == 2:
52
+ return x @ w.t()
53
+ assert w.ndim == 4
54
+ return nn.functional.conv2d(x, w, padding=(w.shape[-1]//2,))
55
+
56
+
57
+ class AdaptiveLossWeightMLP(nn.Module):
58
+ def __init__(
59
+ self,
60
+ noise_scheduler,
61
+ logvar_channels=128,
62
+ device='cuda',
63
+ **kwargs
64
+ ):
65
+ super().__init__()
66
+ self.device = device
67
+ self.noise_scheduler = noise_scheduler
68
+ self.noise_scheduler.alphas_cumprod = self.noise_scheduler.alphas_cumprod.to(device)
69
+
70
+ self.a_bar_mean = noise_scheduler.alphas_cumprod.mean().to(device)
71
+ self.a_bar_std = noise_scheduler.alphas_cumprod.std().to(device)
72
+ self.alphas_cumprod = noise_scheduler.alphas_cumprod.to(device)
73
+
74
+ self.logvar_fourier = FourierFeatureExtractor(logvar_channels).to(device)
75
+ # kernel = []? (not in code given, added matching edm2)
76
+ self.logvar_linear = NormalizedLinearLayer(
77
+ logvar_channels, 1, kernel=[]).to(device)
78
+
79
+ def _forward(self, timesteps: torch.Tensor):
80
+ return self.compute_variance(timesteps)
81
+
82
+ def forward(self, loss: torch.Tensor, timesteps):
83
+ adaptive_loss_weights = self.compute_variance(timesteps)
84
+ # type: torch.Tensor
85
+ loss_scaled = loss / torch.exp(adaptive_loss_weights)
86
+ # loss = loss_scaled + adaptive_loss_weights # type: torch.Tensor
87
+
88
+ # stdev, mean = torch.std_mean(loss)
89
+ # print(f"{mean=:.4f} {stdev=:.4f}")
90
+
91
+ return loss_scaled
92
+
93
+ def compute_variance(self, timesteps: torch.Tensor):
94
+ return self._compute_ddpm_variance(timesteps)
95
+
96
+ def _compute_ddpm_variance(self, timesteps: torch.Tensor):
97
+ timesteps = timesteps.to(self.device)
98
+ a_bar = self.noise_scheduler.alphas_cumprod[timesteps]
99
+ c_noise = a_bar.sub(self.a_bar_mean).div_(self.a_bar_std)
100
+ return self.logvar_linear(self.logvar_fourier(c_noise)).squeeze()
101
+
102
+
103
+ class EDM2WeightingWrapper:
104
+ def __init__(self,
105
+ noise_scheduler,
106
+ optimizer=torch.optim.AdamW,
107
+ lr=5e-3, optimizer_args={'weight_decay': 0},
108
+ logvar_channels=128,
109
+ device="cuda",
110
+ ):
111
+ """
112
+ Initialize EDM2Loss with Fourier features for training with dynamic loss weighting.
113
+
114
+ :param optimizer: Optimizer class to use.
115
+ :param lr: Learning rate for the optimizer.
116
+ :param optimizer_args: Additional arguments for the optimizer.
117
+ :param device: Device to run computations on.
118
+ :param logvar_channels: Fourier decomposition complexity.
119
+ """
120
+ self.device = device
121
+ noise_scheduler.alphas_cumprod = noise_scheduler.alphas_cumprod.to(device)
122
+ self.model = AdaptiveLossWeightMLP(
123
+ noise_scheduler=noise_scheduler,
124
+ logvar_channels=logvar_channels,
125
+ device=device
126
+ ).to(device)
127
+ # # モデルのすべてのパラメータを指定されたデバイスに移動
128
+ # for param in self.model.parameters():
129
+ # param.data = param.data.to(device)
130
+
131
+ self.model.train(mode=True)
132
+ self.optimizer = optimizer(
133
+ self.model.parameters(), lr=lr, **optimizer_args)
134
+
135
+ self.model.train(mode=True) # Ensure the model is in training mode
136
+
137
+
138
+ def __call__(self, loss, timesteps):
139
+ """
140
+ Compute the weighted loss and backpropagate it through the loss_module.
141
+
142
+ :param timesteps: Tensor of timesteps (shape: [batch_size]).
143
+ :param loss: Tensor of individual losses (shape: [batch_size]).
144
+ :return: Scalar tensor representing the total weighted loss.
145
+ """
146
+ timesteps = timesteps.to(self.device)
147
+ loss = loss.to(self.device)
148
+
149
+ # Forward pass through the loss_module
150
+ weighted_losses = self.model(loss, timesteps)
151
+ weighted_loss = weighted_losses.mean()
152
+
153
+ # Backward pass for loss_module
154
+ # Only compute gradients for self.model, don't touch anything else
155
+ weighted_loss.backward(
156
+ retain_graph=True, inputs=list(self.model.parameters()))
157
+
158
+ self.optimizer.step()
159
+ self.optimizer.zero_grad()
160
+
161
+ return weighted_losses
162
+
163
+ def save_model(self, path):
164
+ save_model(self.model, path)
165
+
166
+ def load_model(self, path):
167
+ load_model(self.model, path)