-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlora.py
1700 lines (1414 loc) · 66.5 KB
/
lora.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
import math
from itertools import groupby
from typing import Callable, Dict, List, Optional, Set, Tuple, Type, Union
import numpy as np
import PIL
import torch
import torch.nn as nn
import torch.nn.functional as F
try:
from safetensors.torch import safe_open
from safetensors.torch import save_file as safe_save
safetensors_available = True
except ImportError:
from safe_open import safe_open
def safe_save(
tensors: Dict[str, torch.Tensor],
filename: str,
metadata: Optional[Dict[str, str]] = None,
) -> None:
raise EnvironmentError(
"Saving safetensors requires the safetensors library. Please install with pip or similar."
)
safetensors_available = False
class LoraInjectedLinear(nn.Module):
"""
LoraInjectedLinear 类是对 nn.Linear 的扩展,注入了 LoRA(低秩适应)机制。
LoRA 通过在原始线性层的基础上添加低秩矩阵来减少可训练参数数量,从而加速训练和推理。
"""
def __init__(
self, in_features, out_features, bias=False, r=4, dropout_p=0.1, scale=1.0
):
super().__init__()
# 检查 LoRA 的秩是否超过输入或输出特征的最小维度
if r > min(in_features, out_features):
raise ValueError(
f"LoRA rank {r} must be less or equal than {min(in_features, out_features)}"
)
# 记录 LoRA 的秩
self.r = r
# 定义原始的线性层
self.linear = nn.Linear(in_features, out_features, bias)
# 定义 LoRA 的下层线性层,将输入特征映射到低秩空间
self.lora_down = nn.Linear(in_features, r, bias=False)
# 定义 Dropout 层,防止过拟合并增加模型的泛化能力
self.dropout = nn.Dropout(dropout_p)
# 定义 LoRA 的上层线性层,将低秩空间的表示映射回输出特征空间
self.lora_up = nn.Linear(r, out_features, bias=False)
# 定义缩放因子,用于调整 LoRA 的贡献
self.scale = scale
# 定义选择器(selector),这里使用恒等映射(Identity),后续可以自定义
self.selector = nn.Identity()
# 初始化 LoRA 下层线性层的权重,使用正态分布,标准差为 1/r
nn.init.normal_(self.lora_down.weight, std=1 / r)
# 初始化 LoRA 上层线性层的权重为零
nn.init.zeros_(self.lora_up.weight)
def forward(self, input):
"""
前向传播函数,计算线性变换和 LoRA 调整的总和。
参数:
input (torch.Tensor): 输入张量,形状为 (batch_size, in_features)
返回:
torch.Tensor: 输出张量,形状为 (batch_size, out_features)
"""
# 计算原始线性层的输出
# 计算 LoRA 的调整部分:
# 1. 通过选择器(selector)处理输入
# 2. 通过 LoRA 下层线性层映射到低秩空间
# 3. 应用 Dropout
# 4. 通过 LoRA 上层线性层映射回输出特征空间
# 5. 乘以缩放因子
# 返回原始线性层输出和 LoRA 调整部分的总和
return (
self.linear(input)
+ self.dropout(self.lora_up(self.selector(self.lora_down(input))))
* self.scale
)
def realize_as_lora(self):
"""
获取 LoRA 层的权重,以便进行权重合并或其他操作。
返回:
Tuple[torch.Tensor, torch.Tensor]: 包含 LoRA 上层和下层线性层的权重
"""
return self.lora_up.weight.data * self.scale, self.lora_down.weight.data
def set_selector_from_diag(self, diag: torch.Tensor):
# diag is a 1D tensor of size (r,)
"""
设置选择器为对角矩阵,仅在 LoRA 秩为1时有效。
参数:
diag (torch.Tensor): 1D 张量,形状为 (r,)
"""
# 检查 diag 的形状是否与 LoRA 的秩匹配
assert diag.shape == (self.r,)
# 将选择器定义为线性层,初始化为对角矩阵
self.selector = nn.Linear(self.r, self.r, bias=False)
self.selector.weight.data = torch.diag(diag)
# 将选择器的权重移动到与 LoRA 上层线性层相同的设备和类型
self.selector.weight.data = self.selector.weight.data.to(
self.lora_up.weight.device
).to(self.lora_up.weight.dtype)
class LoraInjectedConv2d(nn.Module):
"""
LoraInjectedConv2d 类是对 PyTorch 中 nn.Conv2d 层的扩展,注入了 LoRA(低秩适应)机制。
LoRA 通过在原始卷积层的基础上添加低秩卷积层来减少可训练参数数量,从而加速训练和推理。
参数:
in_channels (int): 输入通道数。
out_channels (int): 输出通道数。
kernel_size (int 或 tuple): 卷积核大小,可以是单个整数或两个整数的元组。
stride (int 或 tuple, 可选): 卷积步幅,默认为1。
padding (int 或 tuple, 可选): 输入的每条边补充0的层数,默认为0。
dilation (int 或 tuple, 可选): 卷积核元素之间的间距,默认为1。
groups (int, 可选): 输入通道和输出通道的分组数,默认为1。
bias (bool, 可选): 是否使用偏置,默认为True。
r (int, 可选): LoRA 的秩(rank),即低秩矩阵的维度,默认为4。
dropout_p (float, 可选): Dropout 的概率,默认为0.1。
scale (float, 可选): 缩放因子,用于调整 LoRA 的贡献,默认为1.0。
"""
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size,
stride=1,
padding=0,
dilation=1,
groups: int = 1,
bias: bool = True,
r: int = 4,
dropout_p: float = 0.1,
scale: float = 1.0,
):
super().__init__()
# 检查 LoRA 的秩是否超过输入或输出通道的最小值
if r > min(in_channels, out_channels):
raise ValueError(
f"LoRA rank {r} must be less or equal than {min(in_channels, out_channels)}"
)
# 记录 LoRA 的秩
self.r = r
# 定义原始的卷积层
self.conv = nn.Conv2d(
in_channels=in_channels, # 输入通道数
out_channels=out_channels, # 输出通道数
kernel_size=kernel_size, # 卷积核大小
stride=stride, # 卷积步幅
padding=padding, # 输入的每条边补充0的层数
dilation=dilation, # 卷积核元素之间的间距
groups=groups, # 输入通道和输出通道的分组数
bias=bias, # 是否使用偏置
)
# 定义 LoRA 的下层卷积层,将输入通道映射到低秩空间
self.lora_down = nn.Conv2d(
in_channels=in_channels, # 输入通道数
out_channels=r, # 输出通道数为 LoRA 的秩
kernel_size=kernel_size, # 卷积核大小,与原始卷积层相同
stride=stride, # 卷积步幅,与原始卷积层相同
padding=padding, # 输入的每条边补充0的层数,与原始卷积层相同
dilation=dilation, # 卷积核元素之间的间距,与原始卷积层相同
groups=groups, # 分组数,与原始卷积层相同
bias=False, # 不使用偏置
)
# 定义 Dropout 层,防止过拟合并增加模型的泛化能力
self.dropout = nn.Dropout(dropout_p)
# 定义 LoRA 的上层卷积层,将低秩空间的表示映射回输出通道空间
self.lora_up = nn.Conv2d(
in_channels=r, # 输入通道数为 LoRA 的秩
out_channels=out_channels, # 输出通道数与原始卷积层相同
kernel_size=1, # 卷积核大小为1x1
stride=1, # 卷积步幅为1
padding=0, # 不进行填充
bias=False, # 不使用偏置
)
# 定义选择器(selector),这里使用恒等映射(Identity),后续可以自定义
self.selector = nn.Identity()
# 定义缩放因子,用于调整 LoRA 的贡献
self.scale = scale
# 初始化 LoRA 下层卷积层的权重,使用正态分布,标准差为 1/r
nn.init.normal_(self.lora_down.weight, std=1 / r)
# 初始化 LoRA 上层卷积层的权重为零
nn.init.zeros_(self.lora_up.weight)
def forward(self, input):
"""
前向传播函数,计算卷积变换和 LoRA 调整的总和。
参数:
input (torch.Tensor): 输入张量,形状为 (batch_size, in_channels, H, W)
返回:
torch.Tensor: 输出张量,形状为 (batch_size, out_channels, H', W')
"""
# 计算原始卷积层的输出
# 计算 LoRA 的调整部分:
# 1. 通过选择器(selector)处理输入
# 2. 通过 LoRA 下层卷积层映射到低秩空间
# 3. 应用 Dropout
# 4. 通过 LoRA 上层卷积层映射回输出通道空间
# 5. 乘以缩放因子
# 返回原始卷积层输出和 LoRA 调整部分的总和
return (
self.conv(input)
+ self.dropout(self.lora_up(self.selector(self.lora_down(input))))
* self.scale
)
def realize_as_lora(self):
"""
获取 LoRA 层的权重,以便进行权重合并或其他操作。
返回:
Tuple[torch.Tensor, torch.Tensor]: 包含 LoRA 上层和下层卷积层的权重
"""
return self.lora_up.weight.data * self.scale, self.lora_down.weight.data
def set_selector_from_diag(self, diag: torch.Tensor):
"""
设置选择器为对角矩阵,仅在 LoRA 秩为1时有效。
参数:
diag (torch.Tensor): 1D 张量,形状为 (r,)
异常:
AssertionError: 如果 diag 的形状不等于 (r,)
"""
# 检查 diag 的形状是否与 LoRA 的秩匹配
# diag is a 1D tensor of size (r,)
assert diag.shape == (self.r,)
# 将选择器定义为1x1卷积层,初始化为对角矩阵
self.selector = nn.Conv2d(
in_channels=self.r, # 输入通道数为 LoRA 的秩
out_channels=self.r, # 输出通道数也为 LoRA 的秩
kernel_size=1, # 卷积核大小为1x1
stride=1, # 卷积步幅为1
padding=0, # 不进行填充
bias=False, # 不使用偏置
)
# 将选择器的权重设置为对角矩阵
self.selector.weight.data = torch.diag(diag)
# same device + dtype as lora_up
# 将选择器的权重移动到与 LoRA 上层卷积层相同的设备和类型
self.selector.weight.data = self.selector.weight.data.to(
self.lora_up.weight.device
).to(self.lora_up.weight.dtype)
UNET_DEFAULT_TARGET_REPLACE = {"CrossAttention", "Attention", "GEGLU"}
UNET_EXTENDED_TARGET_REPLACE = {"ResnetBlock2D", "CrossAttention", "Attention", "GEGLU"}
TEXT_ENCODER_DEFAULT_TARGET_REPLACE = {"CLIPAttention"}
TEXT_ENCODER_EXTENDED_TARGET_REPLACE = {"CLIPAttention"}
DEFAULT_TARGET_REPLACE = UNET_DEFAULT_TARGET_REPLACE
EMBED_FLAG = "<embed>"
def _find_children(
model,
search_class: List[Type[nn.Module]] = [nn.Linear],
):
"""
查找模型中所有属于特定类(或类的组合)的子模块。
返回所有匹配的子模块,以及这些子模块的父模块和它们被引用的名称。
参数:
model (nn.Module): 需要搜索的 PyTorch 模型。
search_class (List[Type[nn.Module]], 可选): 要搜索的模块类列表,默认为 [nn.Linear]。
返回:
Generator[Tuple[nn.Module, str, nn.Module]]: 一个生成器,生成包含父模块、名称和子模块的元组。
"""
# 遍历模型中的每个父模块
for parent in model.modules():
for name, module in parent.named_children():
if any([isinstance(module, _class) for _class in search_class]):
yield parent, name, module
def _find_modules_v2(
model,
ancestor_class: Optional[Set[str]] = None,
search_class: List[Type[nn.Module]] = [nn.Linear],
exclude_children_of: Optional[List[Type[nn.Module]]] = [
LoraInjectedLinear,
LoraInjectedConv2d,
],
):
"""
查找所有属于特定类(或类的组合)的模块,这些模块是其他特定类(或类的组合)模块的直接或间接后代。
返回所有匹配的模块,以及这些模块的父模块和它们被引用的名称。
参数:
model (nn.Module): 需要搜索的 PyTorch 模型。
ancestor_class (Optional[Set[str]], 可选): 祖先模块的类名集合,如果为 None,则遍历所有模块。
search_class (List[Type[nn.Module]], 可选): 要搜索的模块类列表,默认为 [nn.Linear]。
exclude_children_of (Optional[List[Type[nn.Module]]], 可选): 要排除的子模块类列表,默认为 [LoraInjectedLinear, LoraInjectedConv2d]。
返回:
Generator[Tuple[nn.Module, str, nn.Module]]: 一个生成器,生成包含父模块、名称和子模块的元组。
"""
# Get the targets we should replace all linears under
if ancestor_class is not None:
ancestors = (
module
for module in model.modules()
if module.__class__.__name__ in ancestor_class
)
else:
# this, incase you want to naively iterate over all modules.
ancestors = [module for module in model.modules()]
# For each target find every linear_class module that isn't a child of a LoraInjectedLinear
for ancestor in ancestors:
for fullname, module in ancestor.named_modules():
if any([isinstance(module, _class) for _class in search_class]):
# Find the direct parent if this is a descendant, not a child, of target
*path, name = fullname.split(".")
parent = ancestor
while path:
parent = parent.get_submodule(path.pop(0))
# Skip this linear if it's a child of a LoraInjectedLinear
if exclude_children_of and any(
[isinstance(parent, _class) for _class in exclude_children_of]
):
continue
# Otherwise, yield it
yield parent, name, module
def _find_modules_old(
model,
ancestor_class: Set[str] = DEFAULT_TARGET_REPLACE,
search_class: List[Type[nn.Module]] = [nn.Linear],
exclude_children_of: Optional[List[Type[nn.Module]]] = [LoraInjectedLinear],
):
ret = []
for _module in model.modules():
if _module.__class__.__name__ in ancestor_class:
for name, _child_module in _module.named_modules():
if _child_module.__class__ in search_class:
ret.append((_module, name, _child_module))
print(ret)
return ret
_find_modules = _find_modules_v2
def inject_trainable_lora(
model: nn.Module,
target_replace_module: Set[str] = DEFAULT_TARGET_REPLACE,
r: int = 4,
loras=None, # path to lora .pt
verbose: bool = False,
dropout_p: float = 0.0,
scale: float = 1.0,
):
"""
将 LoRA 注入到模型中,并返回需要训练的 LoRA 参数组。
参数:
model (nn.Module): 需要注入 LoRA 的 PyTorch 模型。
target_replace_module (Set[str], 可选): 需要替换的目标模块名称集合,默认为 DEFAULT_TARGET_REPLACE。
r (int, 可选): LoRA 的秩(rank),即低秩矩阵的维度,默认为4。
loras (str, 可选): LoRA 权重文件的路径(.pt 文件),如果为 None,则不加载预训练的 LoRA 权重。
verbose (bool, 可选): 是否打印详细信息,默认为 False。
dropout_p (float, 可选): Dropout 的概率,默认为0.0。
scale (float, 可选): 缩放因子,用于调整 LoRA 的贡献,默认为1.0。
返回:
Tuple[List[Parameter], List[str]]: 包含需要训练的 LoRA 参数组的列表和模块名称的列表。
"""
# 初始化需要训练的参数列表和模块名称列表
require_grad_params = []
names = []
# 如果提供了 LoRA 权重文件路径,则加载 LoRA 权重
if loras != None:
loras = torch.load(loras)
# 遍历模型中所有需要替换的目标模块
for _module, name, _child_module in _find_modules(
model, target_replace_module, search_class=[nn.Linear]
):
# 获取当前线性层的权重和偏置
weight = _child_module.weight
bias = _child_module.bias
if verbose:
print("LoRA Injection : injecting lora into ", name)
print("LoRA Injection : weight shape", weight.shape)
# 创建 LoraInjectedLinear 实例,替换原始的线性层
_tmp = LoraInjectedLinear(
_child_module.in_features, # 输入特征的维度
_child_module.out_features, # 输出特征的维度
_child_module.bias is not None, # 是否使用偏置
r=r, # LoRA 的秩
dropout_p=dropout_p, # Dropout 的概率
scale=scale, # 缩放因子
)
# 将原始线性层的权重赋值给新的 LoRA 线性层
_tmp.linear.weight = weight
# 如果存在偏置,则将偏置也赋值给新的 LoRA 线性层
if bias is not None:
_tmp.linear.bias = bias
# switch the module
# 将新的 LoRA 线性层移动到与原始模块相同的设备和类型
_tmp.to(_child_module.weight.device).to(_child_module.weight.dtype)
# 替换模型中的原始模块为新的 LoRA 模块
_module._modules[name] = _tmp
# 将 LoRA 层的可训练参数添加到参数列表中
require_grad_params.append(_module._modules[name].lora_up.parameters())
require_grad_params.append(_module._modules[name].lora_down.parameters())
# 如果提供了 LoRA 权重文件,则加载预训练的 LoRA 权重
if loras != None:
_module._modules[name].lora_up.weight = loras.pop(0)
_module._modules[name].lora_down.weight = loras.pop(0)
# 设置 LoRA 层的权重为可训练
_module._modules[name].lora_up.weight.requires_grad = True
_module._modules[name].lora_down.weight.requires_grad = True
# 将模块名称添加到名称列表中
names.append(name)
# 返回需要训练的参数组和模块名称
return require_grad_params, names
def inject_trainable_lora_extended(
model: nn.Module,
target_replace_module: Set[str] = UNET_EXTENDED_TARGET_REPLACE,
r: int = 4,
loras=None, # path to lora .pt
):
"""
将 LoRA 注入到模型中,并返回需要训练的 LoRA 参数组。此函数支持线性层和卷积层。
参数:
model (nn.Module): 需要注入 LoRA 的 PyTorch 模型。
target_replace_module (Set[str], 可选): 需要替换的目标模块名称集合,默认为 UNET_EXTENDED_TARGET_REPLACE。
r (int, 可选): LoRA 的秩(rank),即低秩矩阵的维度,默认为4。
loras (str, 可选): LoRA 权重文件的路径(.pt 文件),如果为 None,则不加载预训练的 LoRA 权重。
返回:
Tuple[List[Parameter], List[str]]: 包含需要训练的 LoRA 参数组的列表和模块名称的列表。
"""
# 初始化需要训练的参数列表和模块名称列表
require_grad_params = []
names = []
# 如果提供了 LoRA 权重文件路径,则加载 LoRA 权重
if loras != None:
loras = torch.load(loras)
# 遍历模型中所有需要替换的目标模块
for _module, name, _child_module in _find_modules(
model, target_replace_module, search_class=[nn.Linear, nn.Conv2d]
):
# 如果当前模块是线性层
if _child_module.__class__ == nn.Linear:
weight = _child_module.weight
bias = _child_module.bias
# 创建 LoraInjectedLinear 实例,替换原始的线性层
_tmp = LoraInjectedLinear(
_child_module.in_features, # 输入特征的维度
_child_module.out_features, # 输出特征的维度
_child_module.bias is not None, # 是否使用偏置
r=r, # LoRA 的秩
)
# 将原始线性层的权重赋值给新的 LoRA 线性层
_tmp.linear.weight = weight
# 如果存在偏置,则将偏置也赋值给新的 LoRA 线性层
if bias is not None:
_tmp.linear.bias = bias
# 如果当前模块是卷积层
elif _child_module.__class__ == nn.Conv2d:
weight = _child_module.weight
bias = _child_module.bias
# 创建 LoraInjectedConv2d 实例,替换原始的卷积层
_tmp = LoraInjectedConv2d(
_child_module.in_channels, # 输入通道数
_child_module.out_channels, # 输出通道数
_child_module.kernel_size, # 卷积核大小
_child_module.stride, # 卷积步幅
_child_module.padding, # 填充大小
_child_module.dilation, # 扩张率
_child_module.groups, # 分组数
_child_module.bias is not None, # 是否使用偏置
r=r, # LoRA 的秩
)
# 将原始卷积层的权重赋值给新的 LoRA 卷积层
_tmp.conv.weight = weight
# 如果存在偏置,则将偏置也赋值给新的 LoRA 卷积层
if bias is not None:
_tmp.conv.bias = bias
# switch the module
# 将新的 LoRA 模块移动到与原始模块相同的设备和类型
_tmp.to(_child_module.weight.device).to(_child_module.weight.dtype)
if bias is not None:
_tmp.to(_child_module.bias.device).to(_child_module.bias.dtype)
# 替换模型中的原始模块为新的 LoRA 模块
_module._modules[name] = _tmp
# 将 LoRA 层的可训练参数添加到参数列表中
require_grad_params.append(_module._modules[name].lora_up.parameters())
require_grad_params.append(_module._modules[name].lora_down.parameters())
# 如果提供了 LoRA 权重文件,则加载预训练的 LoRA 权重
if loras != None:
_module._modules[name].lora_up.weight = loras.pop(0)
_module._modules[name].lora_down.weight = loras.pop(0)
# 设置 LoRA 层的权重为可训练
_module._modules[name].lora_up.weight.requires_grad = True
_module._modules[name].lora_down.weight.requires_grad = True
# 将模块名称添加到名称列表中
names.append(name)
# 返回需要训练的参数组和模块名称
return require_grad_params, names
def extract_lora_ups_down(model, target_replace_module=DEFAULT_TARGET_REPLACE):
"""
从模型中提取所有注入的 LoRA 层的上 (lora_up) 和下 (lora_down) 层。
参数:
model (nn.Module): 包含已注入 LoRA 层的 PyTorch 模型。
target_replace_module (Set[str], 可选): 需要替换的目标模块名称集合,默认为 DEFAULT_TARGET_REPLACE。
返回:
List[Tuple[nn.Module, nn.Module]]: 包含所有 LoRA 层的上 (lora_up) 和下 (lora_down) 层的元组列表。
异常:
ValueError: 如果模型中没有注入任何 LoRA 层,则抛出此异常。
"""
# 初始化一个空列表,用于存储 LoRA 层的上 (lora_up) 和下 (lora_down) 层
loras = []
# 遍历模型中所有需要替换的目标模块,查找已注入的 LoRA 层
for _m, _n, _child_module in _find_modules(
model,
target_replace_module,
search_class=[LoraInjectedLinear, LoraInjectedConv2d],
):
# 将每个 LoRA 层的上 (lora_up) 和下 (lora_down) 层添加到列表中
loras.append((_child_module.lora_up, _child_module.lora_down))
# 如果没有找到任何 LoRA 层,则抛出 ValueError 异常
if len(loras) == 0:
raise ValueError("No lora injected.")
# 返回包含所有 LoRA 层的上 (lora_up) 和下 (lora_down) 层的元组列表
return loras
def extract_lora_as_tensor(
model, target_replace_module=DEFAULT_TARGET_REPLACE, as_fp16=True
):
"""
从模型中提取所有注入的 LoRA 层的上 (lora_up) 和下 (lora_down) 层,并将它们转换为张量。
参数:
model (nn.Module): 包含已注入 LoRA 层的 PyTorch 模型。
target_replace_module (Set[str], 可选): 需要替换的目标模块名称集合,默认为 DEFAULT_TARGET_REPLACE。
as_fp16 (bool, 可选): 是否将权重转换为 float16 类型,默认为 True。
返回:
List[Tuple[torch.Tensor, torch.Tensor]]: 包含所有 LoRA 层的上 (lora_up) 和下 (lora_down) 层的张量元组列表。
异常:
ValueError: 如果模型中没有注入任何 LoRA 层,则抛出此异常。
"""
# 初始化一个空列表,用于存储 LoRA 层的上 (lora_up) 和下 (lora_down) 层张量
loras = []
# 遍历模型中所有需要替换的目标模块,查找已注入的 LoRA 层
for _m, _n, _child_module in _find_modules(
model,
target_replace_module,
search_class=[LoraInjectedLinear, LoraInjectedConv2d], # 搜索的模块类为 LoraInjectedLinear 和 LoraInjectedConv2d
):
# 获取 LoRA 层的上 (lora_up) 和下 (lora_down) 层的权重张量
up, down = _child_module.realize_as_lora()
# 如果需要,将权重转换为 float16 类型
if as_fp16:
up = up.to(torch.float16)
down = down.to(torch.float16)
# 将上 (lora_up) 和下 (lora_down) 层的权重张量添加到列表中
loras.append((up, down))
# 如果没有找到任何 LoRA 层,则抛出 ValueError 异常
if len(loras) == 0:
raise ValueError("No lora injected.")
# 返回包含所有 LoRA 层的上 (lora_up) 和下 (lora_down) 层的张量元组列表
return loras
def save_lora_weight(
model,
path="./lora.pt",
target_replace_module=DEFAULT_TARGET_REPLACE,
):
"""
将模型中所有注入的 LoRA 层的权重保存到指定的文件中。
参数:
model (nn.Module): 包含已注入 LoRA 层的 PyTorch 模型。
path (str, 可选): 保存 LoRA 权重的文件路径,默认为 "./lora.pt"。
target_replace_module (Set[str], 可选): 需要替换的目标模块名称集合,默认为 DEFAULT_TARGET_REPLACE。
异常:
ValueError: 如果模型中没有注入任何 LoRA 层,则抛出此异常。
"""
# 初始化一个空列表,用于存储 LoRA 层的权重
weights = []
# 提取所有注入的 LoRA 层的上 (lora_up) 和下 (lora_down) 层
for _up, _down in extract_lora_ups_down(
model, target_replace_module=target_replace_module
):
# 将上 (lora_up) 和下 (lora_down) 层的权重转换为 float16 类型并移动到 CPU
weights.append(_up.weight.to("cpu").to(torch.float16))
weights.append(_down.weight.to("cpu").to(torch.float16))
# 将权重列表保存到指定的文件中
torch.save(weights, path)
def save_lora_as_json(model, path="./lora.json"):
"""
将模型中所有注入的 LoRA 层的权重保存为 JSON 格式的文件。
参数:
model (nn.Module): 包含已注入 LoRA 层的 PyTorch 模型。
path (str, 可选): 保存 LoRA 权重的 JSON 文件路径,默认为 "./lora.json"。
异常:
ValueError: 如果模型中没有注入任何 LoRA 层,则抛出此异常。
"""
# 初始化一个空列表,用于存储 LoRA 层的权重
weights = []
# 提取所有注入的 LoRA 层的上 (lora_up) 和下 (lora_down) 层
for _up, _down in extract_lora_ups_down(model):
# 将上 (lora_up) 和下 (lora_down) 层的权重转换为 NumPy 数组并转换为列表
weights.append(_up.weight.detach().cpu().numpy().tolist())
weights.append(_down.weight.detach().cpu().numpy().tolist())
import json
# 将权重列表写入指定的 JSON 文件中
with open(path, "w") as f:
json.dump(weights, f)
def save_safeloras_with_embeds(
modelmap: Dict[str, Tuple[nn.Module, Set[str]]] = {},
embeds: Dict[str, torch.Tensor] = {},
outpath="./lora.safetensors",
):
"""
将多个模块中的 LoRA 权重保存到一个单独的 safetensor 文件中。
modelmap 是一个字典,格式为 {
"模块名称": (模型, 目标替换模块集合)
}
参数:
modelmap (Dict[str, Tuple[nn.Module, Set[str]]], 可选): 模型映射字典,默认为空字典。
embeds (Dict[str, torch.Tensor], 可选): 嵌入字典,默认为空字典。
outpath (str, 可选): 输出文件路径,默认为 "./lora.safetensors"。
"""
# 初始化权重字典和元数据字典
weights = {}
metadata = {}
# 遍历模型映射字典中的每个模块
for name, (model, target_replace_module) in modelmap.items():
# 将目标替换模块集合转换为 JSON 字符串并存储在元数据字典中
metadata[name] = json.dumps(list(target_replace_module))
# 提取所有注入的 LoRA 层的上 (lora_up) 和下 (lora_down) 层
for i, (_up, _down) in enumerate(
extract_lora_as_tensor(model, target_replace_module)
):
# 获取 LoRA 层的秩(rank)
rank = _down.shape[0]
# 将秩存储在元数据字典中
metadata[f"{name}:{i}:rank"] = str(rank)
# 将上 (lora_up) 和下 (lora_down) 层的张量添加到权重字典中
weights[f"{name}:{i}:up"] = _up
weights[f"{name}:{i}:down"] = _down
# 遍历嵌入字典中的每个 token
for token, tensor in embeds.items():
# 将嵌入标志存储在元数据字典中
metadata[token] = EMBED_FLAG
# 将嵌入张量添加到权重字典中
weights[token] = tensor
print(f"Saving weights to {outpath}")
# 调用 safe_save 函数,将权重和元数据保存到指定的 safetensors 文件中
safe_save(weights, outpath, metadata)
def save_safeloras(
modelmap: Dict[str, Tuple[nn.Module, Set[str]]] = {},
outpath="./lora.safetensors",
):
"""
将多个模块中的 LoRA 权重保存到一个单独的 safetensor 文件中。
参数:
modelmap (Dict[str, Tuple[nn.Module, Set[str]]], 可选): 模型映射字典,默认为空字典。
outpath (str, 可选): 输出文件路径,默认为 "./lora.safetensors"。
"""
# 调用 save_safeloras_with_embeds 函数,嵌入字典为空字典
return save_safeloras_with_embeds(modelmap=modelmap, outpath=outpath)
def convert_loras_to_safeloras_with_embeds(
modelmap: Dict[str, Tuple[str, Set[str], int]] = {},
embeds: Dict[str, torch.Tensor] = {},
outpath="./lora.safetensors",
):
"""
将多个 PyTorch.pt 文件中的 LoRA 转换为单个 safetensor 文件。
modelmap 是一个字典,格式为 {
"模块名称": (PyTorch模型路径, 目标替换模块集合, LoRA秩)
}
参数:
modelmap (Dict[str, Tuple[str, Set[str], int]], 可选): 模型映射字典,键为模块名称,值为 (PyTorch模型路径, 目标替换模块集合, LoRA秩) 的元组,默认为空字典。
embeds (Dict[str, torch.Tensor], 可选): 嵌入字典,键为 token,值为对应的张量,默认为空字典。
outpath (str, 可选): 输出文件路径,默认为 "./lora.safetensors"。
"""
# 初始化权重字典和元数据字典
weights = {}
metadata = {}
# 遍历模型映射字典中的每个模块
for name, (path, target_replace_module, r) in modelmap.items():
# 将目标替换模块集合转换为 JSON 字符串并存储在元数据字典中
metadata[name] = json.dumps(list(target_replace_module))
# 加载 LoRA 权重文件
lora = torch.load(path)
# 遍历 LoRA 权重列表
for i, weight in enumerate(lora):
# 判断当前权重是上 (lora_up) 还是下 (lora_down) 层
is_up = i % 2 == 0
# 计算索引
i = i // 2
if is_up:
# 如果是上 (lora_up) 层,记录秩并存储权重
metadata[f"{name}:{i}:rank"] = str(r)
weights[f"{name}:{i}:up"] = weight
else:
# 如果是下 (lora_down) 层,存储权重
weights[f"{name}:{i}:down"] = weight
# 遍历嵌入字典中的每个 token
for token, tensor in embeds.items():
# 将嵌入标志存储在元数据字典中
metadata[token] = EMBED_FLAG
# 将嵌入张量添加到权重字典中
weights[token] = tensor
print(f"Saving weights to {outpath}")
# 调用 safe_save 函数,将权重和元数据保存到指定的 safetensor 文件中
safe_save(weights, outpath, metadata)
def convert_loras_to_safeloras(
modelmap: Dict[str, Tuple[str, Set[str], int]] = {},
outpath="./lora.safetensors",
):
"""
将多个 PyTorch.pt 文件中的 LoRA 转换为单个 safetensor 文件。
参数:
modelmap (Dict[str, Tuple[str, Set[str], int]], 可选): 模型映射字典,键为模块名称,值为 (PyTorch模型路径, 目标替换模块集合, LoRA秩) 的元组,默认为空字典。
outpath (str, 可选): 输出文件路径,默认为 "./lora.safetensors"。
"""
# 调用 convert_loras_to_safeloras_with_embeds 函数,嵌入字典为空字典
convert_loras_to_safeloras_with_embeds(modelmap=modelmap, outpath=outpath)
def parse_safeloras(
safeloras,
) -> Dict[str, Tuple[List[nn.parameter.Parameter], List[int], List[str]]]:
"""
将加载的包含一组模块 LoRA 的 safetensor 文件转换为参数和其他信息。
输出是一个字典,格式为 {
"模块名称": (
[权重列表],
[秩列表],
目标替换模块集合
)
}
参数:
safeloras: 已加载的包含 LoRA 的 safetensor 文件。
返回:
Dict[str, Tuple[List[nn.parameter.Parameter], List[int], List[str]]]: 包含 LoRA 参数、秩和目标替换模块集合的字典。
"""
# 初始化 LoRA 字典
loras = {}
# 获取 safetensor 文件的元数据
metadata = safeloras.metadata()
# 定义一个 lambda 函数,用于提取模块名称
get_name = lambda k: k.split(":")[0]
# 获取所有键并按键排序
keys = list(safeloras.keys())
keys.sort(key=get_name)
# 按模块名称对键进行分组
for name, module_keys in groupby(keys, get_name):
# 获取模块的元数据
info = metadata.get(name)
# 如果没有元数据,则抛出 ValueError 异常
if not info:
raise ValueError(
f"Tensor {name} has no metadata - is this a Lora safetensor?"
)
# 如果元数据是嵌入标志,则跳过(假设这是文本嵌入)
if info == EMBED_FLAG:
continue
# 处理 LoRA
# 解析目标替换模块集合
target = json.loads(info)
# 初始化秩列表和权重列表
module_keys = list(module_keys)
ranks = [4] * (len(module_keys) // 2)
weights = [None] * len(module_keys)
# 遍历模块键
for key in module_keys:
# 分割键以提取模块名称、索引和方向(up 或 down)
_, idx, direction = key.split(":")
idx = int(idx)
# 获取秩并存储在秩列表中
ranks[idx] = int(metadata[f"{name}:{idx}:rank"])
# 计算索引并存储权重
idx = idx * 2 + (1 if direction == "down" else 0)
weights[idx] = nn.parameter.Parameter(safeloras.get_tensor(key))
# 将模块名称、权重列表、秩列表和目标替换模块集合添加到 LoRA 字典中
loras[name] = (weights, ranks, target)
return loras
def parse_safeloras_embeds(
safeloras,
) -> Dict[str, torch.Tensor]:
"""
将加载的包含文本嵌入的 safetensor 文件转换为字典,格式为 embed_token: Tensor。
参数:
safeloras: 已加载的包含文本嵌入的 safetensor 文件。
返回:
Dict[str, torch.Tensor]: 包含嵌入 token 和对应张量的字典。
"""
# 初始化嵌入字典
embeds = {}
# 获取 safetensor 文件的元数据
metadata = safeloras.metadata()
# 遍历所有键
for key in safeloras.keys():
# 获取元数据
meta = metadata.get(key)
# 如果元数据不存在或不是嵌入标志,则跳过
if not meta or meta != EMBED_FLAG:
continue
# 将嵌入张量添加到嵌入字典中
embeds[key] = safeloras.get_tensor(key)
return embeds
def load_safeloras(path, device="cpu"):
"""
从指定的 safetensor 文件中加载 LoRA,并解析为参数和其他信息。
参数:
path (str): 包含 LoRA 的 safetensor 文件路径。
device (str, 可选): 设备类型,默认为 "cpu"。
返回:
Dict[str, Tuple[List[nn.parameter.Parameter], List[int], List[str]]]:
一个字典,键为模块名称,值为包含权重列表、秩列表和目标替换模块集合的元组。
"""
# 使用 safe_open 函数打开 safetensor 文件,并指定框架为 "pt"(PyTorch)和设备类型
safeloras = safe_open(path, framework="pt", device=device)
# 解析 safetensor 文件中的 LoRA 信息
return parse_safeloras(safeloras)
def load_safeloras_embeds(path, device="cpu"):
"""
从指定的 safetensor 文件中加载文本嵌入,并解析为字典。
参数:
path (str): 包含嵌入的 safetensor 文件路径。
device (str, 可选): 设备类型,默认为 "cpu"。
返回:
Dict[str, torch.Tensor]: 一个字典,键为嵌入 token,值为对应的张量。
"""
# 使用 safe_open 函数打开 safetensor 文件,并指定框架为 "pt"(PyTorch)和设备类型
safeloras = safe_open(path, framework="pt", device=device)
# 解析 safetensor 文件中的嵌入信息
return parse_safeloras_embeds(safeloras)
def load_safeloras_both(path, device="cpu"):
"""
从指定的 safetensor 文件中同时加载 LoRA 和文本嵌入,并解析为相应的数据结构。
参数:
path (str): 包含 LoRA 和嵌入的 safetensor 文件路径。
device (str, 可选): 设备类型,默认为 "cpu"。
返回:
Tuple[Dict[str, Tuple[List[nn.parameter.Parameter], List[int], List[str]]], Dict[str, torch.Tensor]]:
一个元组,包含两个字典:
- 第一个字典包含 LoRA 信息,键为模块名称,值为包含权重列表、秩列表和目标替换模块集合的元组。
- 第二个字典包含嵌入信息,键为嵌入 token,值为对应的张量。
"""
# 使用 safe_open 函数打开 safetensor 文件,并指定框架为 "pt"(PyTorch)和设备类型
safeloras = safe_open(path, framework="pt", device=device)
# 解析 safetensor 文件中的 LoRA 和嵌入信息
return parse_safeloras(safeloras), parse_safeloras_embeds(safeloras)