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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# DreamBooth training
|
2 |
+
# XXX dropped option: fine_tune
|
3 |
+
|
4 |
+
import argparse
|
5 |
+
import itertools
|
6 |
+
import math
|
7 |
+
import os
|
8 |
+
from multiprocessing import Value
|
9 |
+
import toml
|
10 |
+
|
11 |
+
from tqdm import tqdm
|
12 |
+
|
13 |
+
import torch
|
14 |
+
from library import deepspeed_utils
|
15 |
+
from library.device_utils import init_ipex, clean_memory_on_device
|
16 |
+
|
17 |
+
|
18 |
+
init_ipex()
|
19 |
+
|
20 |
+
from accelerate.utils import set_seed
|
21 |
+
from diffusers import DDPMScheduler
|
22 |
+
|
23 |
+
import library.train_util as train_util
|
24 |
+
import library.config_util as config_util
|
25 |
+
from library.config_util import (
|
26 |
+
ConfigSanitizer,
|
27 |
+
BlueprintGenerator,
|
28 |
+
)
|
29 |
+
import library.custom_train_functions as custom_train_functions
|
30 |
+
from library.custom_train_functions import (
|
31 |
+
apply_snr_weight,
|
32 |
+
get_weighted_text_embeddings,
|
33 |
+
prepare_scheduler_for_custom_training,
|
34 |
+
pyramid_noise_like,
|
35 |
+
apply_noise_offset,
|
36 |
+
scale_v_prediction_loss_like_noise_prediction,
|
37 |
+
apply_debiased_estimation,
|
38 |
+
apply_masked_loss,
|
39 |
+
)
|
40 |
+
from library.utils import setup_logging, add_logging_arguments
|
41 |
+
|
42 |
+
setup_logging()
|
43 |
+
import logging
|
44 |
+
|
45 |
+
logger = logging.getLogger(__name__)
|
46 |
+
|
47 |
+
# perlin_noise,
|
48 |
+
|
49 |
+
|
50 |
+
def train(args):
|
51 |
+
train_util.verify_training_args(args)
|
52 |
+
train_util.prepare_dataset_args(args, False)
|
53 |
+
deepspeed_utils.prepare_deepspeed_args(args)
|
54 |
+
setup_logging(args, reset=True)
|
55 |
+
|
56 |
+
cache_latents = args.cache_latents
|
57 |
+
|
58 |
+
if args.seed is not None:
|
59 |
+
set_seed(args.seed) # 乱数系列を初期化する
|
60 |
+
|
61 |
+
tokenizer = train_util.load_tokenizer(args)
|
62 |
+
|
63 |
+
# データセットを準備する
|
64 |
+
if args.dataset_class is None:
|
65 |
+
blueprint_generator = BlueprintGenerator(ConfigSanitizer(True, False, args.masked_loss, True))
|
66 |
+
if args.dataset_config is not None:
|
67 |
+
logger.info(f"Load dataset config from {args.dataset_config}")
|
68 |
+
user_config = config_util.load_user_config(args.dataset_config)
|
69 |
+
ignored = ["train_data_dir", "reg_data_dir"]
|
70 |
+
if any(getattr(args, attr) is not None for attr in ignored):
|
71 |
+
logger.warning(
|
72 |
+
"ignore following options because config file is found: {0} / 設定ファイルが利用されるため以下のオプションは無視されます: {0}".format(
|
73 |
+
", ".join(ignored)
|
74 |
+
)
|
75 |
+
)
|
76 |
+
else:
|
77 |
+
user_config = {
|
78 |
+
"datasets": [
|
79 |
+
{"subsets": config_util.generate_dreambooth_subsets_config_by_subdirs(args.train_data_dir, args.reg_data_dir)}
|
80 |
+
]
|
81 |
+
}
|
82 |
+
|
83 |
+
blueprint = blueprint_generator.generate(user_config, args, tokenizer=tokenizer)
|
84 |
+
train_dataset_group = config_util.generate_dataset_group_by_blueprint(blueprint.dataset_group)
|
85 |
+
else:
|
86 |
+
train_dataset_group = train_util.load_arbitrary_dataset(args, tokenizer)
|
87 |
+
|
88 |
+
current_epoch = Value("i", 0)
|
89 |
+
current_step = Value("i", 0)
|
90 |
+
ds_for_collator = train_dataset_group if args.max_data_loader_n_workers == 0 else None
|
91 |
+
collator = train_util.collator_class(current_epoch, current_step, ds_for_collator)
|
92 |
+
|
93 |
+
if args.no_token_padding:
|
94 |
+
train_dataset_group.disable_token_padding()
|
95 |
+
|
96 |
+
if args.debug_dataset:
|
97 |
+
train_util.debug_dataset(train_dataset_group)
|
98 |
+
return
|
99 |
+
|
100 |
+
if cache_latents:
|
101 |
+
assert (
|
102 |
+
train_dataset_group.is_latent_cacheable()
|
103 |
+
), "when caching latents, either color_aug or random_crop cannot be used / latentをキャッシュするときはcolor_augとrandom_cropは使えません"
|
104 |
+
|
105 |
+
# acceleratorを準備する
|
106 |
+
logger.info("prepare accelerator")
|
107 |
+
|
108 |
+
if args.gradient_accumulation_steps > 1:
|
109 |
+
logger.warning(
|
110 |
+
f"gradient_accumulation_steps is {args.gradient_accumulation_steps}. accelerate does not support gradient_accumulation_steps when training multiple models (U-Net and Text Encoder), so something might be wrong"
|
111 |
+
)
|
112 |
+
logger.warning(
|
113 |
+
f"gradient_accumulation_stepsが{args.gradient_accumulation_steps}に設定されています。accelerateは複数モデル(U-NetおよびText Encoder)の学習時にgradient_accumulation_stepsをサポートしていないため結果は未知数です"
|
114 |
+
)
|
115 |
+
|
116 |
+
accelerator = train_util.prepare_accelerator(args)
|
117 |
+
|
118 |
+
# mixed precisionに対応した型を用意しておき適宜castする
|
119 |
+
weight_dtype, save_dtype = train_util.prepare_dtype(args)
|
120 |
+
vae_dtype = torch.float32 if args.no_half_vae else weight_dtype
|
121 |
+
|
122 |
+
# モデルを読み込む
|
123 |
+
text_encoder, vae, unet, load_stable_diffusion_format = train_util.load_target_model(args, weight_dtype, accelerator)
|
124 |
+
|
125 |
+
# verify load/save model formats
|
126 |
+
if load_stable_diffusion_format:
|
127 |
+
src_stable_diffusion_ckpt = args.pretrained_model_name_or_path
|
128 |
+
src_diffusers_model_path = None
|
129 |
+
else:
|
130 |
+
src_stable_diffusion_ckpt = None
|
131 |
+
src_diffusers_model_path = args.pretrained_model_name_or_path
|
132 |
+
|
133 |
+
if args.save_model_as is None:
|
134 |
+
save_stable_diffusion_format = load_stable_diffusion_format
|
135 |
+
use_safetensors = args.use_safetensors
|
136 |
+
else:
|
137 |
+
save_stable_diffusion_format = args.save_model_as.lower() == "ckpt" or args.save_model_as.lower() == "safetensors"
|
138 |
+
use_safetensors = args.use_safetensors or ("safetensors" in args.save_model_as.lower())
|
139 |
+
|
140 |
+
# モデルに xformers とか memory efficient attention を組み込む
|
141 |
+
train_util.replace_unet_modules(unet, args.mem_eff_attn, args.xformers, args.sdpa)
|
142 |
+
|
143 |
+
# 学習を準備する
|
144 |
+
if cache_latents:
|
145 |
+
vae.to(accelerator.device, dtype=vae_dtype)
|
146 |
+
vae.requires_grad_(False)
|
147 |
+
vae.eval()
|
148 |
+
with torch.no_grad():
|
149 |
+
train_dataset_group.cache_latents(vae, args.vae_batch_size, args.cache_latents_to_disk, accelerator.is_main_process)
|
150 |
+
vae.to("cpu")
|
151 |
+
clean_memory_on_device(accelerator.device)
|
152 |
+
|
153 |
+
accelerator.wait_for_everyone()
|
154 |
+
|
155 |
+
# 学習を準備する:モデルを適切な状態にする
|
156 |
+
train_text_encoder = args.stop_text_encoder_training is None or args.stop_text_encoder_training >= 0
|
157 |
+
unet.requires_grad_(True) # 念のため追加
|
158 |
+
text_encoder.requires_grad_(train_text_encoder)
|
159 |
+
if not train_text_encoder:
|
160 |
+
accelerator.print("Text Encoder is not trained.")
|
161 |
+
|
162 |
+
if args.gradient_checkpointing:
|
163 |
+
unet.enable_gradient_checkpointing()
|
164 |
+
text_encoder.gradient_checkpointing_enable()
|
165 |
+
|
166 |
+
if not cache_latents:
|
167 |
+
vae.requires_grad_(False)
|
168 |
+
vae.eval()
|
169 |
+
vae.to(accelerator.device, dtype=weight_dtype)
|
170 |
+
|
171 |
+
# 学習に必要なクラスを準備する
|
172 |
+
accelerator.print("prepare optimizer, data loader etc.")
|
173 |
+
if train_text_encoder:
|
174 |
+
if args.learning_rate_te is None:
|
175 |
+
# wightout list, adamw8bit is crashed
|
176 |
+
trainable_params = list(itertools.chain(unet.parameters(), text_encoder.parameters()))
|
177 |
+
else:
|
178 |
+
trainable_params = [
|
179 |
+
{"params": list(unet.parameters()), "lr": args.learning_rate},
|
180 |
+
{"params": list(text_encoder.parameters()), "lr": args.learning_rate_te},
|
181 |
+
]
|
182 |
+
else:
|
183 |
+
trainable_params = unet.parameters()
|
184 |
+
|
185 |
+
_, _, optimizer = train_util.get_optimizer(args, trainable_params)
|
186 |
+
|
187 |
+
# dataloaderを準備する
|
188 |
+
# DataLoaderのプロセス数:0 は persistent_workers が使えないので注意
|
189 |
+
n_workers = min(args.max_data_loader_n_workers, os.cpu_count()) # cpu_count or max_data_loader_n_workers
|
190 |
+
train_dataloader = torch.utils.data.DataLoader(
|
191 |
+
train_dataset_group,
|
192 |
+
batch_size=1,
|
193 |
+
shuffle=True,
|
194 |
+
collate_fn=collator,
|
195 |
+
num_workers=n_workers,
|
196 |
+
persistent_workers=args.persistent_data_loader_workers,
|
197 |
+
)
|
198 |
+
|
199 |
+
# 学習ステップ数を計算する
|
200 |
+
if args.max_train_epochs is not None:
|
201 |
+
args.max_train_steps = args.max_train_epochs * math.ceil(
|
202 |
+
len(train_dataloader) / accelerator.num_processes / args.gradient_accumulation_steps
|
203 |
+
)
|
204 |
+
accelerator.print(
|
205 |
+
f"override steps. steps for {args.max_train_epochs} epochs is / 指定エポックまでのステップ数: {args.max_train_steps}"
|
206 |
+
)
|
207 |
+
|
208 |
+
# データセット側にも学習ステップを送信
|
209 |
+
train_dataset_group.set_max_train_steps(args.max_train_steps)
|
210 |
+
|
211 |
+
if args.stop_text_encoder_training is None:
|
212 |
+
args.stop_text_encoder_training = args.max_train_steps + 1 # do not stop until end
|
213 |
+
|
214 |
+
# lr schedulerを用意する TODO gradient_accumulation_stepsの扱いが何かおかしいかもしれない。後で確認する
|
215 |
+
lr_scheduler = train_util.get_scheduler_fix(args, optimizer, accelerator.num_processes)
|
216 |
+
|
217 |
+
# 実験的機能:勾配も含めたfp16学習を行う モデル全体をfp16にする
|
218 |
+
if args.full_fp16:
|
219 |
+
assert (
|
220 |
+
args.mixed_precision == "fp16"
|
221 |
+
), "full_fp16 requires mixed precision='fp16' / full_fp16を使う場合はmixed_precision='fp16'を指定してください。"
|
222 |
+
accelerator.print("enable full fp16 training.")
|
223 |
+
unet.to(weight_dtype)
|
224 |
+
text_encoder.to(weight_dtype)
|
225 |
+
|
226 |
+
# acceleratorがなんかよろしくやってくれるらしい
|
227 |
+
if args.deepspeed:
|
228 |
+
if args.train_text_encoder:
|
229 |
+
ds_model = deepspeed_utils.prepare_deepspeed_model(args, unet=unet, text_encoder=text_encoder)
|
230 |
+
else:
|
231 |
+
ds_model = deepspeed_utils.prepare_deepspeed_model(args, unet=unet)
|
232 |
+
ds_model, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
|
233 |
+
ds_model, optimizer, train_dataloader, lr_scheduler
|
234 |
+
)
|
235 |
+
training_models = [ds_model]
|
236 |
+
|
237 |
+
else:
|
238 |
+
if train_text_encoder:
|
239 |
+
unet, text_encoder, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
|
240 |
+
unet, text_encoder, optimizer, train_dataloader, lr_scheduler
|
241 |
+
)
|
242 |
+
training_models = [unet, text_encoder]
|
243 |
+
else:
|
244 |
+
unet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(unet, optimizer, train_dataloader, lr_scheduler)
|
245 |
+
training_models = [unet]
|
246 |
+
|
247 |
+
if not train_text_encoder:
|
248 |
+
text_encoder.to(accelerator.device, dtype=weight_dtype) # to avoid 'cpu' vs 'cuda' error
|
249 |
+
|
250 |
+
# 実験的機能:勾配も含めたfp16学習を行う PyTorchにパッチを当ててfp16でのgrad scaleを有効にする
|
251 |
+
if args.full_fp16:
|
252 |
+
train_util.patch_accelerator_for_fp16_training(accelerator)
|
253 |
+
|
254 |
+
# resumeする
|
255 |
+
train_util.resume_from_local_or_hf_if_specified(accelerator, args)
|
256 |
+
|
257 |
+
# epoch数を計算する
|
258 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
259 |
+
num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
|
260 |
+
if (args.save_n_epoch_ratio is not None) and (args.save_n_epoch_ratio > 0):
|
261 |
+
args.save_every_n_epochs = math.floor(num_train_epochs / args.save_n_epoch_ratio) or 1
|
262 |
+
|
263 |
+
# 学習する
|
264 |
+
total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
|
265 |
+
accelerator.print("running training / 学習開始")
|
266 |
+
accelerator.print(f" num train images * repeats / 学習画像の数×繰り返し回数: {train_dataset_group.num_train_images}")
|
267 |
+
accelerator.print(f" num reg images / 正則化画像の数: {train_dataset_group.num_reg_images}")
|
268 |
+
accelerator.print(f" num batches per epoch / 1epochのバッチ数: {len(train_dataloader)}")
|
269 |
+
accelerator.print(f" num epochs / epoch数: {num_train_epochs}")
|
270 |
+
accelerator.print(f" batch size per device / バッチサイズ: {args.train_batch_size}")
|
271 |
+
accelerator.print(
|
272 |
+
f" total train batch size (with parallel & distributed & accumulation) / 総バッチサイズ(並列学習、勾配合計含む): {total_batch_size}"
|
273 |
+
)
|
274 |
+
accelerator.print(f" gradient ccumulation steps / 勾配を合計するステップ数 = {args.gradient_accumulation_steps}")
|
275 |
+
accelerator.print(f" total optimization steps / 学習ステップ数: {args.max_train_steps}")
|
276 |
+
|
277 |
+
progress_bar = tqdm(range(args.max_train_steps), smoothing=0, disable=not accelerator.is_local_main_process, desc="steps")
|
278 |
+
global_step = 0
|
279 |
+
|
280 |
+
noise_scheduler = DDPMScheduler(
|
281 |
+
beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", num_train_timesteps=1000, clip_sample=False
|
282 |
+
)
|
283 |
+
prepare_scheduler_for_custom_training(noise_scheduler, accelerator.device)
|
284 |
+
if args.zero_terminal_snr:
|
285 |
+
custom_train_functions.fix_noise_scheduler_betas_for_zero_terminal_snr(noise_scheduler)
|
286 |
+
|
287 |
+
if accelerator.is_main_process:
|
288 |
+
init_kwargs = {}
|
289 |
+
if args.wandb_run_name:
|
290 |
+
init_kwargs["wandb"] = {"name": args.wandb_run_name}
|
291 |
+
if args.log_tracker_config is not None:
|
292 |
+
init_kwargs = toml.load(args.log_tracker_config)
|
293 |
+
accelerator.init_trackers("dreambooth" if args.log_tracker_name is None else args.log_tracker_name, init_kwargs=init_kwargs)
|
294 |
+
|
295 |
+
# For --sample_at_first
|
296 |
+
train_util.sample_images(accelerator, args, 0, global_step, accelerator.device, vae, tokenizer, text_encoder, unet)
|
297 |
+
|
298 |
+
loss_recorder = train_util.LossRecorder()
|
299 |
+
for epoch in range(num_train_epochs):
|
300 |
+
accelerator.print(f"\nepoch {epoch+1}/{num_train_epochs}")
|
301 |
+
current_epoch.value = epoch + 1
|
302 |
+
|
303 |
+
# 指定したステップ数までText Encoderを学習する:epoch最初の状態
|
304 |
+
unet.train()
|
305 |
+
# train==True is required to enable gradient_checkpointing
|
306 |
+
if args.gradient_checkpointing or global_step < args.stop_text_encoder_training:
|
307 |
+
text_encoder.train()
|
308 |
+
|
309 |
+
for step, batch in enumerate(train_dataloader):
|
310 |
+
current_step.value = global_step
|
311 |
+
# 指定したステップ数でText Encoderの学習を止める
|
312 |
+
if global_step == args.stop_text_encoder_training:
|
313 |
+
accelerator.print(f"stop text encoder training at step {global_step}")
|
314 |
+
if not args.gradient_checkpointing:
|
315 |
+
text_encoder.train(False)
|
316 |
+
text_encoder.requires_grad_(False)
|
317 |
+
if len(training_models) == 2:
|
318 |
+
training_models = training_models[0] # remove text_encoder from training_models
|
319 |
+
|
320 |
+
with accelerator.accumulate(*training_models):
|
321 |
+
with torch.no_grad():
|
322 |
+
# latentに変換
|
323 |
+
if cache_latents:
|
324 |
+
latents = batch["latents"].to(accelerator.device).to(dtype=weight_dtype)
|
325 |
+
else:
|
326 |
+
latents = vae.encode(batch["images"].to(dtype=weight_dtype)).latent_dist.sample()
|
327 |
+
latents = latents * 0.18215
|
328 |
+
b_size = latents.shape[0]
|
329 |
+
|
330 |
+
# Get the text embedding for conditioning
|
331 |
+
with torch.set_grad_enabled(global_step < args.stop_text_encoder_training):
|
332 |
+
if args.weighted_captions:
|
333 |
+
encoder_hidden_states = get_weighted_text_embeddings(
|
334 |
+
tokenizer,
|
335 |
+
text_encoder,
|
336 |
+
batch["captions"],
|
337 |
+
accelerator.device,
|
338 |
+
args.max_token_length // 75 if args.max_token_length else 1,
|
339 |
+
clip_skip=args.clip_skip,
|
340 |
+
)
|
341 |
+
else:
|
342 |
+
input_ids = batch["input_ids"].to(accelerator.device)
|
343 |
+
encoder_hidden_states = train_util.get_hidden_states(
|
344 |
+
args, input_ids, tokenizer, text_encoder, None if not args.full_fp16 else weight_dtype
|
345 |
+
)
|
346 |
+
|
347 |
+
# Sample noise, sample a random timestep for each image, and add noise to the latents,
|
348 |
+
# with noise offset and/or multires noise if specified
|
349 |
+
noise, noisy_latents, timesteps, huber_c = train_util.get_noise_noisy_latents_and_timesteps(args, noise_scheduler, latents)
|
350 |
+
|
351 |
+
# Predict the noise residual
|
352 |
+
with accelerator.autocast():
|
353 |
+
noise_pred = unet(noisy_latents, timesteps, encoder_hidden_states).sample
|
354 |
+
|
355 |
+
if args.v_parameterization:
|
356 |
+
# v-parameterization training
|
357 |
+
target = noise_scheduler.get_velocity(latents, noise, timesteps)
|
358 |
+
else:
|
359 |
+
target = noise
|
360 |
+
|
361 |
+
loss = train_util.conditional_loss(noise_pred.float(), target.float(), reduction="none", loss_type=args.loss_type, huber_c=huber_c)
|
362 |
+
if args.masked_loss:
|
363 |
+
loss = apply_masked_loss(loss, batch)
|
364 |
+
loss = loss.mean([1, 2, 3])
|
365 |
+
|
366 |
+
loss_weights = batch["loss_weights"] # 各sampleごとのweight
|
367 |
+
loss = loss * loss_weights
|
368 |
+
|
369 |
+
if args.min_snr_gamma:
|
370 |
+
loss = apply_snr_weight(loss, timesteps, noise_scheduler, args.min_snr_gamma, args.v_parameterization)
|
371 |
+
if args.scale_v_pred_loss_like_noise_pred:
|
372 |
+
loss = scale_v_prediction_loss_like_noise_prediction(loss, timesteps, noise_scheduler)
|
373 |
+
if args.debiased_estimation_loss:
|
374 |
+
loss = apply_debiased_estimation(loss, timesteps, noise_scheduler)
|
375 |
+
|
376 |
+
loss = loss.mean() # 平均なのでbatch_sizeで割る必要なし
|
377 |
+
|
378 |
+
accelerator.backward(loss)
|
379 |
+
if accelerator.sync_gradients and args.max_grad_norm != 0.0:
|
380 |
+
if train_text_encoder:
|
381 |
+
params_to_clip = itertools.chain(unet.parameters(), text_encoder.parameters())
|
382 |
+
else:
|
383 |
+
params_to_clip = unet.parameters()
|
384 |
+
accelerator.clip_grad_norm_(params_to_clip, args.max_grad_norm)
|
385 |
+
|
386 |
+
optimizer.step()
|
387 |
+
lr_scheduler.step()
|
388 |
+
optimizer.zero_grad(set_to_none=True)
|
389 |
+
|
390 |
+
# Checks if the accelerator has performed an optimization step behind the scenes
|
391 |
+
if accelerator.sync_gradients:
|
392 |
+
progress_bar.update(1)
|
393 |
+
global_step += 1
|
394 |
+
|
395 |
+
train_util.sample_images(
|
396 |
+
accelerator, args, None, global_step, accelerator.device, vae, tokenizer, text_encoder, unet
|
397 |
+
)
|
398 |
+
|
399 |
+
# 指定ステップごとにモデルを保存
|
400 |
+
if args.save_every_n_steps is not None and global_step % args.save_every_n_steps == 0:
|
401 |
+
accelerator.wait_for_everyone()
|
402 |
+
if accelerator.is_main_process:
|
403 |
+
src_path = src_stable_diffusion_ckpt if save_stable_diffusion_format else src_diffusers_model_path
|
404 |
+
train_util.save_sd_model_on_epoch_end_or_stepwise(
|
405 |
+
args,
|
406 |
+
False,
|
407 |
+
accelerator,
|
408 |
+
src_path,
|
409 |
+
save_stable_diffusion_format,
|
410 |
+
use_safetensors,
|
411 |
+
save_dtype,
|
412 |
+
epoch,
|
413 |
+
num_train_epochs,
|
414 |
+
global_step,
|
415 |
+
accelerator.unwrap_model(text_encoder),
|
416 |
+
accelerator.unwrap_model(unet),
|
417 |
+
vae,
|
418 |
+
)
|
419 |
+
|
420 |
+
current_loss = loss.detach().item()
|
421 |
+
if args.logging_dir is not None:
|
422 |
+
logs = {"loss": current_loss}
|
423 |
+
train_util.append_lr_to_logs(logs, lr_scheduler, args.optimizer_type, including_unet=True)
|
424 |
+
accelerator.log(logs, step=global_step)
|
425 |
+
|
426 |
+
loss_recorder.add(epoch=epoch, step=step, loss=current_loss)
|
427 |
+
avr_loss: float = loss_recorder.moving_average
|
428 |
+
logs = {"avr_loss": avr_loss} # , "lr": lr_scheduler.get_last_lr()[0]}
|
429 |
+
progress_bar.set_postfix(**logs)
|
430 |
+
|
431 |
+
if global_step >= args.max_train_steps:
|
432 |
+
break
|
433 |
+
|
434 |
+
if args.logging_dir is not None:
|
435 |
+
logs = {"loss/epoch": loss_recorder.moving_average}
|
436 |
+
accelerator.log(logs, step=epoch + 1)
|
437 |
+
|
438 |
+
accelerator.wait_for_everyone()
|
439 |
+
|
440 |
+
if args.save_every_n_epochs is not None:
|
441 |
+
if accelerator.is_main_process:
|
442 |
+
# checking for saving is in util
|
443 |
+
src_path = src_stable_diffusion_ckpt if save_stable_diffusion_format else src_diffusers_model_path
|
444 |
+
train_util.save_sd_model_on_epoch_end_or_stepwise(
|
445 |
+
args,
|
446 |
+
True,
|
447 |
+
accelerator,
|
448 |
+
src_path,
|
449 |
+
save_stable_diffusion_format,
|
450 |
+
use_safetensors,
|
451 |
+
save_dtype,
|
452 |
+
epoch,
|
453 |
+
num_train_epochs,
|
454 |
+
global_step,
|
455 |
+
accelerator.unwrap_model(text_encoder),
|
456 |
+
accelerator.unwrap_model(unet),
|
457 |
+
vae,
|
458 |
+
)
|
459 |
+
|
460 |
+
train_util.sample_images(accelerator, args, epoch + 1, global_step, accelerator.device, vae, tokenizer, text_encoder, unet)
|
461 |
+
|
462 |
+
is_main_process = accelerator.is_main_process
|
463 |
+
if is_main_process:
|
464 |
+
unet = accelerator.unwrap_model(unet)
|
465 |
+
text_encoder = accelerator.unwrap_model(text_encoder)
|
466 |
+
|
467 |
+
accelerator.end_training()
|
468 |
+
|
469 |
+
if is_main_process and (args.save_state or args.save_state_on_train_end):
|
470 |
+
train_util.save_state_on_train_end(args, accelerator)
|
471 |
+
|
472 |
+
del accelerator # この後メモリを使うのでこれは消す
|
473 |
+
|
474 |
+
if is_main_process:
|
475 |
+
src_path = src_stable_diffusion_ckpt if save_stable_diffusion_format else src_diffusers_model_path
|
476 |
+
train_util.save_sd_model_on_train_end(
|
477 |
+
args, src_path, save_stable_diffusion_format, use_safetensors, save_dtype, epoch, global_step, text_encoder, unet, vae
|
478 |
+
)
|
479 |
+
logger.info("model saved.")
|
480 |
+
|
481 |
+
|
482 |
+
def setup_parser() -> argparse.ArgumentParser:
|
483 |
+
parser = argparse.ArgumentParser()
|
484 |
+
|
485 |
+
add_logging_arguments(parser)
|
486 |
+
train_util.add_sd_models_arguments(parser)
|
487 |
+
train_util.add_dataset_arguments(parser, True, False, True)
|
488 |
+
train_util.add_training_arguments(parser, True)
|
489 |
+
train_util.add_masked_loss_arguments(parser)
|
490 |
+
deepspeed_utils.add_deepspeed_arguments(parser)
|
491 |
+
train_util.add_sd_saving_arguments(parser)
|
492 |
+
train_util.add_optimizer_arguments(parser)
|
493 |
+
config_util.add_config_arguments(parser)
|
494 |
+
custom_train_functions.add_custom_train_arguments(parser)
|
495 |
+
|
496 |
+
parser.add_argument(
|
497 |
+
"--learning_rate_te",
|
498 |
+
type=float,
|
499 |
+
default=None,
|
500 |
+
help="learning rate for text encoder, default is same as unet / Text Encoderの学習率、デフォルトはunetと同じ",
|
501 |
+
)
|
502 |
+
parser.add_argument(
|
503 |
+
"--no_token_padding",
|
504 |
+
action="store_true",
|
505 |
+
help="disable token padding (same as Diffuser's DreamBooth) / トークンのpaddingを無効にする(Diffusers版DreamBoothと同じ動作)",
|
506 |
+
)
|
507 |
+
parser.add_argument(
|
508 |
+
"--stop_text_encoder_training",
|
509 |
+
type=int,
|
510 |
+
default=None,
|
511 |
+
help="steps to stop text encoder training, -1 for no training / Text Encoderの学習を止めるステップ数、-1で最初から学習しない",
|
512 |
+
)
|
513 |
+
parser.add_argument(
|
514 |
+
"--no_half_vae",
|
515 |
+
action="store_true",
|
516 |
+
help="do not use fp16/bf16 VAE in mixed precision (use float VAE) / mixed precisionでも fp16/bf16 VAEを使わずfloat VAEを使う",
|
517 |
+
)
|
518 |
+
|
519 |
+
return parser
|
520 |
+
|
521 |
+
|
522 |
+
if __name__ == "__main__":
|
523 |
+
parser = setup_parser()
|
524 |
+
|
525 |
+
args = parser.parse_args()
|
526 |
+
train_util.verify_command_line_training_args(args)
|
527 |
+
args = train_util.read_config_from_file(args, parser)
|
528 |
+
|
529 |
+
train(args)
|