ACCC1380 commited on
Commit
b2eaa78
1 Parent(s): 99f5c2e

Upload lora-scripts/sd-scripts/library/sdxl_train_util.py with huggingface_hub

Browse files
lora-scripts/sd-scripts/library/sdxl_train_util.py ADDED
@@ -0,0 +1,372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import math
3
+ import os
4
+ from typing import Optional
5
+
6
+ import torch
7
+ from library.device_utils import init_ipex, clean_memory_on_device
8
+ init_ipex()
9
+
10
+ from accelerate import init_empty_weights
11
+ from tqdm import tqdm
12
+ from transformers import CLIPTokenizer
13
+ from library import model_util, sdxl_model_util, train_util, sdxl_original_unet
14
+ from library.sdxl_lpw_stable_diffusion import SdxlStableDiffusionLongPromptWeightingPipeline
15
+ from .utils import setup_logging
16
+ setup_logging()
17
+ import logging
18
+ logger = logging.getLogger(__name__)
19
+
20
+ TOKENIZER1_PATH = "openai/clip-vit-large-patch14"
21
+ TOKENIZER2_PATH = "laion/CLIP-ViT-bigG-14-laion2B-39B-b160k"
22
+
23
+ # DEFAULT_NOISE_OFFSET = 0.0357
24
+
25
+
26
+ def load_target_model(args, accelerator, model_version: str, weight_dtype):
27
+ model_dtype = match_mixed_precision(args, weight_dtype) # prepare fp16/bf16
28
+ for pi in range(accelerator.state.num_processes):
29
+ if pi == accelerator.state.local_process_index:
30
+ logger.info(f"loading model for process {accelerator.state.local_process_index}/{accelerator.state.num_processes}")
31
+
32
+ (
33
+ load_stable_diffusion_format,
34
+ text_encoder1,
35
+ text_encoder2,
36
+ vae,
37
+ unet,
38
+ logit_scale,
39
+ ckpt_info,
40
+ ) = _load_target_model(
41
+ args.pretrained_model_name_or_path,
42
+ args.vae,
43
+ model_version,
44
+ weight_dtype,
45
+ accelerator.device if args.lowram else "cpu",
46
+ model_dtype,
47
+ )
48
+
49
+ # work on low-ram device
50
+ if args.lowram:
51
+ text_encoder1.to(accelerator.device)
52
+ text_encoder2.to(accelerator.device)
53
+ unet.to(accelerator.device)
54
+ vae.to(accelerator.device)
55
+
56
+ clean_memory_on_device(accelerator.device)
57
+ accelerator.wait_for_everyone()
58
+
59
+ return load_stable_diffusion_format, text_encoder1, text_encoder2, vae, unet, logit_scale, ckpt_info
60
+
61
+
62
+ def _load_target_model(
63
+ name_or_path: str, vae_path: Optional[str], model_version: str, weight_dtype, device="cpu", model_dtype=None
64
+ ):
65
+ # model_dtype only work with full fp16/bf16
66
+ name_or_path = os.readlink(name_or_path) if os.path.islink(name_or_path) else name_or_path
67
+ load_stable_diffusion_format = os.path.isfile(name_or_path) # determine SD or Diffusers
68
+
69
+ if load_stable_diffusion_format:
70
+ logger.info(f"load StableDiffusion checkpoint: {name_or_path}")
71
+ (
72
+ text_encoder1,
73
+ text_encoder2,
74
+ vae,
75
+ unet,
76
+ logit_scale,
77
+ ckpt_info,
78
+ ) = sdxl_model_util.load_models_from_sdxl_checkpoint(model_version, name_or_path, device, model_dtype)
79
+ else:
80
+ # Diffusers model is loaded to CPU
81
+ from diffusers import StableDiffusionXLPipeline
82
+
83
+ variant = "fp16" if weight_dtype == torch.float16 else None
84
+ logger.info(f"load Diffusers pretrained models: {name_or_path}, variant={variant}")
85
+ try:
86
+ try:
87
+ pipe = StableDiffusionXLPipeline.from_pretrained(
88
+ name_or_path, torch_dtype=model_dtype, variant=variant, tokenizer=None
89
+ )
90
+ except EnvironmentError as ex:
91
+ if variant is not None:
92
+ logger.info("try to load fp32 model")
93
+ pipe = StableDiffusionXLPipeline.from_pretrained(name_or_path, variant=None, tokenizer=None)
94
+ else:
95
+ raise ex
96
+ except EnvironmentError as ex:
97
+ logger.error(
98
+ f"model is not found as a file or in Hugging Face, perhaps file name is wrong? / 指定したモデル名のファイル、またはHugging Faceのモデルが見つかりません。ファイル名が誤っているかもしれません: {name_or_path}"
99
+ )
100
+ raise ex
101
+
102
+ text_encoder1 = pipe.text_encoder
103
+ text_encoder2 = pipe.text_encoder_2
104
+
105
+ # convert to fp32 for cache text_encoders outputs
106
+ if text_encoder1.dtype != torch.float32:
107
+ text_encoder1 = text_encoder1.to(dtype=torch.float32)
108
+ if text_encoder2.dtype != torch.float32:
109
+ text_encoder2 = text_encoder2.to(dtype=torch.float32)
110
+
111
+ vae = pipe.vae
112
+ unet = pipe.unet
113
+ del pipe
114
+
115
+ # Diffusers U-Net to original U-Net
116
+ state_dict = sdxl_model_util.convert_diffusers_unet_state_dict_to_sdxl(unet.state_dict())
117
+ with init_empty_weights():
118
+ unet = sdxl_original_unet.SdxlUNet2DConditionModel() # overwrite unet
119
+ sdxl_model_util._load_state_dict_on_device(unet, state_dict, device=device, dtype=model_dtype)
120
+ logger.info("U-Net converted to original U-Net")
121
+
122
+ logit_scale = None
123
+ ckpt_info = None
124
+
125
+ # VAEを読み込む
126
+ if vae_path is not None:
127
+ vae = model_util.load_vae(vae_path, weight_dtype)
128
+ logger.info("additional VAE loaded")
129
+
130
+ return load_stable_diffusion_format, text_encoder1, text_encoder2, vae, unet, logit_scale, ckpt_info
131
+
132
+
133
+ def load_tokenizers(args: argparse.Namespace):
134
+ logger.info("prepare tokenizers")
135
+
136
+ original_paths = [TOKENIZER1_PATH, TOKENIZER2_PATH]
137
+ tokeniers = []
138
+ for i, original_path in enumerate(original_paths):
139
+ tokenizer: CLIPTokenizer = None
140
+ if args.tokenizer_cache_dir:
141
+ local_tokenizer_path = os.path.join(args.tokenizer_cache_dir, original_path.replace("/", "_"))
142
+ if os.path.exists(local_tokenizer_path):
143
+ logger.info(f"load tokenizer from cache: {local_tokenizer_path}")
144
+ tokenizer = CLIPTokenizer.from_pretrained(local_tokenizer_path)
145
+
146
+ if tokenizer is None:
147
+ tokenizer = CLIPTokenizer.from_pretrained(original_path)
148
+
149
+ if args.tokenizer_cache_dir and not os.path.exists(local_tokenizer_path):
150
+ logger.info(f"save Tokenizer to cache: {local_tokenizer_path}")
151
+ tokenizer.save_pretrained(local_tokenizer_path)
152
+
153
+ if i == 1:
154
+ tokenizer.pad_token_id = 0 # fix pad token id to make same as open clip tokenizer
155
+
156
+ tokeniers.append(tokenizer)
157
+
158
+ if hasattr(args, "max_token_length") and args.max_token_length is not None:
159
+ logger.info(f"update token length: {args.max_token_length}")
160
+
161
+ return tokeniers
162
+
163
+
164
+ def match_mixed_precision(args, weight_dtype):
165
+ if args.full_fp16:
166
+ assert (
167
+ weight_dtype == torch.float16
168
+ ), "full_fp16 requires mixed precision='fp16' / full_fp16を使う場合はmixed_precision='fp16'を指定してください。"
169
+ return weight_dtype
170
+ elif args.full_bf16:
171
+ assert (
172
+ weight_dtype == torch.bfloat16
173
+ ), "full_bf16 requires mixed precision='bf16' / full_bf16を使う場合はmixed_precision='bf16'を指定してください。"
174
+ return weight_dtype
175
+ else:
176
+ return None
177
+
178
+
179
+ def timestep_embedding(timesteps, dim, max_period=10000):
180
+ """
181
+ Create sinusoidal timestep embeddings.
182
+ :param timesteps: a 1-D Tensor of N indices, one per batch element.
183
+ These may be fractional.
184
+ :param dim: the dimension of the output.
185
+ :param max_period: controls the minimum frequency of the embeddings.
186
+ :return: an [N x dim] Tensor of positional embeddings.
187
+ """
188
+ half = dim // 2
189
+ freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to(
190
+ device=timesteps.device
191
+ )
192
+ args = timesteps[:, None].float() * freqs[None]
193
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
194
+ if dim % 2:
195
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
196
+ return embedding
197
+
198
+
199
+ def get_timestep_embedding(x, outdim):
200
+ assert len(x.shape) == 2
201
+ b, dims = x.shape[0], x.shape[1]
202
+ x = torch.flatten(x)
203
+ emb = timestep_embedding(x, outdim)
204
+ emb = torch.reshape(emb, (b, dims * outdim))
205
+ return emb
206
+
207
+
208
+ def get_size_embeddings(orig_size, crop_size, target_size, device):
209
+ emb1 = get_timestep_embedding(orig_size, 256)
210
+ emb2 = get_timestep_embedding(crop_size, 256)
211
+ emb3 = get_timestep_embedding(target_size, 256)
212
+ vector = torch.cat([emb1, emb2, emb3], dim=1).to(device)
213
+ return vector
214
+
215
+
216
+ def save_sd_model_on_train_end(
217
+ args: argparse.Namespace,
218
+ src_path: str,
219
+ save_stable_diffusion_format: bool,
220
+ use_safetensors: bool,
221
+ save_dtype: torch.dtype,
222
+ epoch: int,
223
+ global_step: int,
224
+ text_encoder1,
225
+ text_encoder2,
226
+ unet,
227
+ vae,
228
+ logit_scale,
229
+ ckpt_info,
230
+ ):
231
+ def sd_saver(ckpt_file, epoch_no, global_step):
232
+ sai_metadata = train_util.get_sai_model_spec(None, args, True, False, False, is_stable_diffusion_ckpt=True)
233
+ sdxl_model_util.save_stable_diffusion_checkpoint(
234
+ ckpt_file,
235
+ text_encoder1,
236
+ text_encoder2,
237
+ unet,
238
+ epoch_no,
239
+ global_step,
240
+ ckpt_info,
241
+ vae,
242
+ logit_scale,
243
+ sai_metadata,
244
+ save_dtype,
245
+ )
246
+
247
+ def diffusers_saver(out_dir):
248
+ sdxl_model_util.save_diffusers_checkpoint(
249
+ out_dir,
250
+ text_encoder1,
251
+ text_encoder2,
252
+ unet,
253
+ src_path,
254
+ vae,
255
+ use_safetensors=use_safetensors,
256
+ save_dtype=save_dtype,
257
+ )
258
+
259
+ train_util.save_sd_model_on_train_end_common(
260
+ args, save_stable_diffusion_format, use_safetensors, epoch, global_step, sd_saver, diffusers_saver
261
+ )
262
+
263
+
264
+ # epochとstepの保存、メタデータにepoch/stepが含まれ引数が同じになるため、統合している
265
+ # on_epoch_end: Trueならepoch終了時、Falseならstep経過時
266
+ def save_sd_model_on_epoch_end_or_stepwise(
267
+ args: argparse.Namespace,
268
+ on_epoch_end: bool,
269
+ accelerator,
270
+ src_path,
271
+ save_stable_diffusion_format: bool,
272
+ use_safetensors: bool,
273
+ save_dtype: torch.dtype,
274
+ epoch: int,
275
+ num_train_epochs: int,
276
+ global_step: int,
277
+ text_encoder1,
278
+ text_encoder2,
279
+ unet,
280
+ vae,
281
+ logit_scale,
282
+ ckpt_info,
283
+ ):
284
+ def sd_saver(ckpt_file, epoch_no, global_step):
285
+ sai_metadata = train_util.get_sai_model_spec(None, args, True, False, False, is_stable_diffusion_ckpt=True)
286
+ sdxl_model_util.save_stable_diffusion_checkpoint(
287
+ ckpt_file,
288
+ text_encoder1,
289
+ text_encoder2,
290
+ unet,
291
+ epoch_no,
292
+ global_step,
293
+ ckpt_info,
294
+ vae,
295
+ logit_scale,
296
+ sai_metadata,
297
+ save_dtype,
298
+ )
299
+
300
+ def diffusers_saver(out_dir):
301
+ sdxl_model_util.save_diffusers_checkpoint(
302
+ out_dir,
303
+ text_encoder1,
304
+ text_encoder2,
305
+ unet,
306
+ src_path,
307
+ vae,
308
+ use_safetensors=use_safetensors,
309
+ save_dtype=save_dtype,
310
+ )
311
+
312
+ train_util.save_sd_model_on_epoch_end_or_stepwise_common(
313
+ args,
314
+ on_epoch_end,
315
+ accelerator,
316
+ save_stable_diffusion_format,
317
+ use_safetensors,
318
+ epoch,
319
+ num_train_epochs,
320
+ global_step,
321
+ sd_saver,
322
+ diffusers_saver,
323
+ )
324
+
325
+
326
+ def add_sdxl_training_arguments(parser: argparse.ArgumentParser):
327
+ parser.add_argument(
328
+ "--cache_text_encoder_outputs", action="store_true", help="cache text encoder outputs / text encoderの出力をキャッシュする"
329
+ )
330
+ parser.add_argument(
331
+ "--cache_text_encoder_outputs_to_disk",
332
+ action="store_true",
333
+ help="cache text encoder outputs to disk / text encoderの出力をディスクにキャッシュする",
334
+ )
335
+
336
+
337
+ def verify_sdxl_training_args(args: argparse.Namespace, supportTextEncoderCaching: bool = True):
338
+ assert not args.v2, "v2 cannot be enabled in SDXL training / SDXL学習ではv2を有効にすることはできません"
339
+ if args.v_parameterization:
340
+ logger.warning("v_parameterization will be unexpected / SDXL学習ではv_parameterizationは想定外の動作になります")
341
+
342
+ if args.clip_skip is not None:
343
+ logger.warning("clip_skip will be unexpected / SDXL学習ではclip_skipは動作しません")
344
+
345
+ # if args.multires_noise_iterations:
346
+ # logger.info(
347
+ # f"Warning: SDXL has been trained with noise_offset={DEFAULT_NOISE_OFFSET}, but noise_offset is disabled due to multires_noise_iterations / SDXLはnoise_offset={DEFAULT_NOISE_OFFSET}で学習されていますが、multires_noise_iterationsが有効になっているためnoise_offsetは無効になります"
348
+ # )
349
+ # else:
350
+ # if args.noise_offset is None:
351
+ # args.noise_offset = DEFAULT_NOISE_OFFSET
352
+ # elif args.noise_offset != DEFAULT_NOISE_OFFSET:
353
+ # logger.info(
354
+ # f"Warning: SDXL has been trained with noise_offset={DEFAULT_NOISE_OFFSET} / SDXLはnoise_offset={DEFAULT_NOISE_OFFSET}で学習されています"
355
+ # )
356
+ # logger.info(f"noise_offset is set to {args.noise_offset} / noise_offsetが{args.noise_offset}に設定されました")
357
+
358
+ assert (
359
+ not hasattr(args, "weighted_captions") or not args.weighted_captions
360
+ ), "weighted_captions cannot be enabled in SDXL training currently / SDXL学習では今のところweighted_captionsを有効にすることはできません"
361
+
362
+ if supportTextEncoderCaching:
363
+ if args.cache_text_encoder_outputs_to_disk and not args.cache_text_encoder_outputs:
364
+ args.cache_text_encoder_outputs = True
365
+ logger.warning(
366
+ "cache_text_encoder_outputs is enabled because cache_text_encoder_outputs_to_disk is enabled / "
367
+ + "cache_text_encoder_outputs_to_diskが有効になっているためcache_text_encoder_outputsが有効になりました"
368
+ )
369
+
370
+
371
+ def sample_images(*args, **kwargs):
372
+ return train_util.sample_images_common(SdxlStableDiffusionLongPromptWeightingPipeline, *args, **kwargs)