ACCC1380 commited on
Commit
8832fc5
1 Parent(s): cf0ba61

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

Browse files
lora-scripts/sd-scripts/networks/extract_lora_from_models.py ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # extract approximating LoRA by svd from two SD models
2
+ # The code is based on https://github.com/cloneofsimo/lora/blob/develop/lora_diffusion/cli_svd.py
3
+ # Thanks to cloneofsimo!
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ import time
9
+ import torch
10
+ from safetensors.torch import load_file, save_file
11
+ from tqdm import tqdm
12
+ from library import sai_model_spec, model_util, sdxl_model_util
13
+ import lora
14
+ from library.utils import setup_logging
15
+ setup_logging()
16
+ import logging
17
+ logger = logging.getLogger(__name__)
18
+
19
+ # CLAMP_QUANTILE = 0.99
20
+ # MIN_DIFF = 1e-1
21
+
22
+
23
+ def save_to_file(file_name, model, state_dict, dtype):
24
+ if dtype is not None:
25
+ for key in list(state_dict.keys()):
26
+ if type(state_dict[key]) == torch.Tensor:
27
+ state_dict[key] = state_dict[key].to(dtype)
28
+
29
+ if os.path.splitext(file_name)[1] == ".safetensors":
30
+ save_file(model, file_name)
31
+ else:
32
+ torch.save(model, file_name)
33
+
34
+
35
+ def svd(
36
+ model_org=None,
37
+ model_tuned=None,
38
+ save_to=None,
39
+ dim=4,
40
+ v2=None,
41
+ sdxl=None,
42
+ conv_dim=None,
43
+ v_parameterization=None,
44
+ device=None,
45
+ save_precision=None,
46
+ clamp_quantile=0.99,
47
+ min_diff=0.01,
48
+ no_metadata=False,
49
+ load_precision=None,
50
+ load_original_model_to=None,
51
+ load_tuned_model_to=None,
52
+ ):
53
+ def str_to_dtype(p):
54
+ if p == "float":
55
+ return torch.float
56
+ if p == "fp16":
57
+ return torch.float16
58
+ if p == "bf16":
59
+ return torch.bfloat16
60
+ return None
61
+
62
+ assert v2 != sdxl or (not v2 and not sdxl), "v2 and sdxl cannot be specified at the same time / v2とsdxlは同時に指定できません"
63
+ if v_parameterization is None:
64
+ v_parameterization = v2
65
+
66
+ load_dtype = str_to_dtype(load_precision) if load_precision else None
67
+ save_dtype = str_to_dtype(save_precision)
68
+ work_device = "cpu"
69
+
70
+ # load models
71
+ if not sdxl:
72
+ logger.info(f"loading original SD model : {model_org}")
73
+ text_encoder_o, _, unet_o = model_util.load_models_from_stable_diffusion_checkpoint(v2, model_org)
74
+ text_encoders_o = [text_encoder_o]
75
+ if load_dtype is not None:
76
+ text_encoder_o = text_encoder_o.to(load_dtype)
77
+ unet_o = unet_o.to(load_dtype)
78
+
79
+ logger.info(f"loading tuned SD model : {model_tuned}")
80
+ text_encoder_t, _, unet_t = model_util.load_models_from_stable_diffusion_checkpoint(v2, model_tuned)
81
+ text_encoders_t = [text_encoder_t]
82
+ if load_dtype is not None:
83
+ text_encoder_t = text_encoder_t.to(load_dtype)
84
+ unet_t = unet_t.to(load_dtype)
85
+
86
+ model_version = model_util.get_model_version_str_for_sd1_sd2(v2, v_parameterization)
87
+ else:
88
+ device_org = load_original_model_to if load_original_model_to else "cpu"
89
+ device_tuned = load_tuned_model_to if load_tuned_model_to else "cpu"
90
+
91
+ logger.info(f"loading original SDXL model : {model_org}")
92
+ text_encoder_o1, text_encoder_o2, _, unet_o, _, _ = sdxl_model_util.load_models_from_sdxl_checkpoint(
93
+ sdxl_model_util.MODEL_VERSION_SDXL_BASE_V1_0, model_org, device_org
94
+ )
95
+ text_encoders_o = [text_encoder_o1, text_encoder_o2]
96
+ if load_dtype is not None:
97
+ text_encoder_o1 = text_encoder_o1.to(load_dtype)
98
+ text_encoder_o2 = text_encoder_o2.to(load_dtype)
99
+ unet_o = unet_o.to(load_dtype)
100
+
101
+ logger.info(f"loading original SDXL model : {model_tuned}")
102
+ text_encoder_t1, text_encoder_t2, _, unet_t, _, _ = sdxl_model_util.load_models_from_sdxl_checkpoint(
103
+ sdxl_model_util.MODEL_VERSION_SDXL_BASE_V1_0, model_tuned, device_tuned
104
+ )
105
+ text_encoders_t = [text_encoder_t1, text_encoder_t2]
106
+ if load_dtype is not None:
107
+ text_encoder_t1 = text_encoder_t1.to(load_dtype)
108
+ text_encoder_t2 = text_encoder_t2.to(load_dtype)
109
+ unet_t = unet_t.to(load_dtype)
110
+
111
+ model_version = sdxl_model_util.MODEL_VERSION_SDXL_BASE_V1_0
112
+
113
+ # create LoRA network to extract weights: Use dim (rank) as alpha
114
+ if conv_dim is None:
115
+ kwargs = {}
116
+ else:
117
+ kwargs = {"conv_dim": conv_dim, "conv_alpha": conv_dim}
118
+
119
+ lora_network_o = lora.create_network(1.0, dim, dim, None, text_encoders_o, unet_o, **kwargs)
120
+ lora_network_t = lora.create_network(1.0, dim, dim, None, text_encoders_t, unet_t, **kwargs)
121
+ assert len(lora_network_o.text_encoder_loras) == len(
122
+ lora_network_t.text_encoder_loras
123
+ ), f"model version is different (SD1.x vs SD2.x) / それぞれのモデルのバージョンが違います(SD1.xベースとSD2.xベース) "
124
+
125
+ # get diffs
126
+ diffs = {}
127
+ text_encoder_different = False
128
+ for i, (lora_o, lora_t) in enumerate(zip(lora_network_o.text_encoder_loras, lora_network_t.text_encoder_loras)):
129
+ lora_name = lora_o.lora_name
130
+ module_o = lora_o.org_module
131
+ module_t = lora_t.org_module
132
+ diff = module_t.weight.to(work_device) - module_o.weight.to(work_device)
133
+
134
+ # clear weight to save memory
135
+ module_o.weight = None
136
+ module_t.weight = None
137
+
138
+ # Text Encoder might be same
139
+ if not text_encoder_different and torch.max(torch.abs(diff)) > min_diff:
140
+ text_encoder_different = True
141
+ logger.info(f"Text encoder is different. {torch.max(torch.abs(diff))} > {min_diff}")
142
+
143
+ diffs[lora_name] = diff
144
+
145
+ # clear target Text Encoder to save memory
146
+ for text_encoder in text_encoders_t:
147
+ del text_encoder
148
+
149
+ if not text_encoder_different:
150
+ logger.warning("Text encoder is same. Extract U-Net only.")
151
+ lora_network_o.text_encoder_loras = []
152
+ diffs = {} # clear diffs
153
+
154
+ for i, (lora_o, lora_t) in enumerate(zip(lora_network_o.unet_loras, lora_network_t.unet_loras)):
155
+ lora_name = lora_o.lora_name
156
+ module_o = lora_o.org_module
157
+ module_t = lora_t.org_module
158
+ diff = module_t.weight.to(work_device) - module_o.weight.to(work_device)
159
+
160
+ # clear weight to save memory
161
+ module_o.weight = None
162
+ module_t.weight = None
163
+
164
+ diffs[lora_name] = diff
165
+
166
+ # clear LoRA network, target U-Net to save memory
167
+ del lora_network_o
168
+ del lora_network_t
169
+ del unet_t
170
+
171
+ # make LoRA with svd
172
+ logger.info("calculating by svd")
173
+ lora_weights = {}
174
+ with torch.no_grad():
175
+ for lora_name, mat in tqdm(list(diffs.items())):
176
+ if args.device:
177
+ mat = mat.to(args.device)
178
+ mat = mat.to(torch.float) # calc by float
179
+
180
+ # if conv_dim is None, diffs do not include LoRAs for conv2d-3x3
181
+ conv2d = len(mat.size()) == 4
182
+ kernel_size = None if not conv2d else mat.size()[2:4]
183
+ conv2d_3x3 = conv2d and kernel_size != (1, 1)
184
+
185
+ rank = dim if not conv2d_3x3 or conv_dim is None else conv_dim
186
+ out_dim, in_dim = mat.size()[0:2]
187
+
188
+ if device:
189
+ mat = mat.to(device)
190
+
191
+ # logger.info(lora_name, mat.size(), mat.device, rank, in_dim, out_dim)
192
+ rank = min(rank, in_dim, out_dim) # LoRA rank cannot exceed the original dim
193
+
194
+ if conv2d:
195
+ if conv2d_3x3:
196
+ mat = mat.flatten(start_dim=1)
197
+ else:
198
+ mat = mat.squeeze()
199
+
200
+ U, S, Vh = torch.linalg.svd(mat)
201
+
202
+ U = U[:, :rank]
203
+ S = S[:rank]
204
+ U = U @ torch.diag(S)
205
+
206
+ Vh = Vh[:rank, :]
207
+
208
+ dist = torch.cat([U.flatten(), Vh.flatten()])
209
+ hi_val = torch.quantile(dist, clamp_quantile)
210
+ low_val = -hi_val
211
+
212
+ U = U.clamp(low_val, hi_val)
213
+ Vh = Vh.clamp(low_val, hi_val)
214
+
215
+ if conv2d:
216
+ U = U.reshape(out_dim, rank, 1, 1)
217
+ Vh = Vh.reshape(rank, in_dim, kernel_size[0], kernel_size[1])
218
+
219
+ U = U.to(work_device, dtype=save_dtype).contiguous()
220
+ Vh = Vh.to(work_device, dtype=save_dtype).contiguous()
221
+
222
+ lora_weights[lora_name] = (U, Vh)
223
+
224
+ # make state dict for LoRA
225
+ lora_sd = {}
226
+ for lora_name, (up_weight, down_weight) in lora_weights.items():
227
+ lora_sd[lora_name + ".lora_up.weight"] = up_weight
228
+ lora_sd[lora_name + ".lora_down.weight"] = down_weight
229
+ lora_sd[lora_name + ".alpha"] = torch.tensor(down_weight.size()[0])
230
+
231
+ # load state dict to LoRA and save it
232
+ lora_network_save, lora_sd = lora.create_network_from_weights(1.0, None, None, text_encoders_o, unet_o, weights_sd=lora_sd)
233
+ lora_network_save.apply_to(text_encoders_o, unet_o) # create internal module references for state_dict
234
+
235
+ info = lora_network_save.load_state_dict(lora_sd)
236
+ logger.info(f"Loading extracted LoRA weights: {info}")
237
+
238
+ dir_name = os.path.dirname(save_to)
239
+ if dir_name and not os.path.exists(dir_name):
240
+ os.makedirs(dir_name, exist_ok=True)
241
+
242
+ # minimum metadata
243
+ net_kwargs = {}
244
+ if conv_dim is not None:
245
+ net_kwargs["conv_dim"] = str(conv_dim)
246
+ net_kwargs["conv_alpha"] = str(float(conv_dim))
247
+
248
+ metadata = {
249
+ "ss_v2": str(v2),
250
+ "ss_base_model_version": model_version,
251
+ "ss_network_module": "networks.lora",
252
+ "ss_network_dim": str(dim),
253
+ "ss_network_alpha": str(float(dim)),
254
+ "ss_network_args": json.dumps(net_kwargs),
255
+ }
256
+
257
+ if not no_metadata:
258
+ title = os.path.splitext(os.path.basename(save_to))[0]
259
+ sai_metadata = sai_model_spec.build_metadata(None, v2, v_parameterization, sdxl, True, False, time.time(), title=title)
260
+ metadata.update(sai_metadata)
261
+
262
+ lora_network_save.save_weights(save_to, save_dtype, metadata)
263
+ logger.info(f"LoRA weights are saved to: {save_to}")
264
+
265
+
266
+ def setup_parser() -> argparse.ArgumentParser:
267
+ parser = argparse.ArgumentParser()
268
+ parser.add_argument("--v2", action="store_true", help="load Stable Diffusion v2.x model / Stable Diffusion 2.xのモデルを読み込む")
269
+ parser.add_argument(
270
+ "--v_parameterization",
271
+ action="store_true",
272
+ default=None,
273
+ help="make LoRA metadata for v-parameterization (default is same to v2) / 作成するLoRAのメタデータにv-parameterization用と設定する(省略時はv2と同じ)",
274
+ )
275
+ parser.add_argument(
276
+ "--sdxl", action="store_true", help="load Stable Diffusion SDXL base model / Stable Diffusion SDXL baseのモデルを読み込む"
277
+ )
278
+ parser.add_argument(
279
+ "--load_precision",
280
+ type=str,
281
+ default=None,
282
+ choices=[None, "float", "fp16", "bf16"],
283
+ help="precision in loading, model default if omitted / 読み込み時に精度を変更して読み込む、省略時はモデルファイルによる"
284
+ )
285
+ parser.add_argument(
286
+ "--save_precision",
287
+ type=str,
288
+ default=None,
289
+ choices=[None, "float", "fp16", "bf16"],
290
+ help="precision in saving, same to merging if omitted / 保存時に精度を変更して保存する、省略時はfloat",
291
+ )
292
+ parser.add_argument(
293
+ "--model_org",
294
+ type=str,
295
+ default=None,
296
+ required=True,
297
+ help="Stable Diffusion original model: ckpt or safetensors file / 元モデル、ckptまたはsafetensors",
298
+ )
299
+ parser.add_argument(
300
+ "--model_tuned",
301
+ type=str,
302
+ default=None,
303
+ required=True,
304
+ help="Stable Diffusion tuned model, LoRA is difference of `original to tuned`: ckpt or safetensors file / 派生モデル(生成されるLoRAは元→派生の差分になります)、ckptまたはsafetensors",
305
+ )
306
+ parser.add_argument(
307
+ "--save_to",
308
+ type=str,
309
+ default=None,
310
+ required=True,
311
+ help="destination file name: ckpt or safetensors file / 保存先のファイル名、ckptまたはsafetensors",
312
+ )
313
+ parser.add_argument("--dim", type=int, default=4, help="dimension (rank) of LoRA (default 4) / LoRAの次元数(rank)(デフォルト4)")
314
+ parser.add_argument(
315
+ "--conv_dim",
316
+ type=int,
317
+ default=None,
318
+ help="dimension (rank) of LoRA for Conv2d-3x3 (default None, disabled) / LoRAのConv2d-3x3の次元数(rank)(デフォルトNone、適用なし)",
319
+ )
320
+ parser.add_argument("--device", type=str, default=None, help="device to use, cuda for GPU / 計算を行うデバイス、cuda でGPUを使う")
321
+ parser.add_argument(
322
+ "--clamp_quantile",
323
+ type=float,
324
+ default=0.99,
325
+ help="Quantile clamping value, float, (0-1). Default = 0.99 / 値をクランプするための分位点、float、(0-1)。デフォルトは0.99",
326
+ )
327
+ parser.add_argument(
328
+ "--min_diff",
329
+ type=float,
330
+ default=0.01,
331
+ help="Minimum difference between finetuned model and base to consider them different enough to extract, float, (0-1). Default = 0.01 /"
332
+ + "LoRAを抽出するために元モデルと派生モデルの差分の最小値、float、(0-1)。デフォルトは0.01",
333
+ )
334
+ parser.add_argument(
335
+ "--no_metadata",
336
+ action="store_true",
337
+ help="do not save sai modelspec metadata (minimum ss_metadata for LoRA is saved) / "
338
+ + "sai modelspecのメタデータを保存しない(LoRAの最低限のss_metadataは保存される)",
339
+ )
340
+ parser.add_argument(
341
+ "--load_original_model_to",
342
+ type=str,
343
+ default=None,
344
+ help="location to load original model, cpu or cuda, cuda:0, etc, default is cpu, only for SDXL / 元モデル読み込み先、cpuまたはcuda、cuda:0など、省略時はcpu、SDXLのみ有効",
345
+ )
346
+ parser.add_argument(
347
+ "--load_tuned_model_to",
348
+ type=str,
349
+ default=None,
350
+ help="location to load tuned model, cpu or cuda, cuda:0, etc, default is cpu, only for SDXL / 派生モデル読み込み先、cpuまたはcuda、cuda:0など、省略時はcpu、SDXLのみ有効",
351
+ )
352
+
353
+ return parser
354
+
355
+
356
+ if __name__ == "__main__":
357
+ parser = setup_parser()
358
+
359
+ args = parser.parse_args()
360
+ svd(**vars(args))