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