ACCC1380 commited on
Commit
94326ff
1 Parent(s): 1eb9457

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

Browse files
lora-scripts/sd-scripts/sdxl_train_control_net_lllite_old.py ADDED
@@ -0,0 +1,586 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import math
4
+ import os
5
+ import random
6
+ import time
7
+ from multiprocessing import Value
8
+ from types import SimpleNamespace
9
+ import toml
10
+
11
+ from tqdm import tqdm
12
+
13
+ import torch
14
+ from library.device_utils import init_ipex, clean_memory_on_device
15
+ init_ipex()
16
+
17
+ from torch.nn.parallel import DistributedDataParallel as DDP
18
+ from accelerate.utils import set_seed
19
+ from diffusers import DDPMScheduler, ControlNetModel
20
+ from safetensors.torch import load_file
21
+ from library import deepspeed_utils, sai_model_spec, sdxl_model_util, sdxl_original_unet, sdxl_train_util
22
+
23
+ import library.model_util as model_util
24
+ import library.train_util as train_util
25
+ import library.config_util as config_util
26
+ from library.config_util import (
27
+ ConfigSanitizer,
28
+ BlueprintGenerator,
29
+ )
30
+ import library.huggingface_util as huggingface_util
31
+ import library.custom_train_functions as custom_train_functions
32
+ from library.custom_train_functions import (
33
+ add_v_prediction_like_loss,
34
+ apply_snr_weight,
35
+ prepare_scheduler_for_custom_training,
36
+ pyramid_noise_like,
37
+ apply_noise_offset,
38
+ scale_v_prediction_loss_like_noise_prediction,
39
+ apply_debiased_estimation,
40
+ )
41
+ import networks.control_net_lllite as control_net_lllite
42
+ from library.utils import setup_logging, add_logging_arguments
43
+
44
+ setup_logging()
45
+ import logging
46
+
47
+ logger = logging.getLogger(__name__)
48
+
49
+
50
+ # TODO 他のスクリプトと共通化する
51
+ def generate_step_logs(args: argparse.Namespace, current_loss, avr_loss, lr_scheduler):
52
+ logs = {
53
+ "loss/current": current_loss,
54
+ "loss/average": avr_loss,
55
+ "lr": lr_scheduler.get_last_lr()[0],
56
+ }
57
+
58
+ if args.optimizer_type.lower().startswith("DAdapt".lower()):
59
+ logs["lr/d*lr"] = lr_scheduler.optimizers[-1].param_groups[0]["d"] * lr_scheduler.optimizers[-1].param_groups[0]["lr"]
60
+
61
+ return logs
62
+
63
+
64
+ def train(args):
65
+ train_util.verify_training_args(args)
66
+ train_util.prepare_dataset_args(args, True)
67
+ sdxl_train_util.verify_sdxl_training_args(args)
68
+ setup_logging(args, reset=True)
69
+
70
+ cache_latents = args.cache_latents
71
+ use_user_config = args.dataset_config is not None
72
+
73
+ if args.seed is None:
74
+ args.seed = random.randint(0, 2**32)
75
+ set_seed(args.seed)
76
+
77
+ tokenizer1, tokenizer2 = sdxl_train_util.load_tokenizers(args)
78
+
79
+ # データセットを準備する
80
+ blueprint_generator = BlueprintGenerator(ConfigSanitizer(False, False, True, True))
81
+ if use_user_config:
82
+ logger.info(f"Load dataset config from {args.dataset_config}")
83
+ user_config = config_util.load_user_config(args.dataset_config)
84
+ ignored = ["train_data_dir", "conditioning_data_dir"]
85
+ if any(getattr(args, attr) is not None for attr in ignored):
86
+ logger.warning(
87
+ "ignore following options because config file is found: {0} / 設定ファイルが利用されるため以下のオプションは無視されます: {0}".format(
88
+ ", ".join(ignored)
89
+ )
90
+ )
91
+ else:
92
+ user_config = {
93
+ "datasets": [
94
+ {
95
+ "subsets": config_util.generate_controlnet_subsets_config_by_subdirs(
96
+ args.train_data_dir,
97
+ args.conditioning_data_dir,
98
+ args.caption_extension,
99
+ )
100
+ }
101
+ ]
102
+ }
103
+
104
+ blueprint = blueprint_generator.generate(user_config, args, tokenizer=[tokenizer1, tokenizer2])
105
+ train_dataset_group = config_util.generate_dataset_group_by_blueprint(blueprint.dataset_group)
106
+
107
+ current_epoch = Value("i", 0)
108
+ current_step = Value("i", 0)
109
+ ds_for_collator = train_dataset_group if args.max_data_loader_n_workers == 0 else None
110
+ collator = train_util.collator_class(current_epoch, current_step, ds_for_collator)
111
+
112
+ train_dataset_group.verify_bucket_reso_steps(32)
113
+
114
+ if args.debug_dataset:
115
+ train_util.debug_dataset(train_dataset_group)
116
+ return
117
+ if len(train_dataset_group) == 0:
118
+ logger.error(
119
+ "No data found. Please verify arguments (train_data_dir must be the parent of folders with images) / 画像がありません。引数指定を確認してください(train_data_dirには画像があるフォルダではなく、画像があるフォルダの親フォルダを指定する必要があります)"
120
+ )
121
+ return
122
+
123
+ if cache_latents:
124
+ assert (
125
+ train_dataset_group.is_latent_cacheable()
126
+ ), "when caching latents, either color_aug or random_crop cannot be used / latentをキャッシュするときはcolor_augとrandom_cropは使えません"
127
+ else:
128
+ logger.warning(
129
+ "WARNING: random_crop is not supported yet for ControlNet training / ControlNetの学習ではrandom_cropはまだサポートされていません"
130
+ )
131
+
132
+ if args.cache_text_encoder_outputs:
133
+ assert (
134
+ train_dataset_group.is_text_encoder_output_cacheable()
135
+ ), "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は使えません"
136
+
137
+ # acceleratorを準備する
138
+ logger.info("prepare accelerator")
139
+ accelerator = train_util.prepare_accelerator(args)
140
+ is_main_process = accelerator.is_main_process
141
+
142
+ # mixed precisionに対応した型を用意しておき適宜castする
143
+ weight_dtype, save_dtype = train_util.prepare_dtype(args)
144
+ vae_dtype = torch.float32 if args.no_half_vae else weight_dtype
145
+
146
+ # モデルを読み込む
147
+ (
148
+ load_stable_diffusion_format,
149
+ text_encoder1,
150
+ text_encoder2,
151
+ vae,
152
+ unet,
153
+ logit_scale,
154
+ ckpt_info,
155
+ ) = sdxl_train_util.load_target_model(args, accelerator, sdxl_model_util.MODEL_VERSION_SDXL_BASE_V1_0, weight_dtype)
156
+
157
+ # モデルに xformers とか memory efficient attention を組み込む
158
+ train_util.replace_unet_modules(unet, args.mem_eff_attn, args.xformers, args.sdpa)
159
+
160
+ # 学習を準備する
161
+ if cache_latents:
162
+ vae.to(accelerator.device, dtype=vae_dtype)
163
+ vae.requires_grad_(False)
164
+ vae.eval()
165
+ with torch.no_grad():
166
+ train_dataset_group.cache_latents(
167
+ vae,
168
+ args.vae_batch_size,
169
+ args.cache_latents_to_disk,
170
+ accelerator.is_main_process,
171
+ )
172
+ vae.to("cpu")
173
+ clean_memory_on_device(accelerator.device)
174
+
175
+ accelerator.wait_for_everyone()
176
+
177
+ # TextEncoderの出力をキャッシュする
178
+ if args.cache_text_encoder_outputs:
179
+ # Text Encodes are eval and no grad
180
+ with torch.no_grad():
181
+ train_dataset_group.cache_text_encoder_outputs(
182
+ (tokenizer1, tokenizer2),
183
+ (text_encoder1, text_encoder2),
184
+ accelerator.device,
185
+ None,
186
+ args.cache_text_encoder_outputs_to_disk,
187
+ accelerator.is_main_process,
188
+ )
189
+ accelerator.wait_for_everyone()
190
+
191
+ # prepare ControlNet
192
+ network = control_net_lllite.ControlNetLLLite(unet, args.cond_emb_dim, args.network_dim, args.network_dropout)
193
+ network.apply_to()
194
+
195
+ if args.network_weights is not None:
196
+ info = network.load_weights(args.network_weights)
197
+ accelerator.print(f"load ControlNet weights from {args.network_weights}: {info}")
198
+
199
+ if args.gradient_checkpointing:
200
+ unet.enable_gradient_checkpointing()
201
+ network.enable_gradient_checkpointing() # may have no effect
202
+
203
+ # 学習に必要なクラスを準備する
204
+ accelerator.print("prepare optimizer, data loader etc.")
205
+
206
+ trainable_params = list(network.prepare_optimizer_params())
207
+ logger.info(f"trainable params count: {len(trainable_params)}")
208
+ logger.info(f"number of trainable parameters: {sum(p.numel() for p in trainable_params if p.requires_grad)}")
209
+
210
+ _, _, optimizer = train_util.get_optimizer(args, trainable_params)
211
+
212
+ # dataloaderを準備する
213
+ # DataLoaderのプロセス数:0 は persistent_workers が使えないので注意
214
+ n_workers = min(args.max_data_loader_n_workers, os.cpu_count()) # cpu_count or max_data_loader_n_workers
215
+
216
+ train_dataloader = torch.utils.data.DataLoader(
217
+ train_dataset_group,
218
+ batch_size=1,
219
+ shuffle=True,
220
+ collate_fn=collator,
221
+ num_workers=n_workers,
222
+ persistent_workers=args.persistent_data_loader_workers,
223
+ )
224
+
225
+ # 学習ステップ数を計算する
226
+ if args.max_train_epochs is not None:
227
+ args.max_train_steps = args.max_train_epochs * math.ceil(
228
+ len(train_dataloader) / accelerator.num_processes / args.gradient_accumulation_steps
229
+ )
230
+ accelerator.print(
231
+ f"override steps. steps for {args.max_train_epochs} epochs is / 指定エポックまでのステップ数: {args.max_train_steps}"
232
+ )
233
+
234
+ # データセット側にも学習ステップを送信
235
+ train_dataset_group.set_max_train_steps(args.max_train_steps)
236
+
237
+ # lr schedulerを用意する
238
+ lr_scheduler = train_util.get_scheduler_fix(args, optimizer, accelerator.num_processes)
239
+
240
+ # 実験的機能:勾配も含めたfp16/bf16学習を行う モデル全体をfp16/bf16にする
241
+ if args.full_fp16:
242
+ assert (
243
+ args.mixed_precision == "fp16"
244
+ ), "full_fp16 requires mixed precision='fp16' / full_fp16を使う場合はmixed_precision='fp16'を指定してください。"
245
+ accelerator.print("enable full fp16 training.")
246
+ unet.to(weight_dtype)
247
+ network.to(weight_dtype)
248
+ elif args.full_bf16:
249
+ assert (
250
+ args.mixed_precision == "bf16"
251
+ ), "full_bf16 requires mixed precision='bf16' / full_bf16を使う場合はmixed_precision='bf16'を指定してください。"
252
+ accelerator.print("enable full bf16 training.")
253
+ unet.to(weight_dtype)
254
+ network.to(weight_dtype)
255
+
256
+ # acceleratorがなんかよろしくやってくれるらしい
257
+ unet, network, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
258
+ unet, network, optimizer, train_dataloader, lr_scheduler
259
+ )
260
+ network: control_net_lllite.ControlNetLLLite
261
+
262
+ if args.gradient_checkpointing:
263
+ unet.train() # according to TI example in Diffusers, train is required -> これオリジナルのU-Netしたので本当は外せる
264
+ else:
265
+ unet.eval()
266
+
267
+ network.prepare_grad_etc()
268
+
269
+ # TextEncoderの出力をキャッシュするときにはCPUへ移動する
270
+ if args.cache_text_encoder_outputs:
271
+ # move Text Encoders for sampling images. Text Encoder doesn't work on CPU with fp16
272
+ text_encoder1.to("cpu", dtype=torch.float32)
273
+ text_encoder2.to("cpu", dtype=torch.float32)
274
+ clean_memory_on_device(accelerator.device)
275
+ else:
276
+ # make sure Text Encoders are on GPU
277
+ text_encoder1.to(accelerator.device)
278
+ text_encoder2.to(accelerator.device)
279
+
280
+ if not cache_latents:
281
+ vae.requires_grad_(False)
282
+ vae.eval()
283
+ vae.to(accelerator.device, dtype=vae_dtype)
284
+
285
+ # 実験的機能:勾配も含めたfp16学習を行う PyTorchにパッチを当ててfp16でのgrad scaleを有効にする
286
+ if args.full_fp16:
287
+ train_util.patch_accelerator_for_fp16_training(accelerator)
288
+
289
+ # resumeする
290
+ train_util.resume_from_local_or_hf_if_specified(accelerator, args)
291
+
292
+ # epoch数を計算する
293
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
294
+ num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
295
+ if (args.save_n_epoch_ratio is not None) and (args.save_n_epoch_ratio > 0):
296
+ args.save_every_n_epochs = math.floor(num_train_epochs / args.save_n_epoch_ratio) or 1
297
+
298
+ # 学習する
299
+ # TODO: find a way to handle total batch size when there are multiple datasets
300
+ accelerator.print("running training / 学習開始")
301
+ accelerator.print(f" num train images * repeats / 学習画像の数×繰り返し回数: {train_dataset_group.num_train_images}")
302
+ accelerator.print(f" num reg images / 正則化画像の数: {train_dataset_group.num_reg_images}")
303
+ accelerator.print(f" num batches per epoch / 1epochのバッチ数: {len(train_dataloader)}")
304
+ accelerator.print(f" num epochs / epoch数: {num_train_epochs}")
305
+ accelerator.print(
306
+ f" batch size per device / バッチサイズ: {', '.join([str(d.batch_size) for d in train_dataset_group.datasets])}"
307
+ )
308
+ # logger.info(f" total train batch size (with parallel & distributed & accumulation) / 総バッチサイズ(並列学習、勾配合計含む): {total_batch_size}")
309
+ accelerator.print(f" gradient accumulation steps / 勾配を合計するステップ数 = {args.gradient_accumulation_steps}")
310
+ accelerator.print(f" total optimization steps / 学習ステップ数: {args.max_train_steps}")
311
+
312
+ progress_bar = tqdm(range(args.max_train_steps), smoothing=0, disable=not accelerator.is_local_main_process, desc="steps")
313
+ global_step = 0
314
+
315
+ noise_scheduler = DDPMScheduler(
316
+ beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", num_train_timesteps=1000, clip_sample=False
317
+ )
318
+ prepare_scheduler_for_custom_training(noise_scheduler, accelerator.device)
319
+ if args.zero_terminal_snr:
320
+ custom_train_functions.fix_noise_scheduler_betas_for_zero_terminal_snr(noise_scheduler)
321
+
322
+ if accelerator.is_main_process:
323
+ init_kwargs = {}
324
+ if args.log_tracker_config is not None:
325
+ init_kwargs = toml.load(args.log_tracker_config)
326
+ accelerator.init_trackers(
327
+ "lllite_control_net_train" if args.log_tracker_name is None else args.log_tracker_name, init_kwargs=init_kwargs
328
+ )
329
+
330
+ loss_recorder = train_util.LossRecorder()
331
+ del train_dataset_group
332
+
333
+ # function for saving/removing
334
+ def save_model(ckpt_name, unwrapped_nw, steps, epoch_no, force_sync_upload=False):
335
+ os.makedirs(args.output_dir, exist_ok=True)
336
+ ckpt_file = os.path.join(args.output_dir, ckpt_name)
337
+
338
+ accelerator.print(f"\nsaving checkpoint: {ckpt_file}")
339
+ sai_metadata = train_util.get_sai_model_spec(None, args, True, True, False)
340
+ sai_metadata["modelspec.architecture"] = sai_model_spec.ARCH_SD_XL_V1_BASE + "/control-net-lllite"
341
+
342
+ unwrapped_nw.save_weights(ckpt_file, save_dtype, sai_metadata)
343
+ if args.huggingface_repo_id is not None:
344
+ huggingface_util.upload(args, ckpt_file, "/" + ckpt_name, force_sync_upload=force_sync_upload)
345
+
346
+ def remove_model(old_ckpt_name):
347
+ old_ckpt_file = os.path.join(args.output_dir, old_ckpt_name)
348
+ if os.path.exists(old_ckpt_file):
349
+ accelerator.print(f"removing old checkpoint: {old_ckpt_file}")
350
+ os.remove(old_ckpt_file)
351
+
352
+ # training loop
353
+ for epoch in range(num_train_epochs):
354
+ accelerator.print(f"\nepoch {epoch+1}/{num_train_epochs}")
355
+ current_epoch.value = epoch + 1
356
+
357
+ network.on_epoch_start() # train()
358
+
359
+ for step, batch in enumerate(train_dataloader):
360
+ current_step.value = global_step
361
+ with accelerator.accumulate(network):
362
+ with torch.no_grad():
363
+ if "latents" in batch and batch["latents"] is not None:
364
+ latents = batch["latents"].to(accelerator.device).to(dtype=weight_dtype)
365
+ else:
366
+ # latentに変換
367
+ latents = vae.encode(batch["images"].to(dtype=vae_dtype)).latent_dist.sample().to(dtype=weight_dtype)
368
+
369
+ # NaNが含まれていれば警告を表示し0に置き換える
370
+ if torch.any(torch.isnan(latents)):
371
+ accelerator.print("NaN found in latents, replacing with zeros")
372
+ latents = torch.nan_to_num(latents, 0, out=latents)
373
+ latents = latents * sdxl_model_util.VAE_SCALE_FACTOR
374
+
375
+ if "text_encoder_outputs1_list" not in batch or batch["text_encoder_outputs1_list"] is None:
376
+ input_ids1 = batch["input_ids"]
377
+ input_ids2 = batch["input_ids2"]
378
+ with torch.no_grad():
379
+ # Get the text embedding for conditioning
380
+ input_ids1 = input_ids1.to(accelerator.device)
381
+ input_ids2 = input_ids2.to(accelerator.device)
382
+ encoder_hidden_states1, encoder_hidden_states2, pool2 = train_util.get_hidden_states_sdxl(
383
+ args.max_token_length,
384
+ input_ids1,
385
+ input_ids2,
386
+ tokenizer1,
387
+ tokenizer2,
388
+ text_encoder1,
389
+ text_encoder2,
390
+ None if not args.full_fp16 else weight_dtype,
391
+ )
392
+ else:
393
+ encoder_hidden_states1 = batch["text_encoder_outputs1_list"].to(accelerator.device).to(weight_dtype)
394
+ encoder_hidden_states2 = batch["text_encoder_outputs2_list"].to(accelerator.device).to(weight_dtype)
395
+ pool2 = batch["text_encoder_pool2_list"].to(accelerator.device).to(weight_dtype)
396
+
397
+ # get size embeddings
398
+ orig_size = batch["original_sizes_hw"]
399
+ crop_size = batch["crop_top_lefts"]
400
+ target_size = batch["target_sizes_hw"]
401
+ embs = sdxl_train_util.get_size_embeddings(orig_size, crop_size, target_size, accelerator.device).to(weight_dtype)
402
+
403
+ # concat embeddings
404
+ vector_embedding = torch.cat([pool2, embs], dim=1).to(weight_dtype)
405
+ text_embedding = torch.cat([encoder_hidden_states1, encoder_hidden_states2], dim=2).to(weight_dtype)
406
+
407
+ # Sample noise, sample a random timestep for each image, and add noise to the latents,
408
+ # with noise offset and/or multires noise if specified
409
+ noise, noisy_latents, timesteps, huber_c = train_util.get_noise_noisy_latents_and_timesteps(args, noise_scheduler, latents)
410
+
411
+ noisy_latents = noisy_latents.to(weight_dtype) # TODO check why noisy_latents is not weight_dtype
412
+
413
+ controlnet_image = batch["conditioning_images"].to(dtype=weight_dtype)
414
+
415
+ with accelerator.autocast():
416
+ # conditioning imageをControlNetに渡す / pass conditioning image to ControlNet
417
+ # 内部でcond_embに変換される / it will be converted to cond_emb inside
418
+ network.set_cond_image(controlnet_image)
419
+
420
+ # それらの値を使いつつ、U-Netでノイズを予測する / predict noise with U-Net using those values
421
+ noise_pred = unet(noisy_latents, timesteps, text_embedding, vector_embedding)
422
+
423
+ if args.v_parameterization:
424
+ # v-parameterization training
425
+ target = noise_scheduler.get_velocity(latents, noise, timesteps)
426
+ else:
427
+ target = noise
428
+
429
+ loss = train_util.conditional_loss(noise_pred.float(), target.float(), reduction="none", loss_type=args.loss_type, huber_c=huber_c)
430
+ loss = loss.mean([1, 2, 3])
431
+
432
+ loss_weights = batch["loss_weights"] # 各sampleごとのweight
433
+ loss = loss * loss_weights
434
+
435
+ if args.min_snr_gamma:
436
+ loss = apply_snr_weight(loss, timesteps, noise_scheduler, args.min_snr_gamma, args.v_parameterization)
437
+ if args.scale_v_pred_loss_like_noise_pred:
438
+ loss = scale_v_prediction_loss_like_noise_prediction(loss, timesteps, noise_scheduler)
439
+ if args.v_pred_like_loss:
440
+ loss = add_v_prediction_like_loss(loss, timesteps, noise_scheduler, args.v_pred_like_loss)
441
+ if args.debiased_estimation_loss:
442
+ loss = apply_debiased_estimation(loss, timesteps, noise_scheduler)
443
+
444
+ loss = loss.mean() # 平均なのでbatch_sizeで割る必要なし
445
+
446
+ accelerator.backward(loss)
447
+ if accelerator.sync_gradients and args.max_grad_norm != 0.0:
448
+ params_to_clip = network.get_trainable_params()
449
+ accelerator.clip_grad_norm_(params_to_clip, args.max_grad_norm)
450
+
451
+ optimizer.step()
452
+ lr_scheduler.step()
453
+ optimizer.zero_grad(set_to_none=True)
454
+
455
+ # Checks if the accelerator has performed an optimization step behind the scenes
456
+ if accelerator.sync_gradients:
457
+ progress_bar.update(1)
458
+ global_step += 1
459
+
460
+ # sdxl_train_util.sample_images(accelerator, args, None, global_step, accelerator.device, vae, tokenizer, text_encoder, unet)
461
+
462
+ # 指定ステップごとにモデルを保存
463
+ if args.save_every_n_steps is not None and global_step % args.save_every_n_steps == 0:
464
+ accelerator.wait_for_everyone()
465
+ if accelerator.is_main_process:
466
+ ckpt_name = train_util.get_step_ckpt_name(args, "." + args.save_model_as, global_step)
467
+ save_model(ckpt_name, accelerator.unwrap_model(network), global_step, epoch)
468
+
469
+ if args.save_state:
470
+ train_util.save_and_remove_state_stepwise(args, accelerator, global_step)
471
+
472
+ remove_step_no = train_util.get_remove_step_no(args, global_step)
473
+ if remove_step_no is not None:
474
+ remove_ckpt_name = train_util.get_step_ckpt_name(args, "." + args.save_model_as, remove_step_no)
475
+ remove_model(remove_ckpt_name)
476
+
477
+ current_loss = loss.detach().item()
478
+ loss_recorder.add(epoch=epoch, step=step, loss=current_loss)
479
+ avr_loss: float = loss_recorder.moving_average
480
+ logs = {"avr_loss": avr_loss} # , "lr": lr_scheduler.get_last_lr()[0]}
481
+ progress_bar.set_postfix(**logs)
482
+
483
+ if args.logging_dir is not None:
484
+ logs = generate_step_logs(args, current_loss, avr_loss, lr_scheduler)
485
+ accelerator.log(logs, step=global_step)
486
+
487
+ if global_step >= args.max_train_steps:
488
+ break
489
+
490
+ if args.logging_dir is not None:
491
+ logs = {"loss/epoch": loss_recorder.moving_average}
492
+ accelerator.log(logs, step=epoch + 1)
493
+
494
+ accelerator.wait_for_everyone()
495
+
496
+ # 指定エポックごとにモデルを保存
497
+ if args.save_every_n_epochs is not None:
498
+ saving = (epoch + 1) % args.save_every_n_epochs == 0 and (epoch + 1) < num_train_epochs
499
+ if is_main_process and saving:
500
+ ckpt_name = train_util.get_epoch_ckpt_name(args, "." + args.save_model_as, epoch + 1)
501
+ save_model(ckpt_name, accelerator.unwrap_model(network), global_step, epoch + 1)
502
+
503
+ remove_epoch_no = train_util.get_remove_epoch_no(args, epoch + 1)
504
+ if remove_epoch_no is not None:
505
+ remove_ckpt_name = train_util.get_epoch_ckpt_name(args, "." + args.save_model_as, remove_epoch_no)
506
+ remove_model(remove_ckpt_name)
507
+
508
+ if args.save_state:
509
+ train_util.save_and_remove_state_on_epoch_end(args, accelerator, epoch + 1)
510
+
511
+ # self.sample_images(accelerator, args, epoch + 1, global_step, accelerator.device, vae, tokenizer, text_encoder, unet)
512
+
513
+ # end of epoch
514
+
515
+ if is_main_process:
516
+ network = accelerator.unwrap_model(network)
517
+
518
+ accelerator.end_training()
519
+
520
+ if is_main_process and args.save_state:
521
+ train_util.save_state_on_train_end(args, accelerator)
522
+
523
+ if is_main_process:
524
+ ckpt_name = train_util.get_last_ckpt_name(args, "." + args.save_model_as)
525
+ save_model(ckpt_name, network, global_step, num_train_epochs, force_sync_upload=True)
526
+
527
+ logger.info("model saved.")
528
+
529
+
530
+ def setup_parser() -> argparse.ArgumentParser:
531
+ parser = argparse.ArgumentParser()
532
+
533
+ add_logging_arguments(parser)
534
+ train_util.add_sd_models_arguments(parser)
535
+ train_util.add_dataset_arguments(parser, False, True, True)
536
+ train_util.add_training_arguments(parser, False)
537
+ deepspeed_utils.add_deepspeed_arguments(parser)
538
+ train_util.add_optimizer_arguments(parser)
539
+ config_util.add_config_arguments(parser)
540
+ custom_train_functions.add_custom_train_arguments(parser)
541
+ sdxl_train_util.add_sdxl_training_arguments(parser)
542
+
543
+ parser.add_argument(
544
+ "--save_model_as",
545
+ type=str,
546
+ default="safetensors",
547
+ choices=[None, "ckpt", "pt", "safetensors"],
548
+ help="format to save the model (default is .safetensors) / モデル保存時の形式(デフォルトはsafetensors)",
549
+ )
550
+ parser.add_argument(
551
+ "--cond_emb_dim", type=int, default=None, help="conditioning embedding dimension / 条件付け埋め込みの次元数"
552
+ )
553
+ parser.add_argument(
554
+ "--network_weights", type=str, default=None, help="pretrained weights for network / 学習するネットワークの初期重み"
555
+ )
556
+ parser.add_argument("--network_dim", type=int, default=None, help="network dimensions (rank) / モジュールの次元数")
557
+ parser.add_argument(
558
+ "--network_dropout",
559
+ type=float,
560
+ default=None,
561
+ help="Drops neurons out of training every step (0 or None is default behavior (no dropout), 1 would drop all neurons) / 訓練時に毎ステップでニューロンをdropする(0またはNoneはdropoutなし、1は全ニューロンをdropout)",
562
+ )
563
+ parser.add_argument(
564
+ "--conditioning_data_dir",
565
+ type=str,
566
+ default=None,
567
+ help="conditioning data directory / 条件付けデータのディレクトリ",
568
+ )
569
+ parser.add_argument(
570
+ "--no_half_vae",
571
+ action="store_true",
572
+ help="do not use fp16/bf16 VAE in mixed precision (use float VAE) / mixed precisionでも fp16/bf16 VAEを使わずfloat VAEを使う",
573
+ )
574
+ return parser
575
+
576
+
577
+ if __name__ == "__main__":
578
+ # sdxl_original_unet.USE_REENTRANT = False
579
+
580
+ parser = setup_parser()
581
+
582
+ args = parser.parse_args()
583
+ train_util.verify_command_line_training_args(args)
584
+ args = train_util.read_config_from_file(args, parser)
585
+
586
+ train(args)