Upload lora-scripts/sd-scripts/sdxl_train_network.py with huggingface_hub
Browse files
lora-scripts/sd-scripts/sdxl_train_network.py
ADDED
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
|
3 |
+
import torch
|
4 |
+
from library.device_utils import init_ipex, clean_memory_on_device
|
5 |
+
init_ipex()
|
6 |
+
|
7 |
+
from library import sdxl_model_util, sdxl_train_util, train_util
|
8 |
+
import train_network
|
9 |
+
from library.utils import setup_logging
|
10 |
+
setup_logging()
|
11 |
+
import logging
|
12 |
+
logger = logging.getLogger(__name__)
|
13 |
+
|
14 |
+
class SdxlNetworkTrainer(train_network.NetworkTrainer):
|
15 |
+
def __init__(self):
|
16 |
+
super().__init__()
|
17 |
+
self.vae_scale_factor = sdxl_model_util.VAE_SCALE_FACTOR
|
18 |
+
self.is_sdxl = True
|
19 |
+
|
20 |
+
def assert_extra_args(self, args, train_dataset_group):
|
21 |
+
super().assert_extra_args(args, train_dataset_group)
|
22 |
+
sdxl_train_util.verify_sdxl_training_args(args)
|
23 |
+
|
24 |
+
if args.cache_text_encoder_outputs:
|
25 |
+
assert (
|
26 |
+
train_dataset_group.is_text_encoder_output_cacheable()
|
27 |
+
), "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は使えません"
|
28 |
+
|
29 |
+
assert (
|
30 |
+
args.network_train_unet_only or not args.cache_text_encoder_outputs
|
31 |
+
), "network for Text Encoder cannot be trained with caching Text Encoder outputs / Text Encoderの出力をキャッシュしながらText Encoderのネットワークを学習することはできません"
|
32 |
+
|
33 |
+
train_dataset_group.verify_bucket_reso_steps(32)
|
34 |
+
|
35 |
+
def load_target_model(self, args, weight_dtype, accelerator):
|
36 |
+
(
|
37 |
+
load_stable_diffusion_format,
|
38 |
+
text_encoder1,
|
39 |
+
text_encoder2,
|
40 |
+
vae,
|
41 |
+
unet,
|
42 |
+
logit_scale,
|
43 |
+
ckpt_info,
|
44 |
+
) = sdxl_train_util.load_target_model(args, accelerator, sdxl_model_util.MODEL_VERSION_SDXL_BASE_V1_0, weight_dtype)
|
45 |
+
|
46 |
+
self.load_stable_diffusion_format = load_stable_diffusion_format
|
47 |
+
self.logit_scale = logit_scale
|
48 |
+
self.ckpt_info = ckpt_info
|
49 |
+
|
50 |
+
return sdxl_model_util.MODEL_VERSION_SDXL_BASE_V1_0, [text_encoder1, text_encoder2], vae, unet
|
51 |
+
|
52 |
+
def load_tokenizer(self, args):
|
53 |
+
tokenizer = sdxl_train_util.load_tokenizers(args)
|
54 |
+
return tokenizer
|
55 |
+
|
56 |
+
def is_text_encoder_outputs_cached(self, args):
|
57 |
+
return args.cache_text_encoder_outputs
|
58 |
+
|
59 |
+
def cache_text_encoder_outputs_if_needed(
|
60 |
+
self, args, accelerator, unet, vae, tokenizers, text_encoders, dataset: train_util.DatasetGroup, weight_dtype
|
61 |
+
):
|
62 |
+
if args.cache_text_encoder_outputs:
|
63 |
+
if not args.lowram:
|
64 |
+
# メモリ消費を減らす
|
65 |
+
logger.info("move vae and unet to cpu to save memory")
|
66 |
+
org_vae_device = vae.device
|
67 |
+
org_unet_device = unet.device
|
68 |
+
vae.to("cpu")
|
69 |
+
unet.to("cpu")
|
70 |
+
clean_memory_on_device(accelerator.device)
|
71 |
+
|
72 |
+
# When TE is not be trained, it will not be prepared so we need to use explicit autocast
|
73 |
+
with accelerator.autocast():
|
74 |
+
dataset.cache_text_encoder_outputs(
|
75 |
+
tokenizers,
|
76 |
+
text_encoders,
|
77 |
+
accelerator.device,
|
78 |
+
weight_dtype,
|
79 |
+
args.cache_text_encoder_outputs_to_disk,
|
80 |
+
accelerator.is_main_process,
|
81 |
+
)
|
82 |
+
|
83 |
+
text_encoders[0].to("cpu", dtype=torch.float32) # Text Encoder doesn't work with fp16 on CPU
|
84 |
+
text_encoders[1].to("cpu", dtype=torch.float32)
|
85 |
+
clean_memory_on_device(accelerator.device)
|
86 |
+
|
87 |
+
if not args.lowram:
|
88 |
+
logger.info("move vae and unet back to original device")
|
89 |
+
vae.to(org_vae_device)
|
90 |
+
unet.to(org_unet_device)
|
91 |
+
else:
|
92 |
+
# Text Encoderから毎回出力を取得するので、GPUに乗せておく
|
93 |
+
text_encoders[0].to(accelerator.device, dtype=weight_dtype)
|
94 |
+
text_encoders[1].to(accelerator.device, dtype=weight_dtype)
|
95 |
+
|
96 |
+
def get_text_cond(self, args, accelerator, batch, tokenizers, text_encoders, weight_dtype):
|
97 |
+
if "text_encoder_outputs1_list" not in batch or batch["text_encoder_outputs1_list"] is None:
|
98 |
+
input_ids1 = batch["input_ids"]
|
99 |
+
input_ids2 = batch["input_ids2"]
|
100 |
+
with torch.enable_grad():
|
101 |
+
# Get the text embedding for conditioning
|
102 |
+
# TODO support weighted captions
|
103 |
+
# if args.weighted_captions:
|
104 |
+
# encoder_hidden_states = get_weighted_text_embeddings(
|
105 |
+
# tokenizer,
|
106 |
+
# text_encoder,
|
107 |
+
# batch["captions"],
|
108 |
+
# accelerator.device,
|
109 |
+
# args.max_token_length // 75 if args.max_token_length else 1,
|
110 |
+
# clip_skip=args.clip_skip,
|
111 |
+
# )
|
112 |
+
# else:
|
113 |
+
input_ids1 = input_ids1.to(accelerator.device)
|
114 |
+
input_ids2 = input_ids2.to(accelerator.device)
|
115 |
+
encoder_hidden_states1, encoder_hidden_states2, pool2 = train_util.get_hidden_states_sdxl(
|
116 |
+
args.max_token_length,
|
117 |
+
input_ids1,
|
118 |
+
input_ids2,
|
119 |
+
tokenizers[0],
|
120 |
+
tokenizers[1],
|
121 |
+
text_encoders[0],
|
122 |
+
text_encoders[1],
|
123 |
+
None if not args.full_fp16 else weight_dtype,
|
124 |
+
accelerator=accelerator,
|
125 |
+
)
|
126 |
+
else:
|
127 |
+
encoder_hidden_states1 = batch["text_encoder_outputs1_list"].to(accelerator.device).to(weight_dtype)
|
128 |
+
encoder_hidden_states2 = batch["text_encoder_outputs2_list"].to(accelerator.device).to(weight_dtype)
|
129 |
+
pool2 = batch["text_encoder_pool2_list"].to(accelerator.device).to(weight_dtype)
|
130 |
+
|
131 |
+
# # verify that the text encoder outputs are correct
|
132 |
+
# ehs1, ehs2, p2 = train_util.get_hidden_states_sdxl(
|
133 |
+
# args.max_token_length,
|
134 |
+
# batch["input_ids"].to(text_encoders[0].device),
|
135 |
+
# batch["input_ids2"].to(text_encoders[0].device),
|
136 |
+
# tokenizers[0],
|
137 |
+
# tokenizers[1],
|
138 |
+
# text_encoders[0],
|
139 |
+
# text_encoders[1],
|
140 |
+
# None if not args.full_fp16 else weight_dtype,
|
141 |
+
# )
|
142 |
+
# b_size = encoder_hidden_states1.shape[0]
|
143 |
+
# assert ((encoder_hidden_states1.to("cpu") - ehs1.to(dtype=weight_dtype)).abs().max() > 1e-2).sum() <= b_size * 2
|
144 |
+
# assert ((encoder_hidden_states2.to("cpu") - ehs2.to(dtype=weight_dtype)).abs().max() > 1e-2).sum() <= b_size * 2
|
145 |
+
# assert ((pool2.to("cpu") - p2.to(dtype=weight_dtype)).abs().max() > 1e-2).sum() <= b_size * 2
|
146 |
+
# logger.info("text encoder outputs verified")
|
147 |
+
|
148 |
+
return encoder_hidden_states1, encoder_hidden_states2, pool2
|
149 |
+
|
150 |
+
def call_unet(self, args, accelerator, unet, noisy_latents, timesteps, text_conds, batch, weight_dtype):
|
151 |
+
noisy_latents = noisy_latents.to(weight_dtype) # TODO check why noisy_latents is not weight_dtype
|
152 |
+
|
153 |
+
# get size embeddings
|
154 |
+
orig_size = batch["original_sizes_hw"]
|
155 |
+
crop_size = batch["crop_top_lefts"]
|
156 |
+
target_size = batch["target_sizes_hw"]
|
157 |
+
embs = sdxl_train_util.get_size_embeddings(orig_size, crop_size, target_size, accelerator.device).to(weight_dtype)
|
158 |
+
|
159 |
+
# concat embeddings
|
160 |
+
encoder_hidden_states1, encoder_hidden_states2, pool2 = text_conds
|
161 |
+
vector_embedding = torch.cat([pool2, embs], dim=1).to(weight_dtype)
|
162 |
+
text_embedding = torch.cat([encoder_hidden_states1, encoder_hidden_states2], dim=2).to(weight_dtype)
|
163 |
+
|
164 |
+
noise_pred = unet(noisy_latents, timesteps, text_embedding, vector_embedding)
|
165 |
+
return noise_pred
|
166 |
+
|
167 |
+
def sample_images(self, accelerator, args, epoch, global_step, device, vae, tokenizer, text_encoder, unet):
|
168 |
+
sdxl_train_util.sample_images(accelerator, args, epoch, global_step, device, vae, tokenizer, text_encoder, unet)
|
169 |
+
|
170 |
+
|
171 |
+
def setup_parser() -> argparse.ArgumentParser:
|
172 |
+
parser = train_network.setup_parser()
|
173 |
+
sdxl_train_util.add_sdxl_training_arguments(parser)
|
174 |
+
return parser
|
175 |
+
|
176 |
+
|
177 |
+
if __name__ == "__main__":
|
178 |
+
parser = setup_parser()
|
179 |
+
|
180 |
+
args = parser.parse_args()
|
181 |
+
train_util.verify_command_line_training_args(args)
|
182 |
+
args = train_util.read_config_from_file(args, parser)
|
183 |
+
|
184 |
+
trainer = SdxlNetworkTrainer()
|
185 |
+
trainer.train(args)
|