ACCC1380 commited on
Commit
1eb9457
1 Parent(s): 7d9d8cd

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

Browse files
lora-scripts/sd-scripts/sdxl_train_textual_inversion.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+
4
+ import regex
5
+
6
+ import torch
7
+ from library.device_utils import init_ipex
8
+ init_ipex()
9
+
10
+ from library import sdxl_model_util, sdxl_train_util, train_util
11
+
12
+ import train_textual_inversion
13
+
14
+
15
+ class SdxlTextualInversionTrainer(train_textual_inversion.TextualInversionTrainer):
16
+ def __init__(self):
17
+ super().__init__()
18
+ self.vae_scale_factor = sdxl_model_util.VAE_SCALE_FACTOR
19
+ self.is_sdxl = True
20
+
21
+ def assert_extra_args(self, args, train_dataset_group):
22
+ super().assert_extra_args(args, train_dataset_group)
23
+ sdxl_train_util.verify_sdxl_training_args(args, supportTextEncoderCaching=False)
24
+
25
+ train_dataset_group.verify_bucket_reso_steps(32)
26
+
27
+ def load_target_model(self, args, weight_dtype, accelerator):
28
+ (
29
+ load_stable_diffusion_format,
30
+ text_encoder1,
31
+ text_encoder2,
32
+ vae,
33
+ unet,
34
+ logit_scale,
35
+ ckpt_info,
36
+ ) = sdxl_train_util.load_target_model(args, accelerator, sdxl_model_util.MODEL_VERSION_SDXL_BASE_V1_0, weight_dtype)
37
+
38
+ self.load_stable_diffusion_format = load_stable_diffusion_format
39
+ self.logit_scale = logit_scale
40
+ self.ckpt_info = ckpt_info
41
+
42
+ return sdxl_model_util.MODEL_VERSION_SDXL_BASE_V1_0, [text_encoder1, text_encoder2], vae, unet
43
+
44
+ def load_tokenizer(self, args):
45
+ tokenizer = sdxl_train_util.load_tokenizers(args)
46
+ return tokenizer
47
+
48
+ def get_text_cond(self, args, accelerator, batch, tokenizers, text_encoders, weight_dtype):
49
+ input_ids1 = batch["input_ids"]
50
+ input_ids2 = batch["input_ids2"]
51
+ with torch.enable_grad():
52
+ input_ids1 = input_ids1.to(accelerator.device)
53
+ input_ids2 = input_ids2.to(accelerator.device)
54
+ encoder_hidden_states1, encoder_hidden_states2, pool2 = train_util.get_hidden_states_sdxl(
55
+ args.max_token_length,
56
+ input_ids1,
57
+ input_ids2,
58
+ tokenizers[0],
59
+ tokenizers[1],
60
+ text_encoders[0],
61
+ text_encoders[1],
62
+ None if not args.full_fp16 else weight_dtype,
63
+ accelerator=accelerator,
64
+ )
65
+ return encoder_hidden_states1, encoder_hidden_states2, pool2
66
+
67
+ def call_unet(self, args, accelerator, unet, noisy_latents, timesteps, text_conds, batch, weight_dtype):
68
+ noisy_latents = noisy_latents.to(weight_dtype) # TODO check why noisy_latents is not weight_dtype
69
+
70
+ # get size embeddings
71
+ orig_size = batch["original_sizes_hw"]
72
+ crop_size = batch["crop_top_lefts"]
73
+ target_size = batch["target_sizes_hw"]
74
+ embs = sdxl_train_util.get_size_embeddings(orig_size, crop_size, target_size, accelerator.device).to(weight_dtype)
75
+
76
+ # concat embeddings
77
+ encoder_hidden_states1, encoder_hidden_states2, pool2 = text_conds
78
+ vector_embedding = torch.cat([pool2, embs], dim=1).to(weight_dtype)
79
+ text_embedding = torch.cat([encoder_hidden_states1, encoder_hidden_states2], dim=2).to(weight_dtype)
80
+
81
+ noise_pred = unet(noisy_latents, timesteps, text_embedding, vector_embedding)
82
+ return noise_pred
83
+
84
+ def sample_images(self, accelerator, args, epoch, global_step, device, vae, tokenizer, text_encoder, unet, prompt_replacement):
85
+ sdxl_train_util.sample_images(
86
+ accelerator, args, epoch, global_step, device, vae, tokenizer, text_encoder, unet, prompt_replacement
87
+ )
88
+
89
+ def save_weights(self, file, updated_embs, save_dtype, metadata):
90
+ state_dict = {"clip_l": updated_embs[0], "clip_g": updated_embs[1]}
91
+
92
+ if save_dtype is not None:
93
+ for key in list(state_dict.keys()):
94
+ v = state_dict[key]
95
+ v = v.detach().clone().to("cpu").to(save_dtype)
96
+ state_dict[key] = v
97
+
98
+ if os.path.splitext(file)[1] == ".safetensors":
99
+ from safetensors.torch import save_file
100
+
101
+ save_file(state_dict, file, metadata)
102
+ else:
103
+ torch.save(state_dict, file)
104
+
105
+ def load_weights(self, file):
106
+ if os.path.splitext(file)[1] == ".safetensors":
107
+ from safetensors.torch import load_file
108
+
109
+ data = load_file(file)
110
+ else:
111
+ data = torch.load(file, map_location="cpu")
112
+
113
+ emb_l = data.get("clip_l", None) # ViT-L text encoder 1
114
+ emb_g = data.get("clip_g", None) # BiG-G text encoder 2
115
+
116
+ assert (
117
+ emb_l is not None or emb_g is not None
118
+ ), f"weight file does not contains weights for text encoder 1 or 2 / 重みファイルにテキストエンコーダー1または2の重みが含まれていません: {file}"
119
+
120
+ return [emb_l, emb_g]
121
+
122
+
123
+ def setup_parser() -> argparse.ArgumentParser:
124
+ parser = train_textual_inversion.setup_parser()
125
+ # don't add sdxl_train_util.add_sdxl_training_arguments(parser): because it only adds text encoder caching
126
+ # sdxl_train_util.add_sdxl_training_arguments(parser)
127
+ return parser
128
+
129
+
130
+ if __name__ == "__main__":
131
+ parser = setup_parser()
132
+
133
+ args = parser.parse_args()
134
+ train_util.verify_command_line_training_args(args)
135
+ args = train_util.read_config_from_file(args, parser)
136
+
137
+ trainer = SdxlTextualInversionTrainer()
138
+ trainer.train(args)