Markus28 commited on
Commit
8561a1f
·
1 Parent(s): 326b1c4

feat: added LoRA

Browse files
Files changed (1) hide show
  1. modeling_lora.py +115 -0
modeling_lora.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import partial
2
+ from typing import Iterator, Tuple
3
+
4
+ import torch
5
+ from torch import nn
6
+ import torch.nn.utils.parametrize as parametrize
7
+ import math
8
+
9
+ from torch.nn import Parameter
10
+
11
+ from .modeling_bert import BertModel, BertPreTrainedModel, JinaBertConfig
12
+
13
+
14
+ class LoRAParametrization(nn.Module):
15
+ def __init__(self, fan_in, fan_out, fan_in_fan_out=False, num_adaptions=1, rank=4, lora_dropout_p=0.0, lora_alpha=1):
16
+ super().__init__()
17
+ # if weight is stored as (fan_out, fan_in), the memory layout of A & B follows (W + BA)x
18
+ # otherwise, it's x(W + AB). This allows us to tie the weights between linear layers and embeddings
19
+ self.swap = (lambda x: (x[1], x[0])) if fan_in_fan_out else (lambda x: x)
20
+ lora_A_data = []
21
+ for _ in range(num_adaptions):
22
+ new_adaption = torch.zeros(self.swap((rank, fan_in)))
23
+ nn.init.kaiming_uniform_(new_adaption, a=math.sqrt(5))
24
+ lora_A_data.append(new_adaption)
25
+ lora_A_data = torch.stack(lora_A_data, dim=0)
26
+ self.lora_A = nn.Parameter(lora_A_data)
27
+ self.lora_B = nn.Parameter(torch.zeros((num_adaptions, *self.swap((fan_out, rank)))))
28
+ self.lora_alpha, self.rank = lora_alpha, rank
29
+ self.scaling = lora_alpha / rank
30
+ self.lora_dropout = nn.Dropout(p=lora_dropout_p) if lora_dropout_p > 0 else lambda x: x
31
+ self.dropout_fn = self._dropout if lora_dropout_p > 0 else lambda x: x
32
+ self.register_buffer("lora_dropout_mask", torch.ones(self.swap((1, fan_in)), dtype=self.lora_A.dtype), persistent=False)
33
+ self.forward_fn = lambda x: x
34
+ self.current_task = None
35
+
36
+ def _dropout(self, A):
37
+ # to mimic the original implementation: A @ dropout(x), we do (A * dropout(ones)) @ x
38
+ return A * self.lora_dropout(self.lora_dropout_mask)
39
+
40
+ def lora_forward(self, X):
41
+ assert self.current_task is not None
42
+ return X + torch.matmul(*self.swap((self.lora_B[self.current_task], self.dropout_fn(self.lora_A[self.current_task])))).view(X.shape) * self.scaling
43
+
44
+ def forward(self, X):
45
+ return self.forward_fn(X)
46
+
47
+ def select_task(self, task=None):
48
+ self.current_task = task
49
+ if task is None:
50
+ self.forward_fn = lambda x: x
51
+ else:
52
+ self.forward_fn = self.lora_forward
53
+
54
+ @classmethod
55
+ def from_linear(cls, layer, num_adaptions=1, rank=4, lora_dropout_p=0.0, lora_alpha=1):
56
+ fan_out, fan_in = layer.weight.shape
57
+ return cls(
58
+ fan_in, fan_out, num_adaptions=num_adaptions, fan_in_fan_out=False, rank=rank, lora_dropout_p=lora_dropout_p, lora_alpha=lora_alpha
59
+ )
60
+
61
+ @classmethod
62
+ def from_embedding(cls, layer, num_adaptions=1, rank=4, lora_dropout_p=0.0, lora_alpha=1):
63
+ fan_in, fan_out = layer.weight.shape
64
+ return cls(
65
+ fan_in, fan_out, num_adaptions=num_adaptions, fan_in_fan_out=True, rank=rank, lora_dropout_p=lora_dropout_p, lora_alpha=lora_alpha
66
+ )
67
+
68
+ @classmethod
69
+ def add_to_layer(cls, layer, num_adaptions=1, rank=4, lora_dropout_p=0.0, lora_alpha=1):
70
+ if isinstance(layer, nn.Linear):
71
+ parametrize.register_parametrization(layer, "weight", cls.from_linear(layer, num_adaptions=num_adaptions, rank=rank, lora_dropout_p=lora_dropout_p, lora_alpha=lora_alpha))
72
+ elif isinstance(layer, nn.Embedding):
73
+ parametrize.register_parametrization(layer, "weight", cls.from_embedding(layer, num_adaptions=num_adaptions, rank=rank, lora_dropout_p=lora_dropout_p, lora_alpha=lora_alpha))
74
+
75
+ @classmethod
76
+ def select_task_for_layer(cls, layer, task_idx=None):
77
+ if isinstance(layer, LoRAParametrization):
78
+ layer.select_task(task_idx)
79
+
80
+
81
+ class BertLoRA(BertPreTrainedModel):
82
+ def __init__(self, config: JinaBertConfig, add_pooling_layer=True, num_adaptions=1):
83
+ super().__init__(config)
84
+ self.bert = BertModel(config, add_pooling_layer=add_pooling_layer)
85
+ self._register_lora(num_adaptions)
86
+ for name, param in super().named_parameters():
87
+ if 'lora' not in name:
88
+ param.requires_grad_(False)
89
+
90
+ def from_bert(self, *args, num_adaptions=1, **kwargs):
91
+ self.bert = BertModel.from_pretrained(*args, **kwargs)
92
+ self._register_lora(num_adaptions)
93
+
94
+ def _register_lora(self, num_adaptions=1, rank=4, lora_dropout_p=0.0, lora_alpha=1):
95
+ self.apply(partial(LoRAParametrization.add_to_layer, num_adaptions=num_adaptions, rank=rank, lora_dropout_p=lora_dropout_p, lora_alpha=lora_alpha))
96
+
97
+ def select_task(self, task_idx):
98
+ self.apply(partial(LoRAParametrization.select_task_for_layer, task_idx=task_idx))
99
+
100
+ def forward(self, *args, **kwargs):
101
+ return self.bert(*args, **kwargs)
102
+
103
+ def parameters(self, recurse: bool = True) -> Iterator[Parameter]:
104
+ for _å, param in self.named_parameters(recurse=recurse):
105
+ yield param
106
+
107
+ def named_parameters(
108
+ self,
109
+ prefix: str = '',
110
+ recurse: bool = True,
111
+ remove_duplicate: bool = True
112
+ ) -> Iterator[Tuple[str, Parameter]]:
113
+ for name, param in super().named_parameters(prefix=prefix, recurse=recurse, remove_duplicate=remove_duplicate):
114
+ if 'lora' in name:
115
+ yield name, param