ACCC1380 commited on
Commit
960cabc
1 Parent(s): 53ac835

Upload lora-scripts/sd-scripts/networks/merge_lora_old.py with huggingface_hub

Browse files
lora-scripts/sd-scripts/networks/merge_lora_old.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ import argparse
4
+ import os
5
+ import torch
6
+ from safetensors.torch import load_file, save_file
7
+ import library.model_util as model_util
8
+ import lora
9
+ from library.utils import setup_logging
10
+ setup_logging()
11
+ import logging
12
+ logger = logging.getLogger(__name__)
13
+
14
+ def load_state_dict(file_name, dtype):
15
+ if os.path.splitext(file_name)[1] == '.safetensors':
16
+ sd = load_file(file_name)
17
+ else:
18
+ sd = torch.load(file_name, map_location='cpu')
19
+ for key in list(sd.keys()):
20
+ if type(sd[key]) == torch.Tensor:
21
+ sd[key] = sd[key].to(dtype)
22
+ return sd
23
+
24
+
25
+ def save_to_file(file_name, model, state_dict, dtype):
26
+ if dtype is not None:
27
+ for key in list(state_dict.keys()):
28
+ if type(state_dict[key]) == torch.Tensor:
29
+ state_dict[key] = state_dict[key].to(dtype)
30
+
31
+ if os.path.splitext(file_name)[1] == '.safetensors':
32
+ save_file(model, file_name)
33
+ else:
34
+ torch.save(model, file_name)
35
+
36
+
37
+ def merge_to_sd_model(text_encoder, unet, models, ratios, merge_dtype):
38
+ text_encoder.to(merge_dtype)
39
+ unet.to(merge_dtype)
40
+
41
+ # create module map
42
+ name_to_module = {}
43
+ for i, root_module in enumerate([text_encoder, unet]):
44
+ if i == 0:
45
+ prefix = lora.LoRANetwork.LORA_PREFIX_TEXT_ENCODER
46
+ target_replace_modules = lora.LoRANetwork.TEXT_ENCODER_TARGET_REPLACE_MODULE
47
+ else:
48
+ prefix = lora.LoRANetwork.LORA_PREFIX_UNET
49
+ target_replace_modules = lora.LoRANetwork.UNET_TARGET_REPLACE_MODULE
50
+
51
+ for name, module in root_module.named_modules():
52
+ if module.__class__.__name__ in target_replace_modules:
53
+ for child_name, child_module in module.named_modules():
54
+ if child_module.__class__.__name__ == "Linear" or (child_module.__class__.__name__ == "Conv2d" and child_module.kernel_size == (1, 1)):
55
+ lora_name = prefix + '.' + name + '.' + child_name
56
+ lora_name = lora_name.replace('.', '_')
57
+ name_to_module[lora_name] = child_module
58
+
59
+ for model, ratio in zip(models, ratios):
60
+ logger.info(f"loading: {model}")
61
+ lora_sd = load_state_dict(model, merge_dtype)
62
+
63
+ logger.info(f"merging...")
64
+ for key in lora_sd.keys():
65
+ if "lora_down" in key:
66
+ up_key = key.replace("lora_down", "lora_up")
67
+ alpha_key = key[:key.index("lora_down")] + 'alpha'
68
+
69
+ # find original module for this lora
70
+ module_name = '.'.join(key.split('.')[:-2]) # remove trailing ".lora_down.weight"
71
+ if module_name not in name_to_module:
72
+ logger.info(f"no module found for LoRA weight: {key}")
73
+ continue
74
+ module = name_to_module[module_name]
75
+ # logger.info(f"apply {key} to {module}")
76
+
77
+ down_weight = lora_sd[key]
78
+ up_weight = lora_sd[up_key]
79
+
80
+ dim = down_weight.size()[0]
81
+ alpha = lora_sd.get(alpha_key, dim)
82
+ scale = alpha / dim
83
+
84
+ # W <- W + U * D
85
+ weight = module.weight
86
+ if len(weight.size()) == 2:
87
+ # linear
88
+ weight = weight + ratio * (up_weight @ down_weight) * scale
89
+ else:
90
+ # conv2d
91
+ weight = weight + ratio * (up_weight.squeeze(3).squeeze(2) @ down_weight.squeeze(3).squeeze(2)).unsqueeze(2).unsqueeze(3) * scale
92
+
93
+ module.weight = torch.nn.Parameter(weight)
94
+
95
+
96
+ def merge_lora_models(models, ratios, merge_dtype):
97
+ merged_sd = {}
98
+
99
+ alpha = None
100
+ dim = None
101
+ for model, ratio in zip(models, ratios):
102
+ logger.info(f"loading: {model}")
103
+ lora_sd = load_state_dict(model, merge_dtype)
104
+
105
+ logger.info(f"merging...")
106
+ for key in lora_sd.keys():
107
+ if 'alpha' in key:
108
+ if key in merged_sd:
109
+ assert merged_sd[key] == lora_sd[key], f"alpha mismatch / alphaが異なる場合、現時点ではマージできません"
110
+ else:
111
+ alpha = lora_sd[key].detach().numpy()
112
+ merged_sd[key] = lora_sd[key]
113
+ else:
114
+ if key in merged_sd:
115
+ assert merged_sd[key].size() == lora_sd[key].size(
116
+ ), f"weights shape mismatch merging v1 and v2, different dims? / 重みのサイズが合いません。v1とv2、または次元数の異なるモデルはマージできません"
117
+ merged_sd[key] = merged_sd[key] + lora_sd[key] * ratio
118
+ else:
119
+ if "lora_down" in key:
120
+ dim = lora_sd[key].size()[0]
121
+ merged_sd[key] = lora_sd[key] * ratio
122
+
123
+ logger.info(f"dim (rank): {dim}, alpha: {alpha}")
124
+ if alpha is None:
125
+ alpha = dim
126
+
127
+ return merged_sd, dim, alpha
128
+
129
+
130
+ def merge(args):
131
+ assert len(args.models) == len(args.ratios), f"number of models must be equal to number of ratios / モデルの数と重みの数は合わせてください"
132
+
133
+ def str_to_dtype(p):
134
+ if p == 'float':
135
+ return torch.float
136
+ if p == 'fp16':
137
+ return torch.float16
138
+ if p == 'bf16':
139
+ return torch.bfloat16
140
+ return None
141
+
142
+ merge_dtype = str_to_dtype(args.precision)
143
+ save_dtype = str_to_dtype(args.save_precision)
144
+ if save_dtype is None:
145
+ save_dtype = merge_dtype
146
+
147
+ if args.sd_model is not None:
148
+ logger.info(f"loading SD model: {args.sd_model}")
149
+
150
+ text_encoder, vae, unet = model_util.load_models_from_stable_diffusion_checkpoint(args.v2, args.sd_model)
151
+
152
+ merge_to_sd_model(text_encoder, unet, args.models, args.ratios, merge_dtype)
153
+
154
+ logger.info("")
155
+ logger.info(f"saving SD model to: {args.save_to}")
156
+ model_util.save_stable_diffusion_checkpoint(args.v2, args.save_to, text_encoder, unet,
157
+ args.sd_model, 0, 0, save_dtype, vae)
158
+ else:
159
+ state_dict, _, _ = merge_lora_models(args.models, args.ratios, merge_dtype)
160
+
161
+ logger.info(f"")
162
+ logger.info(f"saving model to: {args.save_to}")
163
+ save_to_file(args.save_to, state_dict, state_dict, save_dtype)
164
+
165
+
166
+ def setup_parser() -> argparse.ArgumentParser:
167
+ parser = argparse.ArgumentParser()
168
+ parser.add_argument("--v2", action='store_true',
169
+ help='load Stable Diffusion v2.x model / Stable Diffusion 2.xのモデルを読み込む')
170
+ parser.add_argument("--save_precision", type=str, default=None,
171
+ choices=[None, "float", "fp16", "bf16"], help="precision in saving, same to merging if omitted / 保存時に精度を変更して保存する、省略時はマージ時の精度と同じ")
172
+ parser.add_argument("--precision", type=str, default="float",
173
+ choices=["float", "fp16", "bf16"], help="precision in merging (float is recommended) / マージの計算時の精度(floatを推奨)")
174
+ parser.add_argument("--sd_model", type=str, default=None,
175
+ help="Stable Diffusion model to load: ckpt or safetensors file, merge LoRA models if omitted / 読み込むモデル、ckptまたはsafetensors。省略時はLoRAモデル同士をマージする")
176
+ parser.add_argument("--save_to", type=str, default=None,
177
+ help="destination file name: ckpt or safetensors file / 保存先のファイル名、ckptまたはsafetensors")
178
+ parser.add_argument("--models", type=str, nargs='*',
179
+ help="LoRA models to merge: ckpt or safetensors file / マージするLoRAモデル、ckptまたはsafetensors")
180
+ parser.add_argument("--ratios", type=float, nargs='*',
181
+ help="ratios for each model / それぞれのLoRAモデルの比率")
182
+
183
+ return parser
184
+
185
+
186
+ if __name__ == '__main__':
187
+ parser = setup_parser()
188
+
189
+ args = parser.parse_args()
190
+ merge(args)