ACCC1380 commited on
Commit
7c0e495
1 Parent(s): b5f7190

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

Browse files
lora-scripts/sd-scripts/networks/resize_lora.py ADDED
@@ -0,0 +1,411 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Convert LoRA to different rank approximation (should only be used to go to lower rank)
2
+ # This code is based off the extract_lora_from_models.py file which is based on https://github.com/cloneofsimo/lora/blob/develop/lora_diffusion/cli_svd.py
3
+ # Thanks to cloneofsimo
4
+
5
+ import os
6
+ import argparse
7
+ import torch
8
+ from safetensors.torch import load_file, save_file, safe_open
9
+ from tqdm import tqdm
10
+ import numpy as np
11
+
12
+ from library import train_util
13
+ from library import model_util
14
+ from library.utils import setup_logging
15
+
16
+ setup_logging()
17
+ import logging
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+ MIN_SV = 1e-6
22
+
23
+ # Model save and load functions
24
+
25
+
26
+ def load_state_dict(file_name, dtype):
27
+ if model_util.is_safetensors(file_name):
28
+ sd = load_file(file_name)
29
+ with safe_open(file_name, framework="pt") as f:
30
+ metadata = f.metadata()
31
+ else:
32
+ sd = torch.load(file_name, map_location="cpu")
33
+ metadata = None
34
+
35
+ for key in list(sd.keys()):
36
+ if type(sd[key]) == torch.Tensor:
37
+ sd[key] = sd[key].to(dtype)
38
+
39
+ return sd, metadata
40
+
41
+
42
+ def save_to_file(file_name, state_dict, dtype, metadata):
43
+ if dtype is not None:
44
+ for key in list(state_dict.keys()):
45
+ if type(state_dict[key]) == torch.Tensor:
46
+ state_dict[key] = state_dict[key].to(dtype)
47
+
48
+ if model_util.is_safetensors(file_name):
49
+ save_file(state_dict, file_name, metadata)
50
+ else:
51
+ torch.save(state_dict, file_name)
52
+
53
+
54
+ # Indexing functions
55
+
56
+
57
+ def index_sv_cumulative(S, target):
58
+ original_sum = float(torch.sum(S))
59
+ cumulative_sums = torch.cumsum(S, dim=0) / original_sum
60
+ index = int(torch.searchsorted(cumulative_sums, target)) + 1
61
+ index = max(1, min(index, len(S) - 1))
62
+
63
+ return index
64
+
65
+
66
+ def index_sv_fro(S, target):
67
+ S_squared = S.pow(2)
68
+ S_fro_sq = float(torch.sum(S_squared))
69
+ sum_S_squared = torch.cumsum(S_squared, dim=0) / S_fro_sq
70
+ index = int(torch.searchsorted(sum_S_squared, target**2)) + 1
71
+ index = max(1, min(index, len(S) - 1))
72
+
73
+ return index
74
+
75
+
76
+ def index_sv_ratio(S, target):
77
+ max_sv = S[0]
78
+ min_sv = max_sv / target
79
+ index = int(torch.sum(S > min_sv).item())
80
+ index = max(1, min(index, len(S) - 1))
81
+
82
+ return index
83
+
84
+
85
+ # Modified from Kohaku-blueleaf's extract/merge functions
86
+ def extract_conv(weight, lora_rank, dynamic_method, dynamic_param, device, scale=1):
87
+ out_size, in_size, kernel_size, _ = weight.size()
88
+ U, S, Vh = torch.linalg.svd(weight.reshape(out_size, -1).to(device))
89
+
90
+ param_dict = rank_resize(S, lora_rank, dynamic_method, dynamic_param, scale)
91
+ lora_rank = param_dict["new_rank"]
92
+
93
+ U = U[:, :lora_rank]
94
+ S = S[:lora_rank]
95
+ U = U @ torch.diag(S)
96
+ Vh = Vh[:lora_rank, :]
97
+
98
+ param_dict["lora_down"] = Vh.reshape(lora_rank, in_size, kernel_size, kernel_size).cpu()
99
+ param_dict["lora_up"] = U.reshape(out_size, lora_rank, 1, 1).cpu()
100
+ del U, S, Vh, weight
101
+ return param_dict
102
+
103
+
104
+ def extract_linear(weight, lora_rank, dynamic_method, dynamic_param, device, scale=1):
105
+ out_size, in_size = weight.size()
106
+
107
+ U, S, Vh = torch.linalg.svd(weight.to(device))
108
+
109
+ param_dict = rank_resize(S, lora_rank, dynamic_method, dynamic_param, scale)
110
+ lora_rank = param_dict["new_rank"]
111
+
112
+ U = U[:, :lora_rank]
113
+ S = S[:lora_rank]
114
+ U = U @ torch.diag(S)
115
+ Vh = Vh[:lora_rank, :]
116
+
117
+ param_dict["lora_down"] = Vh.reshape(lora_rank, in_size).cpu()
118
+ param_dict["lora_up"] = U.reshape(out_size, lora_rank).cpu()
119
+ del U, S, Vh, weight
120
+ return param_dict
121
+
122
+
123
+ def merge_conv(lora_down, lora_up, device):
124
+ in_rank, in_size, kernel_size, k_ = lora_down.shape
125
+ out_size, out_rank, _, _ = lora_up.shape
126
+ assert in_rank == out_rank and kernel_size == k_, f"rank {in_rank} {out_rank} or kernel {kernel_size} {k_} mismatch"
127
+
128
+ lora_down = lora_down.to(device)
129
+ lora_up = lora_up.to(device)
130
+
131
+ merged = lora_up.reshape(out_size, -1) @ lora_down.reshape(in_rank, -1)
132
+ weight = merged.reshape(out_size, in_size, kernel_size, kernel_size)
133
+ del lora_up, lora_down
134
+ return weight
135
+
136
+
137
+ def merge_linear(lora_down, lora_up, device):
138
+ in_rank, in_size = lora_down.shape
139
+ out_size, out_rank = lora_up.shape
140
+ assert in_rank == out_rank, f"rank {in_rank} {out_rank} mismatch"
141
+
142
+ lora_down = lora_down.to(device)
143
+ lora_up = lora_up.to(device)
144
+
145
+ weight = lora_up @ lora_down
146
+ del lora_up, lora_down
147
+ return weight
148
+
149
+
150
+ # Calculate new rank
151
+
152
+
153
+ def rank_resize(S, rank, dynamic_method, dynamic_param, scale=1):
154
+ param_dict = {}
155
+
156
+ if dynamic_method == "sv_ratio":
157
+ # Calculate new dim and alpha based off ratio
158
+ new_rank = index_sv_ratio(S, dynamic_param) + 1
159
+ new_alpha = float(scale * new_rank)
160
+
161
+ elif dynamic_method == "sv_cumulative":
162
+ # Calculate new dim and alpha based off cumulative sum
163
+ new_rank = index_sv_cumulative(S, dynamic_param) + 1
164
+ new_alpha = float(scale * new_rank)
165
+
166
+ elif dynamic_method == "sv_fro":
167
+ # Calculate new dim and alpha based off sqrt sum of squares
168
+ new_rank = index_sv_fro(S, dynamic_param) + 1
169
+ new_alpha = float(scale * new_rank)
170
+ else:
171
+ new_rank = rank
172
+ new_alpha = float(scale * new_rank)
173
+
174
+ if S[0] <= MIN_SV: # Zero matrix, set dim to 1
175
+ new_rank = 1
176
+ new_alpha = float(scale * new_rank)
177
+ elif new_rank > rank: # cap max rank at rank
178
+ new_rank = rank
179
+ new_alpha = float(scale * new_rank)
180
+
181
+ # Calculate resize info
182
+ s_sum = torch.sum(torch.abs(S))
183
+ s_rank = torch.sum(torch.abs(S[:new_rank]))
184
+
185
+ S_squared = S.pow(2)
186
+ s_fro = torch.sqrt(torch.sum(S_squared))
187
+ s_red_fro = torch.sqrt(torch.sum(S_squared[:new_rank]))
188
+ fro_percent = float(s_red_fro / s_fro)
189
+
190
+ param_dict["new_rank"] = new_rank
191
+ param_dict["new_alpha"] = new_alpha
192
+ param_dict["sum_retained"] = (s_rank) / s_sum
193
+ param_dict["fro_retained"] = fro_percent
194
+ param_dict["max_ratio"] = S[0] / S[new_rank - 1]
195
+
196
+ return param_dict
197
+
198
+
199
+ def resize_lora_model(lora_sd, new_rank, new_conv_rank, save_dtype, device, dynamic_method, dynamic_param, verbose):
200
+ network_alpha = None
201
+ network_dim = None
202
+ verbose_str = "\n"
203
+ fro_list = []
204
+
205
+ # Extract loaded lora dim and alpha
206
+ for key, value in lora_sd.items():
207
+ if network_alpha is None and "alpha" in key:
208
+ network_alpha = value
209
+ if network_dim is None and "lora_down" in key and len(value.size()) == 2:
210
+ network_dim = value.size()[0]
211
+ if network_alpha is not None and network_dim is not None:
212
+ break
213
+ if network_alpha is None:
214
+ network_alpha = network_dim
215
+
216
+ scale = network_alpha / network_dim
217
+
218
+ if dynamic_method:
219
+ logger.info(
220
+ f"Dynamically determining new alphas and dims based off {dynamic_method}: {dynamic_param}, max rank is {new_rank}"
221
+ )
222
+
223
+ lora_down_weight = None
224
+ lora_up_weight = None
225
+
226
+ o_lora_sd = lora_sd.copy()
227
+ block_down_name = None
228
+ block_up_name = None
229
+
230
+ with torch.no_grad():
231
+ for key, value in tqdm(lora_sd.items()):
232
+ weight_name = None
233
+ if "lora_down" in key:
234
+ block_down_name = key.rsplit(".lora_down", 1)[0]
235
+ weight_name = key.rsplit(".", 1)[-1]
236
+ lora_down_weight = value
237
+ else:
238
+ continue
239
+
240
+ # find corresponding lora_up and alpha
241
+ block_up_name = block_down_name
242
+ lora_up_weight = lora_sd.get(block_up_name + ".lora_up." + weight_name, None)
243
+ lora_alpha = lora_sd.get(block_down_name + ".alpha", None)
244
+
245
+ weights_loaded = lora_down_weight is not None and lora_up_weight is not None
246
+
247
+ if weights_loaded:
248
+
249
+ conv2d = len(lora_down_weight.size()) == 4
250
+ if lora_alpha is None:
251
+ scale = 1.0
252
+ else:
253
+ scale = lora_alpha / lora_down_weight.size()[0]
254
+
255
+ if conv2d:
256
+ full_weight_matrix = merge_conv(lora_down_weight, lora_up_weight, device)
257
+ param_dict = extract_conv(full_weight_matrix, new_conv_rank, dynamic_method, dynamic_param, device, scale)
258
+ else:
259
+ full_weight_matrix = merge_linear(lora_down_weight, lora_up_weight, device)
260
+ param_dict = extract_linear(full_weight_matrix, new_rank, dynamic_method, dynamic_param, device, scale)
261
+
262
+ if verbose:
263
+ max_ratio = param_dict["max_ratio"]
264
+ sum_retained = param_dict["sum_retained"]
265
+ fro_retained = param_dict["fro_retained"]
266
+ if not np.isnan(fro_retained):
267
+ fro_list.append(float(fro_retained))
268
+
269
+ verbose_str += f"{block_down_name:75} | "
270
+ verbose_str += (
271
+ f"sum(S) retained: {sum_retained:.1%}, fro retained: {fro_retained:.1%}, max(S) ratio: {max_ratio:0.1f}"
272
+ )
273
+
274
+ if verbose and dynamic_method:
275
+ verbose_str += f", dynamic | dim: {param_dict['new_rank']}, alpha: {param_dict['new_alpha']}\n"
276
+ else:
277
+ verbose_str += "\n"
278
+
279
+ new_alpha = param_dict["new_alpha"]
280
+ o_lora_sd[block_down_name + "." + "lora_down.weight"] = param_dict["lora_down"].to(save_dtype).contiguous()
281
+ o_lora_sd[block_up_name + "." + "lora_up.weight"] = param_dict["lora_up"].to(save_dtype).contiguous()
282
+ o_lora_sd[block_up_name + "." "alpha"] = torch.tensor(param_dict["new_alpha"]).to(save_dtype)
283
+
284
+ block_down_name = None
285
+ block_up_name = None
286
+ lora_down_weight = None
287
+ lora_up_weight = None
288
+ weights_loaded = False
289
+ del param_dict
290
+
291
+ if verbose:
292
+ print(verbose_str)
293
+ print(f"Average Frobenius norm retention: {np.mean(fro_list):.2%} | std: {np.std(fro_list):0.3f}")
294
+ logger.info("resizing complete")
295
+ return o_lora_sd, network_dim, new_alpha
296
+
297
+
298
+ def resize(args):
299
+ if args.save_to is None or not (
300
+ args.save_to.endswith(".ckpt")
301
+ or args.save_to.endswith(".pt")
302
+ or args.save_to.endswith(".pth")
303
+ or args.save_to.endswith(".safetensors")
304
+ ):
305
+ raise Exception("The --save_to argument must be specified and must be a .ckpt , .pt, .pth or .safetensors file.")
306
+
307
+ args.new_conv_rank = args.new_conv_rank if args.new_conv_rank is not None else args.new_rank
308
+
309
+ def str_to_dtype(p):
310
+ if p == "float":
311
+ return torch.float
312
+ if p == "fp16":
313
+ return torch.float16
314
+ if p == "bf16":
315
+ return torch.bfloat16
316
+ return None
317
+
318
+ if args.dynamic_method and not args.dynamic_param:
319
+ raise Exception("If using dynamic_method, then dynamic_param is required")
320
+
321
+ merge_dtype = str_to_dtype("float") # matmul method above only seems to work in float32
322
+ save_dtype = str_to_dtype(args.save_precision)
323
+ if save_dtype is None:
324
+ save_dtype = merge_dtype
325
+
326
+ logger.info("loading Model...")
327
+ lora_sd, metadata = load_state_dict(args.model, merge_dtype)
328
+
329
+ logger.info("Resizing Lora...")
330
+ state_dict, old_dim, new_alpha = resize_lora_model(
331
+ lora_sd, args.new_rank, args.new_conv_rank, save_dtype, args.device, args.dynamic_method, args.dynamic_param, args.verbose
332
+ )
333
+
334
+ # update metadata
335
+ if metadata is None:
336
+ metadata = {}
337
+
338
+ comment = metadata.get("ss_training_comment", "")
339
+
340
+ if not args.dynamic_method:
341
+ conv_desc = "" if args.new_rank == args.new_conv_rank else f" (conv: {args.new_conv_rank})"
342
+ metadata["ss_training_comment"] = f"dimension is resized from {old_dim} to {args.new_rank}{conv_desc}; {comment}"
343
+ metadata["ss_network_dim"] = str(args.new_rank)
344
+ metadata["ss_network_alpha"] = str(new_alpha)
345
+ else:
346
+ metadata["ss_training_comment"] = (
347
+ f"Dynamic resize with {args.dynamic_method}: {args.dynamic_param} from {old_dim}; {comment}"
348
+ )
349
+ metadata["ss_network_dim"] = "Dynamic"
350
+ metadata["ss_network_alpha"] = "Dynamic"
351
+
352
+ model_hash, legacy_hash = train_util.precalculate_safetensors_hashes(state_dict, metadata)
353
+ metadata["sshs_model_hash"] = model_hash
354
+ metadata["sshs_legacy_hash"] = legacy_hash
355
+
356
+ logger.info(f"saving model to: {args.save_to}")
357
+ save_to_file(args.save_to, state_dict, save_dtype, metadata)
358
+
359
+
360
+ def setup_parser() -> argparse.ArgumentParser:
361
+ parser = argparse.ArgumentParser()
362
+
363
+ parser.add_argument(
364
+ "--save_precision",
365
+ type=str,
366
+ default=None,
367
+ choices=[None, "float", "fp16", "bf16"],
368
+ help="precision in saving, float if omitted / 保存時の精度、未指定時はfloat",
369
+ )
370
+ parser.add_argument("--new_rank", type=int, default=4, help="Specify rank of output LoRA / 出力するLoRAのrank (dim)")
371
+ parser.add_argument(
372
+ "--new_conv_rank",
373
+ type=int,
374
+ default=None,
375
+ help="Specify rank of output LoRA for Conv2d 3x3, None for same as new_rank / 出力するConv2D 3x3 LoRAのrank (dim)、Noneでnew_rankと同じ",
376
+ )
377
+ parser.add_argument(
378
+ "--save_to",
379
+ type=str,
380
+ default=None,
381
+ help="destination file name: ckpt or safetensors file / 保存先のファイル名、ckptまたはsafetensors",
382
+ )
383
+ parser.add_argument(
384
+ "--model",
385
+ type=str,
386
+ default=None,
387
+ help="LoRA model to resize at to new rank: ckpt or safetensors file / 読み込むLoRAモデル、ckptまたはsafetensors",
388
+ )
389
+ parser.add_argument(
390
+ "--device", type=str, default=None, help="device to use, cuda for GPU / 計算を行うデバイス、cuda でGPUを使う"
391
+ )
392
+ parser.add_argument(
393
+ "--verbose", action="store_true", help="Display verbose resizing information / rank変更時の詳細情報を出力する"
394
+ )
395
+ parser.add_argument(
396
+ "--dynamic_method",
397
+ type=str,
398
+ default=None,
399
+ choices=[None, "sv_ratio", "sv_fro", "sv_cumulative"],
400
+ help="Specify dynamic resizing method, --new_rank is used as a hard limit for max rank",
401
+ )
402
+ parser.add_argument("--dynamic_param", type=float, default=None, help="Specify target for dynamic reduction")
403
+
404
+ return parser
405
+
406
+
407
+ if __name__ == "__main__":
408
+ parser = setup_parser()
409
+
410
+ args = parser.parse_args()
411
+ resize(args)