ACCC1380 commited on
Commit
1d4d039
1 Parent(s): 5bffbab

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

Browse files
lora-scripts/sd-scripts/train_textual_inversion.py ADDED
@@ -0,0 +1,813 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import math
3
+ import os
4
+ from multiprocessing import Value
5
+ import toml
6
+
7
+ from tqdm import tqdm
8
+
9
+ import torch
10
+ from library.device_utils import init_ipex, clean_memory_on_device
11
+
12
+
13
+ init_ipex()
14
+
15
+ from accelerate.utils import set_seed
16
+ from diffusers import DDPMScheduler
17
+ from transformers import CLIPTokenizer
18
+ from library import deepspeed_utils, model_util
19
+
20
+ import library.train_util as train_util
21
+ import library.huggingface_util as huggingface_util
22
+ import library.config_util as config_util
23
+ from library.config_util import (
24
+ ConfigSanitizer,
25
+ BlueprintGenerator,
26
+ )
27
+ import library.custom_train_functions as custom_train_functions
28
+ from library.custom_train_functions import (
29
+ apply_snr_weight,
30
+ prepare_scheduler_for_custom_training,
31
+ scale_v_prediction_loss_like_noise_prediction,
32
+ add_v_prediction_like_loss,
33
+ apply_debiased_estimation,
34
+ apply_masked_loss,
35
+ )
36
+ from library.utils import setup_logging, add_logging_arguments
37
+
38
+ setup_logging()
39
+ import logging
40
+
41
+ logger = logging.getLogger(__name__)
42
+
43
+ imagenet_templates_small = [
44
+ "a photo of a {}",
45
+ "a rendering of a {}",
46
+ "a cropped photo of the {}",
47
+ "the photo of a {}",
48
+ "a photo of a clean {}",
49
+ "a photo of a dirty {}",
50
+ "a dark photo of the {}",
51
+ "a photo of my {}",
52
+ "a photo of the cool {}",
53
+ "a close-up photo of a {}",
54
+ "a bright photo of the {}",
55
+ "a cropped photo of a {}",
56
+ "a photo of the {}",
57
+ "a good photo of the {}",
58
+ "a photo of one {}",
59
+ "a close-up photo of the {}",
60
+ "a rendition of the {}",
61
+ "a photo of the clean {}",
62
+ "a rendition of a {}",
63
+ "a photo of a nice {}",
64
+ "a good photo of a {}",
65
+ "a photo of the nice {}",
66
+ "a photo of the small {}",
67
+ "a photo of the weird {}",
68
+ "a photo of the large {}",
69
+ "a photo of a cool {}",
70
+ "a photo of a small {}",
71
+ ]
72
+
73
+ imagenet_style_templates_small = [
74
+ "a painting in the style of {}",
75
+ "a rendering in the style of {}",
76
+ "a cropped painting in the style of {}",
77
+ "the painting in the style of {}",
78
+ "a clean painting in the style of {}",
79
+ "a dirty painting in the style of {}",
80
+ "a dark painting in the style of {}",
81
+ "a picture in the style of {}",
82
+ "a cool painting in the style of {}",
83
+ "a close-up painting in the style of {}",
84
+ "a bright painting in the style of {}",
85
+ "a cropped painting in the style of {}",
86
+ "a good painting in the style of {}",
87
+ "a close-up painting in the style of {}",
88
+ "a rendition in the style of {}",
89
+ "a nice painting in the style of {}",
90
+ "a small painting in the style of {}",
91
+ "a weird painting in the style of {}",
92
+ "a large painting in the style of {}",
93
+ ]
94
+
95
+
96
+ class TextualInversionTrainer:
97
+ def __init__(self):
98
+ self.vae_scale_factor = 0.18215
99
+ self.is_sdxl = False
100
+
101
+ def assert_extra_args(self, args, train_dataset_group):
102
+ pass
103
+
104
+ def load_target_model(self, args, weight_dtype, accelerator):
105
+ text_encoder, vae, unet, _ = train_util.load_target_model(args, weight_dtype, accelerator)
106
+ return model_util.get_model_version_str_for_sd1_sd2(args.v2, args.v_parameterization), text_encoder, vae, unet
107
+
108
+ def load_tokenizer(self, args):
109
+ tokenizer = train_util.load_tokenizer(args)
110
+ return tokenizer
111
+
112
+ def assert_token_string(self, token_string, tokenizers: CLIPTokenizer):
113
+ pass
114
+
115
+ def get_text_cond(self, args, accelerator, batch, tokenizers, text_encoders, weight_dtype):
116
+ with torch.enable_grad():
117
+ input_ids = batch["input_ids"].to(accelerator.device)
118
+ encoder_hidden_states = train_util.get_hidden_states(args, input_ids, tokenizers[0], text_encoders[0], None)
119
+ return encoder_hidden_states
120
+
121
+ def call_unet(self, args, accelerator, unet, noisy_latents, timesteps, text_conds, batch, weight_dtype):
122
+ noise_pred = unet(noisy_latents, timesteps, text_conds).sample
123
+ return noise_pred
124
+
125
+ def sample_images(self, accelerator, args, epoch, global_step, device, vae, tokenizer, text_encoder, unet, prompt_replacement):
126
+ train_util.sample_images(
127
+ accelerator, args, epoch, global_step, device, vae, tokenizer, text_encoder, unet, prompt_replacement
128
+ )
129
+
130
+ def save_weights(self, file, updated_embs, save_dtype, metadata):
131
+ state_dict = {"emb_params": updated_embs[0]}
132
+
133
+ if save_dtype is not None:
134
+ for key in list(state_dict.keys()):
135
+ v = state_dict[key]
136
+ v = v.detach().clone().to("cpu").to(save_dtype)
137
+ state_dict[key] = v
138
+
139
+ if os.path.splitext(file)[1] == ".safetensors":
140
+ from safetensors.torch import save_file
141
+
142
+ save_file(state_dict, file, metadata)
143
+ else:
144
+ torch.save(state_dict, file) # can be loaded in Web UI
145
+
146
+ def load_weights(self, file):
147
+ if os.path.splitext(file)[1] == ".safetensors":
148
+ from safetensors.torch import load_file
149
+
150
+ data = load_file(file)
151
+ else:
152
+ # compatible to Web UI's file format
153
+ data = torch.load(file, map_location="cpu")
154
+ if type(data) != dict:
155
+ raise ValueError(f"weight file is not dict / 重みファイルがdict形式ではありません: {file}")
156
+
157
+ if "string_to_param" in data: # textual inversion embeddings
158
+ data = data["string_to_param"]
159
+ if hasattr(data, "_parameters"): # support old PyTorch?
160
+ data = getattr(data, "_parameters")
161
+
162
+ emb = next(iter(data.values()))
163
+ if type(emb) != torch.Tensor:
164
+ raise ValueError(f"weight file does not contains Tensor / 重みファイルのデータがTensorではありません: {file}")
165
+
166
+ if len(emb.size()) == 1:
167
+ emb = emb.unsqueeze(0)
168
+
169
+ return [emb]
170
+
171
+ def train(self, args):
172
+ if args.output_name is None:
173
+ args.output_name = args.token_string
174
+ use_template = args.use_object_template or args.use_style_template
175
+
176
+ train_util.verify_training_args(args)
177
+ train_util.prepare_dataset_args(args, True)
178
+ setup_logging(args, reset=True)
179
+
180
+ cache_latents = args.cache_latents
181
+
182
+ if args.seed is not None:
183
+ set_seed(args.seed)
184
+
185
+ tokenizer_or_list = self.load_tokenizer(args) # list of tokenizer or tokenizer
186
+ tokenizers = tokenizer_or_list if isinstance(tokenizer_or_list, list) else [tokenizer_or_list]
187
+
188
+ # acceleratorを準備する
189
+ logger.info("prepare accelerator")
190
+ accelerator = train_util.prepare_accelerator(args)
191
+
192
+ # mixed precisionに対応した型を用意しておき適宜castする
193
+ weight_dtype, save_dtype = train_util.prepare_dtype(args)
194
+ vae_dtype = torch.float32 if args.no_half_vae else weight_dtype
195
+
196
+ # モデルを読み込む
197
+ model_version, text_encoder_or_list, vae, unet = self.load_target_model(args, weight_dtype, accelerator)
198
+ text_encoders = [text_encoder_or_list] if not isinstance(text_encoder_or_list, list) else text_encoder_or_list
199
+
200
+ if len(text_encoders) > 1 and args.gradient_accumulation_steps > 1:
201
+ accelerator.print(
202
+ "accelerate doesn't seem to support gradient_accumulation_steps for multiple models (text encoders) / "
203
+ + "accelerateでは複数のモデル(テキストエンコーダー)のgradient_accumulation_stepsはサポートされていないようです"
204
+ )
205
+
206
+ # Convert the init_word to token_id
207
+ init_token_ids_list = []
208
+ if args.init_word is not None:
209
+ for i, tokenizer in enumerate(tokenizers):
210
+ init_token_ids = tokenizer.encode(args.init_word, add_special_tokens=False)
211
+ if len(init_token_ids) > 1 and len(init_token_ids) != args.num_vectors_per_token:
212
+ accelerator.print(
213
+ f"token length for init words is not same to num_vectors_per_token, init words is repeated or truncated / "
214
+ + f"初期化単語のトークン長がnum_vectors_per_tokenと合わないため、繰り返しまたは切り捨てが発生します: tokenizer {i+1}, length {len(init_token_ids)}"
215
+ )
216
+ init_token_ids_list.append(init_token_ids)
217
+ else:
218
+ init_token_ids_list = [None] * len(tokenizers)
219
+
220
+ # tokenizerに新しい単語を追加する。追加する単語の数はnum_vectors_per_token
221
+ # token_stringが hoge の場合、"hoge", "hoge1", "hoge2", ... が追加される
222
+ # add new word to tokenizer, count is num_vectors_per_token
223
+ # if token_string is hoge, "hoge", "hoge1", "hoge2", ... are added
224
+
225
+ self.assert_token_string(args.token_string, tokenizers)
226
+
227
+ token_strings = [args.token_string] + [f"{args.token_string}{i+1}" for i in range(args.num_vectors_per_token - 1)]
228
+ token_ids_list = []
229
+ token_embeds_list = []
230
+ for i, (tokenizer, text_encoder, init_token_ids) in enumerate(zip(tokenizers, text_encoders, init_token_ids_list)):
231
+ num_added_tokens = tokenizer.add_tokens(token_strings)
232
+ assert (
233
+ num_added_tokens == args.num_vectors_per_token
234
+ ), f"tokenizer has same word to token string. please use another one / 指定したargs.token_stringは既に存在します。別の単語を使ってください: tokenizer {i+1}, {args.token_string}"
235
+
236
+ token_ids = tokenizer.convert_tokens_to_ids(token_strings)
237
+ accelerator.print(f"tokens are added for tokenizer {i+1}: {token_ids}")
238
+ assert (
239
+ min(token_ids) == token_ids[0] and token_ids[-1] == token_ids[0] + len(token_ids) - 1
240
+ ), f"token ids is not ordered : tokenizer {i+1}, {token_ids}"
241
+ assert (
242
+ len(tokenizer) - 1 == token_ids[-1]
243
+ ), f"token ids is not end of tokenize: tokenizer {i+1}, {token_ids}, {len(tokenizer)}"
244
+ token_ids_list.append(token_ids)
245
+
246
+ # Resize the token embeddings as we are adding new special tokens to the tokenizer
247
+ text_encoder.resize_token_embeddings(len(tokenizer))
248
+
249
+ # Initialise the newly added placeholder token with the embeddings of the initializer token
250
+ token_embeds = text_encoder.get_input_embeddings().weight.data
251
+ if init_token_ids is not None:
252
+ for i, token_id in enumerate(token_ids):
253
+ token_embeds[token_id] = token_embeds[init_token_ids[i % len(init_token_ids)]]
254
+ # accelerator.print(token_id, token_embeds[token_id].mean(), token_embeds[token_id].min())
255
+ token_embeds_list.append(token_embeds)
256
+
257
+ # load weights
258
+ if args.weights is not None:
259
+ embeddings_list = self.load_weights(args.weights)
260
+ assert len(token_ids) == len(
261
+ embeddings_list[0]
262
+ ), f"num_vectors_per_token is mismatch for weights / 指定した重みとnum_vectors_per_tokenの値が異なります: {len(embeddings)}"
263
+ # accelerator.print(token_ids, embeddings.size())
264
+ for token_ids, embeddings, token_embeds in zip(token_ids_list, embeddings_list, token_embeds_list):
265
+ for token_id, embedding in zip(token_ids, embeddings):
266
+ token_embeds[token_id] = embedding
267
+ # accelerator.print(token_id, token_embeds[token_id].mean(), token_embeds[token_id].min())
268
+ accelerator.print(f"weighs loaded")
269
+
270
+ accelerator.print(f"create embeddings for {args.num_vectors_per_token} tokens, for {args.token_string}")
271
+
272
+ # データセットを準備する
273
+ if args.dataset_class is None:
274
+ blueprint_generator = BlueprintGenerator(ConfigSanitizer(True, True, args.masked_loss, False))
275
+ if args.dataset_config is not None:
276
+ accelerator.print(f"Load dataset config from {args.dataset_config}")
277
+ user_config = config_util.load_user_config(args.dataset_config)
278
+ ignored = ["train_data_dir", "reg_data_dir", "in_json"]
279
+ if any(getattr(args, attr) is not None for attr in ignored):
280
+ accelerator.print(
281
+ "ignore following options because config file is found: {0} / 設定ファイルが利用されるため以下のオプションは無視されます: {0}".format(
282
+ ", ".join(ignored)
283
+ )
284
+ )
285
+ else:
286
+ use_dreambooth_method = args.in_json is None
287
+ if use_dreambooth_method:
288
+ accelerator.print("Use DreamBooth method.")
289
+ user_config = {
290
+ "datasets": [
291
+ {
292
+ "subsets": config_util.generate_dreambooth_subsets_config_by_subdirs(
293
+ args.train_data_dir, args.reg_data_dir
294
+ )
295
+ }
296
+ ]
297
+ }
298
+ else:
299
+ logger.info("Train with captions.")
300
+ user_config = {
301
+ "datasets": [
302
+ {
303
+ "subsets": [
304
+ {
305
+ "image_dir": args.train_data_dir,
306
+ "metadata_file": args.in_json,
307
+ }
308
+ ]
309
+ }
310
+ ]
311
+ }
312
+
313
+ blueprint = blueprint_generator.generate(user_config, args, tokenizer=tokenizer_or_list)
314
+ train_dataset_group = config_util.generate_dataset_group_by_blueprint(blueprint.dataset_group)
315
+ else:
316
+ train_dataset_group = train_util.load_arbitrary_dataset(args, tokenizer_or_list)
317
+
318
+ self.assert_extra_args(args, train_dataset_group)
319
+
320
+ current_epoch = Value("i", 0)
321
+ current_step = Value("i", 0)
322
+ ds_for_collator = train_dataset_group if args.max_data_loader_n_workers == 0 else None
323
+ collator = train_util.collator_class(current_epoch, current_step, ds_for_collator)
324
+
325
+ # make captions: tokenstring tokenstring1 tokenstring2 ...tokenstringn という文字列に書き換える超乱暴な実装
326
+ if use_template:
327
+ accelerator.print(f"use template for training captions. is object: {args.use_object_template}")
328
+ templates = imagenet_templates_small if args.use_object_template else imagenet_style_templates_small
329
+ replace_to = " ".join(token_strings)
330
+ captions = []
331
+ for tmpl in templates:
332
+ captions.append(tmpl.format(replace_to))
333
+ train_dataset_group.add_replacement("", captions)
334
+
335
+ # サンプル生成用
336
+ if args.num_vectors_per_token > 1:
337
+ prompt_replacement = (args.token_string, replace_to)
338
+ else:
339
+ prompt_replacement = None
340
+ else:
341
+ # サンプル生成用
342
+ if args.num_vectors_per_token > 1:
343
+ replace_to = " ".join(token_strings)
344
+ train_dataset_group.add_replacement(args.token_string, replace_to)
345
+ prompt_replacement = (args.token_string, replace_to)
346
+ else:
347
+ prompt_replacement = None
348
+
349
+ if args.debug_dataset:
350
+ train_util.debug_dataset(train_dataset_group, show_input_ids=True)
351
+ return
352
+ if len(train_dataset_group) == 0:
353
+ accelerator.print("No data found. Please verify arguments / 画像がありません。引数指定を確認してください")
354
+ return
355
+
356
+ if cache_latents:
357
+ assert (
358
+ train_dataset_group.is_latent_cacheable()
359
+ ), "when caching latents, either color_aug or random_crop cannot be used / latentをキャッシュするときはcolor_augとrandom_cropは使えません"
360
+
361
+ # モデルに xformers とか memory efficient attention を組み込む
362
+ train_util.replace_unet_modules(unet, args.mem_eff_attn, args.xformers, args.sdpa)
363
+ if torch.__version__ >= "2.0.0": # PyTorch 2.0.0 以上対応のxformersなら以下が使える
364
+ vae.set_use_memory_efficient_attention_xformers(args.xformers)
365
+
366
+ # 学習を準備する
367
+ if cache_latents:
368
+ vae.to(accelerator.device, dtype=vae_dtype)
369
+ vae.requires_grad_(False)
370
+ vae.eval()
371
+ with torch.no_grad():
372
+ train_dataset_group.cache_latents(vae, args.vae_batch_size, args.cache_latents_to_disk, accelerator.is_main_process)
373
+ vae.to("cpu")
374
+ clean_memory_on_device(accelerator.device)
375
+
376
+ accelerator.wait_for_everyone()
377
+
378
+ if args.gradient_checkpointing:
379
+ unet.enable_gradient_checkpointing()
380
+ for text_encoder in text_encoders:
381
+ text_encoder.gradient_checkpointing_enable()
382
+
383
+ # 学習に必要なクラスを準備する
384
+ accelerator.print("prepare optimizer, data loader etc.")
385
+ trainable_params = []
386
+ for text_encoder in text_encoders:
387
+ trainable_params += text_encoder.get_input_embeddings().parameters()
388
+ _, _, optimizer = train_util.get_optimizer(args, trainable_params)
389
+
390
+ # dataloaderを準備する
391
+ # DataLoaderのプロセス数:0 は persistent_workers が使えないので注意
392
+ n_workers = min(args.max_data_loader_n_workers, os.cpu_count()) # cpu_count or max_data_loader_n_workers
393
+ train_dataloader = torch.utils.data.DataLoader(
394
+ train_dataset_group,
395
+ batch_size=1,
396
+ shuffle=True,
397
+ collate_fn=collator,
398
+ num_workers=n_workers,
399
+ persistent_workers=args.persistent_data_loader_workers,
400
+ )
401
+
402
+ # 学習ステップ数を計算する
403
+ if args.max_train_epochs is not None:
404
+ args.max_train_steps = args.max_train_epochs * math.ceil(
405
+ len(train_dataloader) / accelerator.num_processes / args.gradient_accumulation_steps
406
+ )
407
+ accelerator.print(
408
+ f"override steps. steps for {args.max_train_epochs} epochs is / 指定エポックまでのステップ数: {args.max_train_steps}"
409
+ )
410
+
411
+ # データセット側にも学習ステップを送信
412
+ train_dataset_group.set_max_train_steps(args.max_train_steps)
413
+
414
+ # lr schedulerを用意する
415
+ lr_scheduler = train_util.get_scheduler_fix(args, optimizer, accelerator.num_processes)
416
+
417
+ # acceleratorがなんかよろしくやってくれるらしい
418
+ if len(text_encoders) == 1:
419
+ text_encoder_or_list, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
420
+ text_encoder_or_list, optimizer, train_dataloader, lr_scheduler
421
+ )
422
+
423
+ elif len(text_encoders) == 2:
424
+ text_encoder1, text_encoder2, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
425
+ text_encoders[0], text_encoders[1], optimizer, train_dataloader, lr_scheduler
426
+ )
427
+
428
+ text_encoder_or_list = text_encoders = [text_encoder1, text_encoder2]
429
+
430
+ else:
431
+ raise NotImplementedError()
432
+
433
+ index_no_updates_list = []
434
+ orig_embeds_params_list = []
435
+ for tokenizer, token_ids, text_encoder in zip(tokenizers, token_ids_list, text_encoders):
436
+ index_no_updates = torch.arange(len(tokenizer)) < token_ids[0]
437
+ index_no_updates_list.append(index_no_updates)
438
+
439
+ # accelerator.print(len(index_no_updates), torch.sum(index_no_updates))
440
+ orig_embeds_params = accelerator.unwrap_model(text_encoder).get_input_embeddings().weight.data.detach().clone()
441
+ orig_embeds_params_list.append(orig_embeds_params)
442
+
443
+ # Freeze all parameters except for the token embeddings in text encoder
444
+ text_encoder.requires_grad_(True)
445
+ unwrapped_text_encoder = accelerator.unwrap_model(text_encoder)
446
+ unwrapped_text_encoder.text_model.encoder.requires_grad_(False)
447
+ unwrapped_text_encoder.text_model.final_layer_norm.requires_grad_(False)
448
+ unwrapped_text_encoder.text_model.embeddings.position_embedding.requires_grad_(False)
449
+ # text_encoder.text_model.embeddings.token_embedding.requires_grad_(True)
450
+
451
+ unet.requires_grad_(False)
452
+ unet.to(accelerator.device, dtype=weight_dtype)
453
+ if args.gradient_checkpointing: # according to TI example in Diffusers, train is required
454
+ # TODO U-Netをオリジナルに置き換えたのでいらないはずなので、後で確認して消す
455
+ unet.train()
456
+ else:
457
+ unet.eval()
458
+
459
+ if not cache_latents: # キャッシュしない場合はVAEを使うのでVAEを準備する
460
+ vae.requires_grad_(False)
461
+ vae.eval()
462
+ vae.to(accelerator.device, dtype=vae_dtype)
463
+
464
+ # 実験的機能:勾配も含めたfp16学習を行う PyTorchにパッチを当ててfp16でのgrad scaleを有効にする
465
+ if args.full_fp16:
466
+ train_util.patch_accelerator_for_fp16_training(accelerator)
467
+ for text_encoder in text_encoders:
468
+ text_encoder.to(weight_dtype)
469
+ if args.full_bf16:
470
+ for text_encoder in text_encoders:
471
+ text_encoder.to(weight_dtype)
472
+
473
+ # resumeする
474
+ train_util.resume_from_local_or_hf_if_specified(accelerator, args)
475
+
476
+ # epoch数を計算する
477
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
478
+ num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
479
+ if (args.save_n_epoch_ratio is not None) and (args.save_n_epoch_ratio > 0):
480
+ args.save_every_n_epochs = math.floor(num_train_epochs / args.save_n_epoch_ratio) or 1
481
+
482
+ # 学習する
483
+ total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
484
+ accelerator.print("running training / 学習開始")
485
+ accelerator.print(f" num train images * repeats / 学習画像の数×繰り返し回数: {train_dataset_group.num_train_images}")
486
+ accelerator.print(f" num reg images / 正則化画像の数: {train_dataset_group.num_reg_images}")
487
+ accelerator.print(f" num batches per epoch / 1epochのバッチ数: {len(train_dataloader)}")
488
+ accelerator.print(f" num epochs / epoch数: {num_train_epochs}")
489
+ accelerator.print(f" batch size per device / バッチサイズ: {args.train_batch_size}")
490
+ accelerator.print(
491
+ f" total train batch size (with parallel & distributed & accumulation) / 総バッチサイズ(並列学習、勾配合計含む): {total_batch_size}"
492
+ )
493
+ accelerator.print(f" gradient ccumulation steps / 勾配を合計するステップ数 = {args.gradient_accumulation_steps}")
494
+ accelerator.print(f" total optimization steps / 学習ステップ数: {args.max_train_steps}")
495
+
496
+ progress_bar = tqdm(range(args.max_train_steps), smoothing=0, disable=not accelerator.is_local_main_process, desc="steps")
497
+ global_step = 0
498
+
499
+ noise_scheduler = DDPMScheduler(
500
+ beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", num_train_timesteps=1000, clip_sample=False
501
+ )
502
+ prepare_scheduler_for_custom_training(noise_scheduler, accelerator.device)
503
+ if args.zero_terminal_snr:
504
+ custom_train_functions.fix_noise_scheduler_betas_for_zero_terminal_snr(noise_scheduler)
505
+
506
+ if accelerator.is_main_process:
507
+ init_kwargs = {}
508
+ if args.wandb_run_name:
509
+ init_kwargs["wandb"] = {"name": args.wandb_run_name}
510
+ if args.log_tracker_config is not None:
511
+ init_kwargs = toml.load(args.log_tracker_config)
512
+ accelerator.init_trackers(
513
+ "textual_inversion" if args.log_tracker_name is None else args.log_tracker_name, init_kwargs=init_kwargs
514
+ )
515
+
516
+ # function for saving/removing
517
+ def save_model(ckpt_name, embs_list, steps, epoch_no, force_sync_upload=False):
518
+ os.makedirs(args.output_dir, exist_ok=True)
519
+ ckpt_file = os.path.join(args.output_dir, ckpt_name)
520
+
521
+ accelerator.print(f"\nsaving checkpoint: {ckpt_file}")
522
+
523
+ sai_metadata = train_util.get_sai_model_spec(None, args, self.is_sdxl, False, True)
524
+
525
+ self.save_weights(ckpt_file, embs_list, save_dtype, sai_metadata)
526
+ if args.huggingface_repo_id is not None:
527
+ huggingface_util.upload(args, ckpt_file, "/" + ckpt_name, force_sync_upload=force_sync_upload)
528
+
529
+ def remove_model(old_ckpt_name):
530
+ old_ckpt_file = os.path.join(args.output_dir, old_ckpt_name)
531
+ if os.path.exists(old_ckpt_file):
532
+ accelerator.print(f"removing old checkpoint: {old_ckpt_file}")
533
+ os.remove(old_ckpt_file)
534
+
535
+ # For --sample_at_first
536
+ self.sample_images(
537
+ accelerator,
538
+ args,
539
+ 0,
540
+ global_step,
541
+ accelerator.device,
542
+ vae,
543
+ tokenizer_or_list,
544
+ text_encoder_or_list,
545
+ unet,
546
+ prompt_replacement,
547
+ )
548
+
549
+ # training loop
550
+ for epoch in range(num_train_epochs):
551
+ accelerator.print(f"\nepoch {epoch+1}/{num_train_epochs}")
552
+ current_epoch.value = epoch + 1
553
+
554
+ for text_encoder in text_encoders:
555
+ text_encoder.train()
556
+
557
+ loss_total = 0
558
+
559
+ for step, batch in enumerate(train_dataloader):
560
+ current_step.value = global_step
561
+ with accelerator.accumulate(text_encoders[0]):
562
+ with torch.no_grad():
563
+ if "latents" in batch and batch["latents"] is not None:
564
+ latents = batch["latents"].to(accelerator.device).to(dtype=weight_dtype)
565
+ else:
566
+ # latentに変換
567
+ latents = vae.encode(batch["images"].to(dtype=vae_dtype)).latent_dist.sample().to(dtype=weight_dtype)
568
+ latents = latents * self.vae_scale_factor
569
+
570
+ # Get the text embedding for conditioning
571
+ text_encoder_conds = self.get_text_cond(args, accelerator, batch, tokenizers, text_encoders, weight_dtype)
572
+
573
+ # Sample noise, sample a random timestep for each image, and add noise to the latents,
574
+ # with noise offset and/or multires noise if specified
575
+ noise, noisy_latents, timesteps, huber_c = train_util.get_noise_noisy_latents_and_timesteps(
576
+ args, noise_scheduler, latents
577
+ )
578
+
579
+ # Predict the noise residual
580
+ with accelerator.autocast():
581
+ noise_pred = self.call_unet(
582
+ args, accelerator, unet, noisy_latents, timesteps, text_encoder_conds, batch, weight_dtype
583
+ )
584
+
585
+ if args.v_parameterization:
586
+ # v-parameterization training
587
+ target = noise_scheduler.get_velocity(latents, noise, timesteps)
588
+ else:
589
+ target = noise
590
+
591
+ loss = train_util.conditional_loss(noise_pred.float(), target.float(), reduction="none", loss_type=args.loss_type, huber_c=huber_c)
592
+ if args.masked_loss:
593
+ loss = apply_masked_loss(loss, batch)
594
+ loss = loss.mean([1, 2, 3])
595
+
596
+ loss_weights = batch["loss_weights"] # 各sampleごとのweight
597
+ loss = loss * loss_weights
598
+
599
+ if args.min_snr_gamma:
600
+ loss = apply_snr_weight(loss, timesteps, noise_scheduler, args.min_snr_gamma, args.v_parameterization)
601
+ if args.scale_v_pred_loss_like_noise_pred:
602
+ loss = scale_v_prediction_loss_like_noise_prediction(loss, timesteps, noise_scheduler)
603
+ if args.v_pred_like_loss:
604
+ loss = add_v_prediction_like_loss(loss, timesteps, noise_scheduler, args.v_pred_like_loss)
605
+ if args.debiased_estimation_loss:
606
+ loss = apply_debiased_estimation(loss, timesteps, noise_scheduler)
607
+
608
+ loss = loss.mean() # 平均なのでbatch_sizeで割る必要なし
609
+
610
+ accelerator.backward(loss)
611
+ if accelerator.sync_gradients and args.max_grad_norm != 0.0:
612
+ params_to_clip = accelerator.unwrap_model(text_encoder).get_input_embeddings().parameters()
613
+ accelerator.clip_grad_norm_(params_to_clip, args.max_grad_norm)
614
+
615
+ optimizer.step()
616
+ lr_scheduler.step()
617
+ optimizer.zero_grad(set_to_none=True)
618
+
619
+ # Let's make sure we don't update any embedding weights besides the newly added token
620
+ with torch.no_grad():
621
+ for text_encoder, orig_embeds_params, index_no_updates in zip(
622
+ text_encoders, orig_embeds_params_list, index_no_updates_list
623
+ ):
624
+ # if full_fp16/bf16, input_embeddings_weight is fp16/bf16, orig_embeds_params is fp32
625
+ input_embeddings_weight = accelerator.unwrap_model(text_encoder).get_input_embeddings().weight
626
+ input_embeddings_weight[index_no_updates] = orig_embeds_params.to(input_embeddings_weight.dtype)[
627
+ index_no_updates
628
+ ]
629
+
630
+ # Checks if the accelerator has performed an optimization step behind the scenes
631
+ if accelerator.sync_gradients:
632
+ progress_bar.update(1)
633
+ global_step += 1
634
+
635
+ self.sample_images(
636
+ accelerator,
637
+ args,
638
+ None,
639
+ global_step,
640
+ accelerator.device,
641
+ vae,
642
+ tokenizer_or_list,
643
+ text_encoder_or_list,
644
+ unet,
645
+ prompt_replacement,
646
+ )
647
+
648
+ # 指定ステップごとにモデルを保存
649
+ if args.save_every_n_steps is not None and global_step % args.save_every_n_steps == 0:
650
+ accelerator.wait_for_everyone()
651
+ if accelerator.is_main_process:
652
+ updated_embs_list = []
653
+ for text_encoder, token_ids in zip(text_encoders, token_ids_list):
654
+ updated_embs = (
655
+ accelerator.unwrap_model(text_encoder)
656
+ .get_input_embeddings()
657
+ .weight[token_ids]
658
+ .data.detach()
659
+ .clone()
660
+ )
661
+ updated_embs_list.append(updated_embs)
662
+
663
+ ckpt_name = train_util.get_step_ckpt_name(args, "." + args.save_model_as, global_step)
664
+ save_model(ckpt_name, updated_embs_list, global_step, epoch)
665
+
666
+ if args.save_state:
667
+ train_util.save_and_remove_state_stepwise(args, accelerator, global_step)
668
+
669
+ remove_step_no = train_util.get_remove_step_no(args, global_step)
670
+ if remove_step_no is not None:
671
+ remove_ckpt_name = train_util.get_step_ckpt_name(args, "." + args.save_model_as, remove_step_no)
672
+ remove_model(remove_ckpt_name)
673
+
674
+ current_loss = loss.detach().item()
675
+ if args.logging_dir is not None:
676
+ logs = {"loss": current_loss, "lr": float(lr_scheduler.get_last_lr()[0])}
677
+ if (
678
+ args.optimizer_type.lower().startswith("DAdapt".lower()) or args.optimizer_type.lower() == "Prodigy".lower()
679
+ ): # tracking d*lr value
680
+ logs["lr/d*lr"] = (
681
+ lr_scheduler.optimizers[0].param_groups[0]["d"] * lr_scheduler.optimizers[0].param_groups[0]["lr"]
682
+ )
683
+ accelerator.log(logs, step=global_step)
684
+
685
+ loss_total += current_loss
686
+ avr_loss = loss_total / (step + 1)
687
+ logs = {"loss": avr_loss} # , "lr": lr_scheduler.get_last_lr()[0]}
688
+ progress_bar.set_postfix(**logs)
689
+
690
+ if global_step >= args.max_train_steps:
691
+ break
692
+
693
+ if args.logging_dir is not None:
694
+ logs = {"loss/epoch": loss_total / len(train_dataloader)}
695
+ accelerator.log(logs, step=epoch + 1)
696
+
697
+ accelerator.wait_for_everyone()
698
+
699
+ updated_embs_list = []
700
+ for text_encoder, token_ids in zip(text_encoders, token_ids_list):
701
+ updated_embs = accelerator.unwrap_model(text_encoder).get_input_embeddings().weight[token_ids].data.detach().clone()
702
+ updated_embs_list.append(updated_embs)
703
+
704
+ if args.save_every_n_epochs is not None:
705
+ saving = (epoch + 1) % args.save_every_n_epochs == 0 and (epoch + 1) < num_train_epochs
706
+ if accelerator.is_main_process and saving:
707
+ ckpt_name = train_util.get_epoch_ckpt_name(args, "." + args.save_model_as, epoch + 1)
708
+ save_model(ckpt_name, updated_embs_list, epoch + 1, global_step)
709
+
710
+ remove_epoch_no = train_util.get_remove_epoch_no(args, epoch + 1)
711
+ if remove_epoch_no is not None:
712
+ remove_ckpt_name = train_util.get_epoch_ckpt_name(args, "." + args.save_model_as, remove_epoch_no)
713
+ remove_model(remove_ckpt_name)
714
+
715
+ if args.save_state:
716
+ train_util.save_and_remove_state_on_epoch_end(args, accelerator, epoch + 1)
717
+
718
+ self.sample_images(
719
+ accelerator,
720
+ args,
721
+ epoch + 1,
722
+ global_step,
723
+ accelerator.device,
724
+ vae,
725
+ tokenizer_or_list,
726
+ text_encoder_or_list,
727
+ unet,
728
+ prompt_replacement,
729
+ )
730
+
731
+ # end of epoch
732
+
733
+ is_main_process = accelerator.is_main_process
734
+ if is_main_process:
735
+ text_encoder = accelerator.unwrap_model(text_encoder)
736
+ updated_embs = text_encoder.get_input_embeddings().weight[token_ids].data.detach().clone()
737
+
738
+ accelerator.end_training()
739
+
740
+ if is_main_process and (args.save_state or args.save_state_on_train_end):
741
+ train_util.save_state_on_train_end(args, accelerator)
742
+
743
+ if is_main_process:
744
+ ckpt_name = train_util.get_last_ckpt_name(args, "." + args.save_model_as)
745
+ save_model(ckpt_name, updated_embs_list, global_step, num_train_epochs, force_sync_upload=True)
746
+
747
+ logger.info("model saved.")
748
+
749
+
750
+ def setup_parser() -> argparse.ArgumentParser:
751
+ parser = argparse.ArgumentParser()
752
+
753
+ add_logging_arguments(parser)
754
+ train_util.add_sd_models_arguments(parser)
755
+ train_util.add_dataset_arguments(parser, True, True, False)
756
+ train_util.add_training_arguments(parser, True)
757
+ train_util.add_masked_loss_arguments(parser)
758
+ deepspeed_utils.add_deepspeed_arguments(parser)
759
+ train_util.add_optimizer_arguments(parser)
760
+ config_util.add_config_arguments(parser)
761
+ custom_train_functions.add_custom_train_arguments(parser, False)
762
+
763
+ parser.add_argument(
764
+ "--save_model_as",
765
+ type=str,
766
+ default="pt",
767
+ choices=[None, "ckpt", "pt", "safetensors"],
768
+ help="format to save the model (default is .pt) / モデル保存時の形式(デフォルトはpt)",
769
+ )
770
+
771
+ parser.add_argument(
772
+ "--weights", type=str, default=None, help="embedding weights to initialize / 学習するネットワークの初期重み"
773
+ )
774
+ parser.add_argument(
775
+ "--num_vectors_per_token", type=int, default=1, help="number of vectors per token / トークンに割り当てるembeddingsの要素数"
776
+ )
777
+ parser.add_argument(
778
+ "--token_string",
779
+ type=str,
780
+ default=None,
781
+ help="token string used in training, must not exist in tokenizer / 学習時に使用されるトークン文字列、tokenizerに存在しない文字であること",
782
+ )
783
+ parser.add_argument(
784
+ "--init_word", type=str, default=None, help="words to initialize vector / ベクトルを初期化に使用する単語、複数可"
785
+ )
786
+ parser.add_argument(
787
+ "--use_object_template",
788
+ action="store_true",
789
+ help="ignore caption and use default templates for object / キャプションは使わずデフォルトの物体用テンプレートで学習する",
790
+ )
791
+ parser.add_argument(
792
+ "--use_style_template",
793
+ action="store_true",
794
+ help="ignore caption and use default templates for stype / キャプションは使わずデフォルトのスタイル用テンプレートで学習する",
795
+ )
796
+ parser.add_argument(
797
+ "--no_half_vae",
798
+ action="store_true",
799
+ help="do not use fp16/bf16 VAE in mixed precision (use float VAE) / mixed precisionでも fp16/bf16 VAEを使わずfloat VAEを使う",
800
+ )
801
+
802
+ return parser
803
+
804
+
805
+ if __name__ == "__main__":
806
+ parser = setup_parser()
807
+
808
+ args = parser.parse_args()
809
+ train_util.verify_command_line_training_args(args)
810
+ args = train_util.read_config_from_file(args, parser)
811
+
812
+ trainer = TextualInversionTrainer()
813
+ trainer.train(args)