ACCC1380 commited on
Commit
069ce1f
1 Parent(s): 1d97f8f

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

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