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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
|
590 |
+
if accelerator.is_main_process:
|
591 |
+
init_kwargs = {}
|
592 |
+
if args.wandb_run_name:
|
593 |
+
init_kwargs["wandb"] = {"name": args.wandb_run_name}
|
594 |
+
if args.log_tracker_config is not None:
|
595 |
+
init_kwargs = toml.load(args.log_tracker_config)
|
596 |
+
accelerator.init_trackers(
|
597 |
+
"finetuning" if args.log_tracker_name is None else args.log_tracker_name,
|
598 |
+
config=train_util.get_sanitized_config_or_none(args),
|
599 |
+
init_kwargs=init_kwargs,
|
600 |
+
)
|
601 |
+
|
602 |
+
# For --sample_at_first
|
603 |
+
sdxl_train_util.sample_images(
|
604 |
+
accelerator, args, 0, global_step, accelerator.device, vae, [tokenizer1, tokenizer2], [text_encoder1, text_encoder2], unet
|
605 |
+
)
|
606 |
+
|
607 |
+
loss_recorder = train_util.LossRecorder()
|
608 |
+
for epoch in range(num_train_epochs):
|
609 |
+
accelerator.print(f"\nepoch {epoch+1}/{num_train_epochs}")
|
610 |
+
current_epoch.value = epoch + 1
|
611 |
+
|
612 |
+
for m in training_models:
|
613 |
+
m.train()
|
614 |
+
|
615 |
+
for step, batch in enumerate(train_dataloader):
|
616 |
+
current_step.value = global_step
|
617 |
+
|
618 |
+
if args.fused_optimizer_groups:
|
619 |
+
optimizer_hooked_count = {i: 0 for i in range(len(optimizers))} # reset counter for each step
|
620 |
+
|
621 |
+
with accelerator.accumulate(*training_models):
|
622 |
+
if "latents" in batch and batch["latents"] is not None:
|
623 |
+
latents = batch["latents"].to(accelerator.device).to(dtype=weight_dtype)
|
624 |
+
else:
|
625 |
+
with torch.no_grad():
|
626 |
+
# latentに変換
|
627 |
+
latents = vae.encode(batch["images"].to(vae_dtype)).latent_dist.sample().to(weight_dtype)
|
628 |
+
|
629 |
+
# NaNが含まれていれば警告を表示し0に置き換える
|
630 |
+
if torch.any(torch.isnan(latents)):
|
631 |
+
accelerator.print("NaN found in latents, replacing with zeros")
|
632 |
+
latents = torch.nan_to_num(latents, 0, out=latents)
|
633 |
+
latents = latents * sdxl_model_util.VAE_SCALE_FACTOR
|
634 |
+
|
635 |
+
if "text_encoder_outputs1_list" not in batch or batch["text_encoder_outputs1_list"] is None:
|
636 |
+
input_ids1 = batch["input_ids"]
|
637 |
+
input_ids2 = batch["input_ids2"]
|
638 |
+
with torch.set_grad_enabled(args.train_text_encoder):
|
639 |
+
# Get the text embedding for conditioning
|
640 |
+
# TODO support weighted captions
|
641 |
+
# if args.weighted_captions:
|
642 |
+
# encoder_hidden_states = get_weighted_text_embeddings(
|
643 |
+
# tokenizer,
|
644 |
+
# text_encoder,
|
645 |
+
# batch["captions"],
|
646 |
+
# accelerator.device,
|
647 |
+
# args.max_token_length // 75 if args.max_token_length else 1,
|
648 |
+
# clip_skip=args.clip_skip,
|
649 |
+
# )
|
650 |
+
# else:
|
651 |
+
input_ids1 = input_ids1.to(accelerator.device)
|
652 |
+
input_ids2 = input_ids2.to(accelerator.device)
|
653 |
+
# unwrap_model is fine for models not wrapped by accelerator
|
654 |
+
encoder_hidden_states1, encoder_hidden_states2, pool2 = train_util.get_hidden_states_sdxl(
|
655 |
+
args.max_token_length,
|
656 |
+
input_ids1,
|
657 |
+
input_ids2,
|
658 |
+
tokenizer1,
|
659 |
+
tokenizer2,
|
660 |
+
text_encoder1,
|
661 |
+
text_encoder2,
|
662 |
+
None if not args.full_fp16 else weight_dtype,
|
663 |
+
accelerator=accelerator,
|
664 |
+
)
|
665 |
+
else:
|
666 |
+
encoder_hidden_states1 = batch["text_encoder_outputs1_list"].to(accelerator.device).to(weight_dtype)
|
667 |
+
encoder_hidden_states2 = batch["text_encoder_outputs2_list"].to(accelerator.device).to(weight_dtype)
|
668 |
+
pool2 = batch["text_encoder_pool2_list"].to(accelerator.device).to(weight_dtype)
|
669 |
+
|
670 |
+
# # verify that the text encoder outputs are correct
|
671 |
+
# ehs1, ehs2, p2 = train_util.get_hidden_states_sdxl(
|
672 |
+
# args.max_token_length,
|
673 |
+
# batch["input_ids"].to(text_encoder1.device),
|
674 |
+
# batch["input_ids2"].to(text_encoder1.device),
|
675 |
+
# tokenizer1,
|
676 |
+
# tokenizer2,
|
677 |
+
# text_encoder1,
|
678 |
+
# text_encoder2,
|
679 |
+
# None if not args.full_fp16 else weight_dtype,
|
680 |
+
# )
|
681 |
+
# b_size = encoder_hidden_states1.shape[0]
|
682 |
+
# assert ((encoder_hidden_states1.to("cpu") - ehs1.to(dtype=weight_dtype)).abs().max() > 1e-2).sum() <= b_size * 2
|
683 |
+
# assert ((encoder_hidden_states2.to("cpu") - ehs2.to(dtype=weight_dtype)).abs().max() > 1e-2).sum() <= b_size * 2
|
684 |
+
# assert ((pool2.to("cpu") - p2.to(dtype=weight_dtype)).abs().max() > 1e-2).sum() <= b_size * 2
|
685 |
+
# logger.info("text encoder outputs verified")
|
686 |
+
|
687 |
+
# get size embeddings
|
688 |
+
orig_size = batch["original_sizes_hw"]
|
689 |
+
crop_size = batch["crop_top_lefts"]
|
690 |
+
target_size = batch["target_sizes_hw"]
|
691 |
+
embs = sdxl_train_util.get_size_embeddings(orig_size, crop_size, target_size, accelerator.device).to(weight_dtype)
|
692 |
+
|
693 |
+
# concat embeddings
|
694 |
+
vector_embedding = torch.cat([pool2, embs], dim=1).to(weight_dtype)
|
695 |
+
text_embedding = torch.cat([encoder_hidden_states1, encoder_hidden_states2], dim=2).to(weight_dtype)
|
696 |
+
|
697 |
+
# Sample noise, sample a random timestep for each image, and add noise to the latents,
|
698 |
+
# with noise offset and/or multires noise if specified
|
699 |
+
noise, noisy_latents, timesteps, huber_c = train_util.get_noise_noisy_latents_and_timesteps(
|
700 |
+
args, noise_scheduler, latents
|
701 |
+
)
|
702 |
+
|
703 |
+
noisy_latents = noisy_latents.to(weight_dtype) # TODO check why noisy_latents is not weight_dtype
|
704 |
+
|
705 |
+
# Predict the noise residual
|
706 |
+
with accelerator.autocast():
|
707 |
+
noise_pred = unet(noisy_latents, timesteps, text_embedding, vector_embedding)
|
708 |
+
|
709 |
+
if args.v_parameterization:
|
710 |
+
# v-parameterization training
|
711 |
+
target = noise_scheduler.get_velocity(latents, noise, timesteps)
|
712 |
+
else:
|
713 |
+
target = noise
|
714 |
+
|
715 |
+
if (
|
716 |
+
args.min_snr_gamma
|
717 |
+
or args.scale_v_pred_loss_like_noise_pred
|
718 |
+
or args.v_pred_like_loss
|
719 |
+
or args.debiased_estimation_loss
|
720 |
+
or args.masked_loss
|
721 |
+
):
|
722 |
+
# do not mean over batch dimension for snr weight or scale v-pred loss
|
723 |
+
loss = train_util.conditional_loss(
|
724 |
+
noise_pred.float(), target.float(), reduction="none", loss_type=args.loss_type, huber_c=huber_c
|
725 |
+
)
|
726 |
+
if args.masked_loss or ("alpha_masks" in batch and batch["alpha_masks"] is not None):
|
727 |
+
loss = apply_masked_loss(loss, batch)
|
728 |
+
loss = loss.mean([1, 2, 3])
|
729 |
+
|
730 |
+
if args.min_snr_gamma:
|
731 |
+
loss = apply_snr_weight(loss, timesteps, noise_scheduler, args.min_snr_gamma, args.v_parameterization)
|
732 |
+
if args.scale_v_pred_loss_like_noise_pred:
|
733 |
+
loss = scale_v_prediction_loss_like_noise_prediction(loss, timesteps, noise_scheduler)
|
734 |
+
if args.v_pred_like_loss:
|
735 |
+
loss = add_v_prediction_like_loss(loss, timesteps, noise_scheduler, args.v_pred_like_loss)
|
736 |
+
if args.debiased_estimation_loss:
|
737 |
+
loss = apply_debiased_estimation(loss, timesteps, noise_scheduler, args.v_parameterization)
|
738 |
+
|
739 |
+
loss = loss.mean() # mean over batch dimension
|
740 |
+
else:
|
741 |
+
loss = train_util.conditional_loss(
|
742 |
+
noise_pred.float(), target.float(), reduction="mean", loss_type=args.loss_type, huber_c=huber_c
|
743 |
+
)
|
744 |
+
|
745 |
+
accelerator.backward(loss)
|
746 |
+
|
747 |
+
if not (args.fused_backward_pass or args.fused_optimizer_groups):
|
748 |
+
if accelerator.sync_gradients and args.max_grad_norm != 0.0:
|
749 |
+
params_to_clip = []
|
750 |
+
for m in training_models:
|
751 |
+
params_to_clip.extend(m.parameters())
|
752 |
+
accelerator.clip_grad_norm_(params_to_clip, args.max_grad_norm)
|
753 |
+
|
754 |
+
optimizer.step()
|
755 |
+
lr_scheduler.step()
|
756 |
+
optimizer.zero_grad(set_to_none=True)
|
757 |
+
else:
|
758 |
+
# optimizer.step() and optimizer.zero_grad() are called in the optimizer hook
|
759 |
+
lr_scheduler.step()
|
760 |
+
if args.fused_optimizer_groups:
|
761 |
+
for i in range(1, len(optimizers)):
|
762 |
+
lr_schedulers[i].step()
|
763 |
+
|
764 |
+
# Checks if the accelerator has performed an optimization step behind the scenes
|
765 |
+
if accelerator.sync_gradients:
|
766 |
+
progress_bar.update(1)
|
767 |
+
global_step += 1
|
768 |
+
|
769 |
+
sdxl_train_util.sample_images(
|
770 |
+
accelerator,
|
771 |
+
args,
|
772 |
+
None,
|
773 |
+
global_step,
|
774 |
+
accelerator.device,
|
775 |
+
vae,
|
776 |
+
[tokenizer1, tokenizer2],
|
777 |
+
[text_encoder1, text_encoder2],
|
778 |
+
unet,
|
779 |
+
)
|
780 |
+
|
781 |
+
# 指定ステップごとにモデルを保存
|
782 |
+
if args.save_every_n_steps is not None and global_step % args.save_every_n_steps == 0:
|
783 |
+
accelerator.wait_for_everyone()
|
784 |
+
if accelerator.is_main_process:
|
785 |
+
src_path = src_stable_diffusion_ckpt if save_stable_diffusion_format else src_diffusers_model_path
|
786 |
+
sdxl_train_util.save_sd_model_on_epoch_end_or_stepwise(
|
787 |
+
args,
|
788 |
+
False,
|
789 |
+
accelerator,
|
790 |
+
src_path,
|
791 |
+
save_stable_diffusion_format,
|
792 |
+
use_safetensors,
|
793 |
+
save_dtype,
|
794 |
+
epoch,
|
795 |
+
num_train_epochs,
|
796 |
+
global_step,
|
797 |
+
accelerator.unwrap_model(text_encoder1),
|
798 |
+
accelerator.unwrap_model(text_encoder2),
|
799 |
+
accelerator.unwrap_model(unet),
|
800 |
+
vae,
|
801 |
+
logit_scale,
|
802 |
+
ckpt_info,
|
803 |
+
)
|
804 |
+
|
805 |
+
current_loss = loss.detach().item() # 平均なのでbatch sizeは関係ないはず
|
806 |
+
if args.logging_dir is not None:
|
807 |
+
logs = {"loss": current_loss}
|
808 |
+
if block_lrs is None:
|
809 |
+
train_util.append_lr_to_logs(logs, lr_scheduler, args.optimizer_type, including_unet=train_unet)
|
810 |
+
else:
|
811 |
+
append_block_lr_to_logs(block_lrs, logs, lr_scheduler, args.optimizer_type) # U-Net is included in block_lrs
|
812 |
+
|
813 |
+
accelerator.log(logs, step=global_step)
|
814 |
+
|
815 |
+
loss_recorder.add(epoch=epoch, step=step, loss=current_loss)
|
816 |
+
avr_loss: float = loss_recorder.moving_average
|
817 |
+
logs = {"avr_loss": avr_loss} # , "lr": lr_scheduler.get_last_lr()[0]}
|
818 |
+
progress_bar.set_postfix(**logs)
|
819 |
+
|
820 |
+
if global_step >= args.max_train_steps:
|
821 |
+
break
|
822 |
+
|
823 |
+
if args.logging_dir is not None:
|
824 |
+
logs = {"loss/epoch": loss_recorder.moving_average}
|
825 |
+
accelerator.log(logs, step=epoch + 1)
|
826 |
+
|
827 |
+
accelerator.wait_for_everyone()
|
828 |
+
|
829 |
+
if args.save_every_n_epochs is not None:
|
830 |
+
if accelerator.is_main_process:
|
831 |
+
src_path = src_stable_diffusion_ckpt if save_stable_diffusion_format else src_diffusers_model_path
|
832 |
+
sdxl_train_util.save_sd_model_on_epoch_end_or_stepwise(
|
833 |
+
args,
|
834 |
+
True,
|
835 |
+
accelerator,
|
836 |
+
src_path,
|
837 |
+
save_stable_diffusion_format,
|
838 |
+
use_safetensors,
|
839 |
+
save_dtype,
|
840 |
+
epoch,
|
841 |
+
num_train_epochs,
|
842 |
+
global_step,
|
843 |
+
accelerator.unwrap_model(text_encoder1),
|
844 |
+
accelerator.unwrap_model(text_encoder2),
|
845 |
+
accelerator.unwrap_model(unet),
|
846 |
+
vae,
|
847 |
+
logit_scale,
|
848 |
+
ckpt_info,
|
849 |
+
)
|
850 |
+
|
851 |
+
sdxl_train_util.sample_images(
|
852 |
+
accelerator,
|
853 |
+
args,
|
854 |
+
epoch + 1,
|
855 |
+
global_step,
|
856 |
+
accelerator.device,
|
857 |
+
vae,
|
858 |
+
[tokenizer1, tokenizer2],
|
859 |
+
[text_encoder1, text_encoder2],
|
860 |
+
unet,
|
861 |
+
)
|
862 |
+
|
863 |
+
is_main_process = accelerator.is_main_process
|
864 |
+
# if is_main_process:
|
865 |
+
unet = accelerator.unwrap_model(unet)
|
866 |
+
text_encoder1 = accelerator.unwrap_model(text_encoder1)
|
867 |
+
text_encoder2 = accelerator.unwrap_model(text_encoder2)
|
868 |
+
|
869 |
+
accelerator.end_training()
|
870 |
+
|
871 |
+
if args.save_state or args.save_state_on_train_end:
|
872 |
+
train_util.save_state_on_train_end(args, accelerator)
|
873 |
+
|
874 |
+
del accelerator # この後メモリを使うのでこれは消す
|
875 |
+
|
876 |
+
if is_main_process:
|
877 |
+
src_path = src_stable_diffusion_ckpt if save_stable_diffusion_format else src_diffusers_model_path
|
878 |
+
sdxl_train_util.save_sd_model_on_train_end(
|
879 |
+
args,
|
880 |
+
src_path,
|
881 |
+
save_stable_diffusion_format,
|
882 |
+
use_safetensors,
|
883 |
+
save_dtype,
|
884 |
+
epoch,
|
885 |
+
global_step,
|
886 |
+
text_encoder1,
|
887 |
+
text_encoder2,
|
888 |
+
unet,
|
889 |
+
vae,
|
890 |
+
logit_scale,
|
891 |
+
ckpt_info,
|
892 |
+
)
|
893 |
+
logger.info("model saved.")
|
894 |
+
|
895 |
+
|
896 |
+
def setup_parser() -> argparse.ArgumentParser:
|
897 |
+
parser = argparse.ArgumentParser()
|
898 |
+
|
899 |
+
add_logging_arguments(parser)
|
900 |
+
train_util.add_sd_models_arguments(parser)
|
901 |
+
train_util.add_dataset_arguments(parser, True, True, True)
|
902 |
+
train_util.add_training_arguments(parser, False)
|
903 |
+
train_util.add_masked_loss_arguments(parser)
|
904 |
+
deepspeed_utils.add_deepspeed_arguments(parser)
|
905 |
+
train_util.add_sd_saving_arguments(parser)
|
906 |
+
train_util.add_optimizer_arguments(parser)
|
907 |
+
config_util.add_config_arguments(parser)
|
908 |
+
custom_train_functions.add_custom_train_arguments(parser)
|
909 |
+
sdxl_train_util.add_sdxl_training_arguments(parser)
|
910 |
+
|
911 |
+
parser.add_argument(
|
912 |
+
"--learning_rate_te1",
|
913 |
+
type=float,
|
914 |
+
default=None,
|
915 |
+
help="learning rate for text encoder 1 (ViT-L) / text encoder 1 (ViT-L)の学習率",
|
916 |
+
)
|
917 |
+
parser.add_argument(
|
918 |
+
"--learning_rate_te2",
|
919 |
+
type=float,
|
920 |
+
default=None,
|
921 |
+
help="learning rate for text encoder 2 (BiG-G) / text encoder 2 (BiG-G)の学習率",
|
922 |
+
)
|
923 |
+
|
924 |
+
parser.add_argument(
|
925 |
+
"--diffusers_xformers", action="store_true", help="use xformers by diffusers / Diffusersでxformersを使用する"
|
926 |
+
)
|
927 |
+
parser.add_argument("--train_text_encoder", action="store_true", help="train text encoder / text encoderも学習する")
|
928 |
+
parser.add_argument(
|
929 |
+
"--no_half_vae",
|
930 |
+
action="store_true",
|
931 |
+
help="do not use fp16/bf16 VAE in mixed precision (use float VAE) / mixed precisionでも fp16/bf16 VAEを使わずfloat VAEを使う",
|
932 |
+
)
|
933 |
+
parser.add_argument(
|
934 |
+
"--block_lr",
|
935 |
+
type=str,
|
936 |
+
default=None,
|
937 |
+
help=f"learning rates for each block of U-Net, comma-separated, {UNET_NUM_BLOCKS_FOR_BLOCK_LR} values / "
|
938 |
+
+ f"U-Netの各ブロックの学習率、カンマ区切り、{UNET_NUM_BLOCKS_FOR_BLOCK_LR}個の値",
|
939 |
+
)
|
940 |
+
parser.add_argument(
|
941 |
+
"--fused_optimizer_groups",
|
942 |
+
type=int,
|
943 |
+
default=None,
|
944 |
+
help="number of optimizers for fused backward pass and optimizer step / fused backward passとoptimizer stepのためのoptimizer数",
|
945 |
+
)
|
946 |
+
return parser
|
947 |
+
|
948 |
+
|
949 |
+
if __name__ == "__main__":
|
950 |
+
parser = setup_parser()
|
951 |
+
|
952 |
+
args = parser.parse_args()
|
953 |
+
train_util.verify_command_line_training_args(args)
|
954 |
+
args = train_util.read_config_from_file(args, parser)
|
955 |
+
|
956 |
+
train(args)
|