ACCC1380 commited on
Commit
3275521
1 Parent(s): ef07717

Upload lora-scripts/sd-scripts/tools/convert_diffusers20_original_sd.py with huggingface_hub

Browse files
lora-scripts/sd-scripts/tools/convert_diffusers20_original_sd.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # convert Diffusers v1.x/v2.0 model to original Stable Diffusion
2
+
3
+ import argparse
4
+ import os
5
+ import torch
6
+ from diffusers import StableDiffusionPipeline
7
+
8
+ import library.model_util as model_util
9
+ from library.utils import setup_logging
10
+ setup_logging()
11
+ import logging
12
+ logger = logging.getLogger(__name__)
13
+
14
+ def convert(args):
15
+ # 引数を確認する
16
+ load_dtype = torch.float16 if args.fp16 else None
17
+
18
+ save_dtype = None
19
+ if args.fp16 or args.save_precision_as == "fp16":
20
+ save_dtype = torch.float16
21
+ elif args.bf16 or args.save_precision_as == "bf16":
22
+ save_dtype = torch.bfloat16
23
+ elif args.float or args.save_precision_as == "float":
24
+ save_dtype = torch.float
25
+
26
+ is_load_ckpt = os.path.isfile(args.model_to_load)
27
+ is_save_ckpt = len(os.path.splitext(args.model_to_save)[1]) > 0
28
+
29
+ assert not is_load_ckpt or args.v1 != args.v2, "v1 or v2 is required to load checkpoint / checkpointの読み込みにはv1/v2指定が必要です"
30
+ # assert (
31
+ # is_save_ckpt or args.reference_model is not None
32
+ # ), f"reference model is required to save as Diffusers / Diffusers形式での保存には参照モデルが必要です"
33
+
34
+ # モデルを読み込む
35
+ msg = "checkpoint" if is_load_ckpt else ("Diffusers" + (" as fp16" if args.fp16 else ""))
36
+ logger.info(f"loading {msg}: {args.model_to_load}")
37
+
38
+ if is_load_ckpt:
39
+ v2_model = args.v2
40
+ text_encoder, vae, unet = model_util.load_models_from_stable_diffusion_checkpoint(
41
+ v2_model, args.model_to_load, unet_use_linear_projection_in_v2=args.unet_use_linear_projection
42
+ )
43
+ else:
44
+ pipe = StableDiffusionPipeline.from_pretrained(
45
+ args.model_to_load, torch_dtype=load_dtype, tokenizer=None, safety_checker=None, variant=args.variant
46
+ )
47
+ text_encoder = pipe.text_encoder
48
+ vae = pipe.vae
49
+ unet = pipe.unet
50
+
51
+ if args.v1 == args.v2:
52
+ # 自動判定する
53
+ v2_model = unet.config.cross_attention_dim == 1024
54
+ logger.info("checking model version: model is " + ("v2" if v2_model else "v1"))
55
+ else:
56
+ v2_model = not args.v1
57
+
58
+ # 変換して保存する
59
+ msg = ("checkpoint" + ("" if save_dtype is None else f" in {save_dtype}")) if is_save_ckpt else "Diffusers"
60
+ logger.info(f"converting and saving as {msg}: {args.model_to_save}")
61
+
62
+ if is_save_ckpt:
63
+ original_model = args.model_to_load if is_load_ckpt else None
64
+ key_count = model_util.save_stable_diffusion_checkpoint(
65
+ v2_model,
66
+ args.model_to_save,
67
+ text_encoder,
68
+ unet,
69
+ original_model,
70
+ args.epoch,
71
+ args.global_step,
72
+ None if args.metadata is None else eval(args.metadata),
73
+ save_dtype=save_dtype,
74
+ vae=vae,
75
+ )
76
+ logger.info(f"model saved. total converted state_dict keys: {key_count}")
77
+ else:
78
+ logger.info(
79
+ f"copy scheduler/tokenizer config from: {args.reference_model if args.reference_model is not None else 'default model'}"
80
+ )
81
+ model_util.save_diffusers_checkpoint(
82
+ v2_model, args.model_to_save, text_encoder, unet, args.reference_model, vae, args.use_safetensors
83
+ )
84
+ logger.info("model saved.")
85
+
86
+
87
+ def setup_parser() -> argparse.ArgumentParser:
88
+ parser = argparse.ArgumentParser()
89
+ parser.add_argument(
90
+ "--v1", action="store_true", help="load v1.x model (v1 or v2 is required to load checkpoint) / 1.xのモデルを読み込む"
91
+ )
92
+ parser.add_argument(
93
+ "--v2", action="store_true", help="load v2.0 model (v1 or v2 is required to load checkpoint) / 2.0のモデルを読み込む"
94
+ )
95
+ parser.add_argument(
96
+ "--unet_use_linear_projection",
97
+ action="store_true",
98
+ help="When saving v2 model as Diffusers, set U-Net config to `use_linear_projection=true` (to match stabilityai's model) / Diffusers形式でv2モデルを保存するときにU-Netの設定を`use_linear_projection=true`にする(stabilityaiのモデルと合わせる)",
99
+ )
100
+ parser.add_argument(
101
+ "--fp16",
102
+ action="store_true",
103
+ help="load as fp16 (Diffusers only) and save as fp16 (checkpoint only) / fp16形式で読み込み(Diffusers形式のみ対応)、保存する(checkpointのみ対応)",
104
+ )
105
+ parser.add_argument("--bf16", action="store_true", help="save as bf16 (checkpoint only) / bf16形式で保存する(checkpointのみ対応)")
106
+ parser.add_argument(
107
+ "--float", action="store_true", help="save as float (checkpoint only) / float(float32)形式で保存する(checkpointのみ対応)"
108
+ )
109
+ parser.add_argument(
110
+ "--save_precision_as",
111
+ type=str,
112
+ default="no",
113
+ choices=["fp16", "bf16", "float"],
114
+ help="save precision, do not specify with --fp16/--bf16/--float / 保存する精度、--fp16/--bf16/--floatと併用しないでくださ���",
115
+ )
116
+ parser.add_argument("--epoch", type=int, default=0, help="epoch to write to checkpoint / checkpointに記録するepoch数の値")
117
+ parser.add_argument(
118
+ "--global_step", type=int, default=0, help="global_step to write to checkpoint / checkpointに記録するglobal_stepの値"
119
+ )
120
+ parser.add_argument(
121
+ "--metadata",
122
+ type=str,
123
+ default=None,
124
+ help='モデルに保存されるメタデータ、Pythonの辞書形式で指定 / metadata: metadata written in to the model in Python Dictionary. Example metadata: \'{"name": "model_name", "resolution": "512x512"}\'',
125
+ )
126
+ parser.add_argument(
127
+ "--variant",
128
+ type=str,
129
+ default=None,
130
+ help="読む込むDiffusersのvariantを指定する、例: fp16 / variant: Diffusers variant to load. Example: fp16",
131
+ )
132
+ parser.add_argument(
133
+ "--reference_model",
134
+ type=str,
135
+ default=None,
136
+ help="scheduler/tokenizerのコピー元Diffusersモデル、Diffusers形式で保存するときに使用される、省略時は`runwayml/stable-diffusion-v1-5` または `stabilityai/stable-diffusion-2-1` / reference Diffusers model to copy scheduler/tokenizer config from, used when saving as Diffusers format, default is `runwayml/stable-diffusion-v1-5` or `stabilityai/stable-diffusion-2-1`",
137
+ )
138
+ parser.add_argument(
139
+ "--use_safetensors",
140
+ action="store_true",
141
+ help="use safetensors format to save Diffusers model (checkpoint depends on the file extension) / Duffusersモデルをsafetensors形式で保存する(checkpointは拡張子で自動判定)",
142
+ )
143
+
144
+ parser.add_argument(
145
+ "model_to_load",
146
+ type=str,
147
+ default=None,
148
+ help="model to load: checkpoint file or Diffusers model's directory / 読み込むモデル、checkpointかDiffusers形式モデルのディレクトリ",
149
+ )
150
+ parser.add_argument(
151
+ "model_to_save",
152
+ type=str,
153
+ default=None,
154
+ help="model to save: checkpoint (with extension) or Diffusers model's directory (without extension) / 変換後のモデル、拡張子がある場合はcheckpoint、ない場合はDiffusesモデルとして保存",
155
+ )
156
+ return parser
157
+
158
+
159
+ if __name__ == "__main__":
160
+ parser = setup_parser()
161
+
162
+ args = parser.parse_args()
163
+ convert(args)