-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpeft.py
More file actions
402 lines (386 loc) · 19.8 KB
/
peft.py
File metadata and controls
402 lines (386 loc) · 19.8 KB
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
import torch
import numpy as np
import functools
from dataclasses import dataclass
import draccus
@dataclass
class PeftStrategyConfig(draccus.ChoiceRegistry):
pass
@PeftStrategyConfig.register_subclass('full')
@dataclass
class FullFineTuneConfig(PeftStrategyConfig):
def wrap(self,model):
return model
# works for gemma
def wrap_linear(model,f):
for param in model.parameters():
param.requires_grad = False
for layer in model.model.layers:
layer.self_attn.q_proj = f(layer.self_attn.q_proj)
layer.self_attn.k_proj = f(layer.self_attn.k_proj)
layer.self_attn.v_proj = f(layer.self_attn.v_proj)
layer.self_attn.o_proj = f(layer.self_attn.o_proj)
layer.mlp.gate_proj = f(layer.mlp.gate_proj)
layer.mlp.up_proj = f(layer.mlp.up_proj)
layer.mlp.down_proj = f(layer.mlp.down_proj)
# need to do this simultaneously with lm_head and embedding
# model.lm_head = f(model.lm_head)
return model
def wrap_like_linear(model,f_factory):
for param in model.parameters():
param.requires_grad = False
f = f_factory(model.model.layers[0].self_attn.q_proj.in_features,
model.model.layers[0].self_attn.q_proj.out_features)
for layer in model.model.layers:
layer.self_attn.q_proj = f(layer.self_attn.q_proj)
f = f_factory(model.model.layers[0].self_attn.k_proj.in_features,
model.model.layers[0].self_attn.k_proj.out_features)
for layer in model.model.layers:
layer.self_attn.k_proj = f(layer.self_attn.k_proj)
f = f_factory(model.model.layers[0].self_attn.v_proj.in_features,
model.model.layers[0].self_attn.v_proj.out_features)
for layer in model.model.layers:
layer.self_attn.v_proj = f(layer.self_attn.v_proj)
f = f_factory(model.model.layers[0].self_attn.o_proj.in_features,
model.model.layers[0].self_attn.o_proj.out_features)
for layer in model.model.layers:
layer.self_attn.o_proj = f(layer.self_attn.o_proj)
f = f_factory(model.model.layers[0].mlp.gate_proj.in_features,
model.model.layers[0].mlp.gate_proj.out_features)
for layer in model.model.layers:
layer.mlp.gate_proj = f(layer.mlp.gate_proj)
f = f_factory(model.model.layers[0].mlp.up_proj.in_features,
model.model.layers[0].mlp.up_proj.out_features)
for layer in model.model.layers:
layer.mlp.up_proj = f(layer.mlp.up_proj)
f = f_factory(model.model.layers[0].mlp.down_proj.in_features,
model.model.layers[0].mlp.down_proj.out_features)
for layer in model.model.layers:
layer.mlp.down_proj = f(layer.mlp.down_proj)
return model
# considers a set of n linear parameters as a three place tensor of shape
# (in_features, out_features, n). We implicitly embed a tensor of shape (a,b,l)
# here defining our fine tune (consider a << in_features, b << out_features, l
# << n). For the special case l = n, a simpler implementation without loss of
# expressivity is avaiable in get_tied_lora_extra_wrapper
def create_tensor_embedding_wrapper(in_features, out_features, a, b, l, premult, postmult, dtype, alpha, gamma):
T = torch.nn.Parameter(torch.randn(a, b, l, dtype=dtype) / gamma)
A = torch.nn.Parameter(torch.randn(a, in_features, dtype=dtype) / gamma)
B = torch.nn.Parameter(torch.zeros(b, out_features, dtype=dtype))
class LinearWithTensorEmbedding(torch.nn.Module):
def __init__(self, linear, T, A, B):
super().__init__()
assert linear.bias is None
assert linear.weight.dtype is dtype
self.linear = linear
self.T = T
self.A = A
self.B = B
self.M = torch.nn.Parameter(torch.randn(l, dtype=dtype) / gamma)
self.norm = float(np.sqrt(self.linear.weight.float().pow(2).mean()))
if premult:
self.pre = torch.nn.Parameter(torch.ones(in_features,dtype=dtype) / gamma)
if postmult:
self.post = torch.nn.Parameter(torch.ones(out_features,dtype=dtype) / gamma)
def forward(self, x):
return self.linear(x) + gamma**(3+(1 if premult else 0)+(1 if postmult else 0)) * alpha * self.norm / np.sqrt(a*b*l) *\
torch.einsum('...i,ai,bo,l,abl,i,o->...o', x, self.A, self.B, self.M, self.T,
self.pre if premult else torch.ones((1,),dtype=dtype),
self.post if postmult else torch.ones((1,),dtype=dtype))
return functools.partial(LinearWithTensorEmbedding, T=T, A=A, B=B)
@PeftStrategyConfig.register_subclass('tensor_embedding')
@dataclass
class TensorEmbeddingConfig(PeftStrategyConfig):
a: int = 16
b: int = 16
l: int = 8
premult: bool = False
postmult: bool = False
alpha: float = 100.
gamma: float = 750.
def wrap(self,model):
return wrap_like_linear(model, functools.partial(create_tensor_embedding_wrapper, a=self.a, b=self.b, l=self.l,
premult=self.premult, postmult=self.postmult, dtype=model.dtype,
alpha=self.alpha, gamma=self.gamma))
def create_tied_lora_extra_wrapper(in_features, out_features, a, b, premult, postmult, dtype, alpha, gamma):
A = torch.nn.Parameter(torch.randn(a, in_features, dtype=dtype) / gamma)
B = torch.nn.Parameter(torch.zeros(b, out_features, dtype=dtype))
class LinearWithTiedLoraExtra(torch.nn.Module):
def __init__(self, linear, A, B):
super().__init__()
assert linear.bias is None
assert linear.weight.dtype is dtype
self.linear = linear
self.A = A
self.B = B
self.M = torch.nn.Parameter(torch.randn(a, b, dtype=dtype) / gamma)
self.norm = float(np.sqrt(self.linear.weight.float().pow(2).mean()))
if premult:
self.pre = torch.nn.Parameter(torch.ones(in_features,dtype=dtype) / gamma)
if postmult:
self.post = torch.nn.Parameter(torch.ones(out_features,dtype=dtype) / gamma)
def forward(self, x):
return self.linear(x) + gamma**(2+(1 if premult else 0)+(1 if postmult else 0)) * alpha * self.norm / np.sqrt(a*b) *\
torch.einsum('...i,ai,ab,bo,i,o->...o', x, self.A, self.M, self.B,
self.pre if premult else torch.ones((1,),dtype=dtype),
self.post if postmult else torch.ones((1,),dtype=dtype))
return functools.partial(LinearWithTiedLoraExtra, A=A, B=B)
@PeftStrategyConfig.register_subclass('tied_lora_extra')
@dataclass
class TiedLoraExtraConfig(PeftStrategyConfig):
a: int = 16
b: int = 16
premult: bool = False
postmult: bool = False
alpha: float = 100.
gamma: float = 750.
def wrap(self,model):
return wrap_like_linear(model, functools.partial(create_tied_lora_extra_wrapper, a=self.a, b=self.b,
premult=self.premult, postmult=self.postmult,
dtype=model.dtype, alpha=self.alpha, gamma=self.gamma))
def create_tied_lora_wrapper(in_features, out_features, r, premult, midmult, postmult, dtype, alpha, gamma):
A = torch.nn.Parameter(torch.randn(in_features, r, dtype=dtype) / gamma)
B = torch.nn.Parameter(torch.zeros(r, out_features, dtype=dtype))
class LinearWithTiedLora(torch.nn.Module):
def __init__(self, linear, A, B):
super().__init__()
assert linear.bias is None
assert linear.weight.dtype is dtype
self.linear = linear
self.A = A
self.B = B
self.norm = float(np.sqrt(self.linear.weight.float().pow(2).mean()))
if premult:
self.pre = torch.nn.Parameter(torch.ones(in_features,dtype=dtype) / gamma)
if midmult:
self.mid = torch.nn.Parameter(torch.ones(r,dtype=dtype) / gamma)
if postmult:
self.post = torch.nn.Parameter(torch.ones(out_features,dtype=dtype) / gamma)
def forward(self, x):
return self.linear(x) + gamma**(2+(1 if premult else 0)+(0 if midmult else 1)+(1 if postmult else 0)) * alpha * self.norm / np.sqrt(r) *\
torch.einsum('...i,ir,ro,i,r,o->...o', x, self.A, self.B,
self.pre if premult else torch.ones((1,),dtype=dtype),
self.mid if premult else torch.ones((1,),dtype=dtype),
self.post if postmult else torch.ones((1,),dtype=dtype))
return functools.partial(LinearWithTiedLora, A=A, B=B)
@PeftStrategyConfig.register_subclass('tied_lora')
@dataclass
class TiedLoraConfig(PeftStrategyConfig):
r: int = 16
premult: bool = False
midmult: bool = True
postmult: bool = True
alpha: float = 100.
gamma: float = 750.
def wrap(self,model):
return wrap_like_linear(model, functools.partial(create_tied_lora_wrapper, r=self.r,
premult=self.premult, midmult=self.midmult, postmult=self.postmult,
dtype=model.dtype, alpha=self.alpha, gamma=self.gamma))
def create_partially_tied_lora_wrapper(in_features, out_features, r, la, lb, premult, midmult, postmult, dtype, alpha, gamma):
A = torch.nn.Parameter(torch.randn(in_features, r, la, dtype=dtype) / gamma)
B = torch.nn.Parameter(torch.zeros(r, out_features, lb, dtype=dtype))
class LinearWithPartiallyTiedLora(torch.nn.Module):
def __init__(self, linear, A, B):
super().__init__()
assert linear.bias is None
assert linear.weight.dtype is dtype
self.linear = linear
self.A = A
self.B = B
self.MA = torch.nn.Parameter(torch.randn(la, dtype=dtype) / gamma)
self.MB = torch.nn.Parameter(torch.randn(lb, dtype=dtype) / gamma)
self.norm = float(np.sqrt(self.linear.weight.float().pow(2).mean()))
if premult:
self.pre = torch.nn.Parameter(torch.ones(in_features,dtype=dtype) / gamma)
if midmult:
self.mid = torch.nn.Parameter(torch.ones(r,dtype=dtype) / gamma)
if postmult:
self.post = torch.nn.Parameter(torch.ones(out_features,dtype=dtype) / gamma)
def forward(self, x):
return self.linear(x) + gamma ** (3+(1 if premult else 0)+(1 if midmult else 0)+(1 if postmult else 0)) * alpha * self.norm / np.sqrt(r*la*lb) *\
torch.einsum('...i,irA,roB,A,B,i,r,o->...o', x, self.A, self.B, self.MA, self.MB,
self.pre if premult else torch.ones((1,),dtype=dtype),
self.mid if midmult else torch.ones((1,),dtype=dtype),
self.post if postmult else torch.ones((1,),dtype=dtype))
return functools.partial(LinearWithPartiallyTiedLora, A=A, B=B)
@PeftStrategyConfig.register_subclass('partially_tied_lora')
@dataclass
class PartiallyTiedLoraConfig(PeftStrategyConfig):
r: int = 8
la: int = 4
lb: int = 4
premult: bool = False
midmult: bool = False
postmult: bool = False
alpha: float = 100.
gamma: float = 750.
def wrap(self,model):
return wrap_like_linear(model, functools.partial(create_partially_tied_lora_wrapper, r=self.r, la=self.la, lb=self.lb,
premult=self.premult, midmult=self.midmult, postmult=self.postmult,
dtype=model.dtype, alpha=self.alpha, gamma=self.gamma))
@PeftStrategyConfig.register_subclass('lora')
@dataclass
class LoraConfig(PeftStrategyConfig):
r: int = 8
alpha: float = 3.
gamma: float = 1.
def wrap(self,model):
r = self.r
alpha = self.alpha
gamma = self.gamma
class LinearWithLoRA(torch.nn.Module):
def __init__(self, linear, r, alpha):
super().__init__()
assert linear.bias is None
self.linear = linear
self.alpha = alpha
self.A = torch.nn.Parameter(torch.randn(linear.in_features, r, dtype=linear.weight.dtype) / gamma)
self.B = torch.nn.Parameter(torch.zeros(r, linear.out_features, dtype=linear.weight.dtype))
def forward(self, x):
return self.linear(x) + gamma * alpha / np.sqrt(r) * (x @ self.A @ self.B)
return wrap_linear(model,functools.partial(LinearWithLoRA, r=self.r, alpha=self.alpha))
@PeftStrategyConfig.register_subclass('strong_gamma_lora')
@dataclass
class StrongGammaLoraConfig(PeftStrategyConfig):
r: int = 8
alpha: float = 3.
gamma: float = 750.
def wrap(self,model):
r = self.r
alpha = self.alpha
gamma = self.gamma
class LinearWithLoRA(torch.nn.Module):
def __init__(self, linear, r, alpha):
super().__init__()
assert linear.bias is None
self.linear = linear
self.alpha = alpha
self.A = torch.nn.Parameter(torch.randn(linear.in_features, r, dtype=linear.weight.dtype) / gamma)
self.B = torch.nn.Parameter(torch.zeros(r, linear.out_features, dtype=linear.weight.dtype))
def forward(self, x):
return self.linear(x) + torch.minimum(torch.tensor(gamma).type_as(self.B), self.B.pow(2).mean().rsqrt()).detach() * \
alpha / np.sqrt(r) * (x @ self.A @ self.B)
return wrap_linear(model,functools.partial(LinearWithLoRA, r=self.r, alpha=self.alpha))
@PeftStrategyConfig.register_subclass('normed_lora')
@dataclass
class NormedLoraConfig(PeftStrategyConfig):
r: int = 8
alpha: float = 100.
gamma: float = 750.
def wrap(self,model):
r = self.r
alpha = self.alpha
gamma = self.gamma
class LinearWithLoRA(torch.nn.Module):
def __init__(self, linear, r, alpha):
super().__init__()
assert linear.bias is None
self.linear = linear
self.alpha = alpha
self.norm = float(np.sqrt(self.linear.weight.float().pow(2).mean()))
self.A = torch.nn.Parameter(torch.randn(linear.in_features, r, dtype=linear.weight.dtype) / gamma)
self.B = torch.nn.Parameter(torch.zeros(r, linear.out_features, dtype=linear.weight.dtype))
def forward(self, x):
return self.linear(x) + gamma * alpha * self.norm / np.sqrt(r) * (x @ self.A @ self.B)
return wrap_linear(model,functools.partial(LinearWithLoRA, r=self.r, alpha=self.alpha))
@PeftStrategyConfig.register_subclass('dora')
@dataclass
class DoraConfig(PeftStrategyConfig):
r: int = 8
transpose: bool = False
eps: float = 1e-6
alpha: float = 100.
gamma: float = 1.
def wrap(self,model):
# ordinary dora scales the input (so reduces in the output dimension)
# we fix input dimension as 0 and output dimension as 1 to agree with matrices acting on the right
transpose = self.transpose
reducedim = 1 if self.transpose else 0
scaledim_name = 'i' if transpose else 'o'
eps = self.eps
r = self.r
alpha = self.alpha
gamma = self.gamma
class LinearWithDora(torch.nn.Module):
def __init__(self, linear):
super().__init__()
assert linear.bias is None
W = linear.weight.T
mag = torch.sqrt(W.float().pow(2).mean(dim=reducedim) + eps).type_as(W)
self.W = torch.nn.Parameter(W.contiguous() / float(np.sqrt(W.float().pow(2).mean())),
requires_grad = False)
self.mag = torch.nn.Parameter(mag)
self.A = torch.nn.Parameter(torch.randn(linear.in_features, r, dtype = W.dtype) / gamma)
self.B = torch.nn.Parameter(torch.zeros(r, linear.out_features, dtype = W.dtype))
def forward(self, x):
Wtune = self.W + gamma * alpha / np.sqrt(r) * self.A @ self.B
imag = torch.rsqrt(Wtune.pow(2).mean(dim=reducedim) + eps)
return torch.einsum(f'...i,io,{scaledim_name}->...o', x, Wtune, imag * self.mag)
return wrap_linear(model,functools.partial(LinearWithDora))
@PeftStrategyConfig.register_subclass('simple_dora')
@dataclass
class SimpleDoraConfig(PeftStrategyConfig):
r: int = 8
transpose: bool = False
eps: float = 1e-6
alpha: float = 100.
beta: float = 1. # mag learning rate boost
gamma: float = 750.
def wrap(self,model):
transpose = self.transpose
eps = self.eps
reducedim = 1 if self.transpose else 0
r = self.r
alpha = self.alpha
beta = self.beta
gamma = self.gamma
class LinearWithSimpleDoraTranspose(torch.nn.Module):
def __init__(self, linear):
super().__init__()
assert linear.bias is None
W = linear.weight.T
mag = torch.sqrt(W.float().pow(2).mean(dim=reducedim,keepdim=True) + eps)
self.W = torch.nn.Parameter((W.float() / mag).type_as(W).contiguous(), requires_grad = False)
self.imag = torch.nn.Parameter(mag.type_as(W).squeeze() * beta,requires_grad=False)
self.mag = torch.nn.Parameter(torch.ones(self.imag.shape,dtype=W.dtype) / beta)
self.A = torch.nn.Parameter(torch.randn(linear.in_features, r, dtype = W.dtype) / gamma)
self.B = torch.nn.Parameter(torch.zeros(r, linear.out_features, dtype = W.dtype))
def forward(self, x):
if transpose:
x = x * self.imag * self.mag
y = x @ self.W + gamma * alpha / np.sqrt(r) * x @ self.A @ self.B
if not transpose:
y = y * self.imag * self.mag
return y
return wrap_linear(model,functools.partial(LinearWithSimpleDoraTranspose))
@PeftStrategyConfig.register_subclass('svdora')
@dataclass
class SvdoraConfig(PeftStrategyConfig):
rU: int = 8
rV: int = 8
alpha: float = 100.
gamma: float = 750.
def wrap(self,model):
alpha = self.alpha
gamma = self.gamma
rU = self.rU
rV = self.rV
class LinearWithSimpleSvdora(torch.nn.Module):
def __init__(self, linear):
super().__init__()
assert linear.bias is None
W = linear.weight.T
U, sigma, Vh = torch.linalg.svd(W.to(torch.float32), full_matrices=False)
print(sigma)
self.U = torch.nn.Parameter(U.to(W.dtype).contiguous(), requires_grad=False)
self.sigma = torch.nn.Parameter(sigma.to(W.dtype))
self.Vh = torch.nn.Parameter(Vh.to(W.dtype).contiguous(), requires_grad=False)
self.A1 = torch.nn.Parameter(torch.randn(U.shape[0], rU, dtype = linear.weight.dtype)/gamma)
self.B1 = torch.nn.Parameter(torch.zeros(rU, U.shape[1], dtype = linear.weight.dtype))
self.A2 = torch.nn.Parameter(torch.randn(Vh.shape[0], rV, dtype = linear.weight.dtype)/gamma)
self.B2 = torch.nn.Parameter(torch.zeros(rV, Vh.shape[1], dtype = linear.weight.dtype))
def forward(self, x):
x = x @ self.U + gamma * alpha / np.sqrt(rU * self.U.shape[1]) * (x @ self.A1 @ self.B1)
x = x * self.sigma
return x @ self.Vh + gamma * alpha / np.sqrt(rV * self.Vh.shape[0]) * x @ self.A2 @ self.B2
return wrap_linear(model,functools.partial(LinearWithSimpleSvdora))