ACCC1380 commited on
Commit
07b7d37
1 Parent(s): 479e33f

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

Browse files
lora-scripts/sd-scripts/tools/merge_models.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+
4
+ import torch
5
+ from safetensors import safe_open
6
+ from safetensors.torch import load_file, save_file
7
+ from tqdm import tqdm
8
+ from library.utils import setup_logging
9
+ setup_logging()
10
+ import logging
11
+ logger = logging.getLogger(__name__)
12
+
13
+ def is_unet_key(key):
14
+ # VAE or TextEncoder, the last one is for SDXL
15
+ return not ("first_stage_model" in key or "cond_stage_model" in key or "conditioner." in key)
16
+
17
+
18
+ TEXT_ENCODER_KEY_REPLACEMENTS = [
19
+ ("cond_stage_model.transformer.embeddings.", "cond_stage_model.transformer.text_model.embeddings."),
20
+ ("cond_stage_model.transformer.encoder.", "cond_stage_model.transformer.text_model.encoder."),
21
+ ("cond_stage_model.transformer.final_layer_norm.", "cond_stage_model.transformer.text_model.final_layer_norm."),
22
+ ]
23
+
24
+
25
+ # support for models with different text encoder keys
26
+ def replace_text_encoder_key(key):
27
+ for rep_from, rep_to in TEXT_ENCODER_KEY_REPLACEMENTS:
28
+ if key.startswith(rep_from):
29
+ return True, rep_to + key[len(rep_from) :]
30
+ return False, key
31
+
32
+
33
+ def merge(args):
34
+ if args.precision == "fp16":
35
+ dtype = torch.float16
36
+ elif args.precision == "bf16":
37
+ dtype = torch.bfloat16
38
+ else:
39
+ dtype = torch.float
40
+
41
+ if args.saving_precision == "fp16":
42
+ save_dtype = torch.float16
43
+ elif args.saving_precision == "bf16":
44
+ save_dtype = torch.bfloat16
45
+ else:
46
+ save_dtype = torch.float
47
+
48
+ # check if all models are safetensors
49
+ for model in args.models:
50
+ if not model.endswith("safetensors"):
51
+ logger.info(f"Model {model} is not a safetensors model")
52
+ exit()
53
+ if not os.path.isfile(model):
54
+ logger.info(f"Model {model} does not exist")
55
+ exit()
56
+
57
+ assert args.ratios is None or len(args.models) == len(args.ratios), "ratios must be the same length as models"
58
+
59
+ # load and merge
60
+ ratio = 1.0 / len(args.models) # default
61
+ supplementary_key_ratios = {} # [key] = ratio, for keys not in all models, add later
62
+
63
+ merged_sd = None
64
+ first_model_keys = set() # check missing keys in other models
65
+ for i, model in enumerate(args.models):
66
+ if args.ratios is not None:
67
+ ratio = args.ratios[i]
68
+
69
+ if merged_sd is None:
70
+ # load first model
71
+ logger.info(f"Loading model {model}, ratio = {ratio}...")
72
+ merged_sd = {}
73
+ with safe_open(model, framework="pt", device=args.device) as f:
74
+ for key in tqdm(f.keys()):
75
+ value = f.get_tensor(key)
76
+ _, key = replace_text_encoder_key(key)
77
+
78
+ first_model_keys.add(key)
79
+
80
+ if not is_unet_key(key) and args.unet_only:
81
+ supplementary_key_ratios[key] = 1.0 # use first model's value for VAE or TextEncoder
82
+ continue
83
+
84
+ value = ratio * value.to(dtype) # first model's value * ratio
85
+ merged_sd[key] = value
86
+
87
+ logger.info(f"Model has {len(merged_sd)} keys " + ("(UNet only)" if args.unet_only else ""))
88
+ continue
89
+
90
+ # load other models
91
+ logger.info(f"Loading model {model}, ratio = {ratio}...")
92
+
93
+ with safe_open(model, framework="pt", device=args.device) as f:
94
+ model_keys = f.keys()
95
+ for key in tqdm(model_keys):
96
+ _, new_key = replace_text_encoder_key(key)
97
+ if new_key not in merged_sd:
98
+ if args.show_skipped and new_key not in first_model_keys:
99
+ logger.info(f"Skip: {new_key}")
100
+ continue
101
+
102
+ value = f.get_tensor(key)
103
+ merged_sd[new_key] = merged_sd[new_key] + ratio * value.to(dtype)
104
+
105
+ # enumerate keys not in this model
106
+ model_keys = set(model_keys)
107
+ for key in merged_sd.keys():
108
+ if key in model_keys:
109
+ continue
110
+ logger.warning(f"Key {key} not in model {model}, use first model's value")
111
+ if key in supplementary_key_ratios:
112
+ supplementary_key_ratios[key] += ratio
113
+ else:
114
+ supplementary_key_ratios[key] = ratio
115
+
116
+ # add supplementary keys' value (including VAE and TextEncoder)
117
+ if len(supplementary_key_ratios) > 0:
118
+ logger.info("add first model's value")
119
+ with safe_open(args.models[0], framework="pt", device=args.device) as f:
120
+ for key in tqdm(f.keys()):
121
+ _, new_key = replace_text_encoder_key(key)
122
+ if new_key not in supplementary_key_ratios:
123
+ continue
124
+
125
+ if is_unet_key(new_key): # not VAE or TextEncoder
126
+ logger.warning(f"Key {new_key} not in all models, ratio = {supplementary_key_ratios[new_key]}")
127
+
128
+ value = f.get_tensor(key) # original key
129
+
130
+ if new_key not in merged_sd:
131
+ merged_sd[new_key] = supplementary_key_ratios[new_key] * value.to(dtype)
132
+ else:
133
+ merged_sd[new_key] = merged_sd[new_key] + supplementary_key_ratios[new_key] * value.to(dtype)
134
+
135
+ # save
136
+ output_file = args.output
137
+ if not output_file.endswith(".safetensors"):
138
+ output_file = output_file + ".safetensors"
139
+
140
+ logger.info(f"Saving to {output_file}...")
141
+
142
+ # convert to save_dtype
143
+ for k in merged_sd.keys():
144
+ merged_sd[k] = merged_sd[k].to(save_dtype)
145
+
146
+ save_file(merged_sd, output_file)
147
+
148
+ logger.info("Done!")
149
+
150
+
151
+ if __name__ == "__main__":
152
+ parser = argparse.ArgumentParser(description="Merge models")
153
+ parser.add_argument("--models", nargs="+", type=str, help="Models to merge")
154
+ parser.add_argument("--output", type=str, help="Output model")
155
+ parser.add_argument("--ratios", nargs="+", type=float, help="Ratios of models, default is equal, total = 1.0")
156
+ parser.add_argument("--unet_only", action="store_true", help="Only merge unet")
157
+ parser.add_argument("--device", type=str, default="cpu", help="Device to use, default is cpu")
158
+ parser.add_argument(
159
+ "--precision", type=str, default="float", choices=["float", "fp16", "bf16"], help="Calculation precision, default is float"
160
+ )
161
+ parser.add_argument(
162
+ "--saving_precision",
163
+ type=str,
164
+ default="float",
165
+ choices=["float", "fp16", "bf16"],
166
+ help="Saving precision, default is float",
167
+ )
168
+ parser.add_argument("--show_skipped", action="store_true", help="Show skipped keys (keys not in first model)")
169
+
170
+ args = parser.parse_args()
171
+ merge(args)