Skip to content

Commit 615de24

Browse files
authored
Merge pull request #1323 from gzrp/dev-postgresql
Add the implementations of tuner for the PEFT example
2 parents 02e0016 + 17df130 commit 615de24

1 file changed

Lines changed: 58 additions & 0 deletions

File tree

  • examples/singa_peft/src/singa_peft/tuners/linear_lora
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
#
2+
# Licensed to the Apache Software Foundation (ASF) under one
3+
# or more contributor license agreements. See the NOTICE file
4+
# distributed with this work for additional information
5+
# regarding copyright ownership. The ASF licenses this file
6+
# to you under the Apache License, Version 2.0 (the
7+
# "License"); you may not use this file except in compliance
8+
# with the License. You may obtain a copy of the License at
9+
#
10+
# http://www.apache.org/licenses/LICENSE-2.0
11+
#
12+
# Unless required by applicable law or agreed to in writing,
13+
# software distributed under the License is distributed on an
14+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
# KIND, either express or implied. See the License for the
16+
# specific language governing permissions and limitations
17+
# under the License.
18+
#
19+
20+
from singa import model, layer
21+
from singa_peft.peft_registry import PeftRegistry
22+
from singa_peft.tuners.base_tuner import BaseTuner
23+
from singa_peft.tuners.linear_lora.config import LinearLoraConfig
24+
from singa_peft.tuners.linear_lora.layer import LinearLoRALayer
25+
26+
27+
@PeftRegistry.register("linear_lora")
28+
class LinearLoraTuner(BaseTuner):
29+
30+
def __init__(self, config):
31+
super().__init__(config)
32+
self.targeted_layers = []
33+
34+
def inject(self, base_model: model.Model) -> model.Model:
35+
# freeze base_model parameters
36+
if self.config.freeze_base_model:
37+
self.freeze_base_parameters(base_model)
38+
return self._inject_linear_lora(base_model, self.config)
39+
40+
def _inject_linear_lora(self, base_model, config: LinearLoraConfig) -> model.Model:
41+
target_layers = config.target_layers
42+
r = config.r
43+
lora_alpha = config.lora_alpha
44+
lora_dropout = config.lora_dropout
45+
for target_layer in target_layers:
46+
base_layer = getattr(base_model, target_layer)
47+
if base_layer is not None and isinstance(base_layer, layer.Linear):
48+
self.targeted_layers.append(target_layer)
49+
new_layer = LinearLoRALayer(base_layer, r, lora_alpha, lora_dropout)
50+
setattr(base_model, target_layer, new_layer)
51+
return base_model
52+
53+
def merge_weights(self, base_model: model.Model, mode: bool = True) -> model.Model:
54+
for target_layer in self.targeted_layers:
55+
base_layer = getattr(base_model, target_layer)
56+
if base_layer is not None:
57+
base_layer.merge_weights(mode)
58+
return base_model

0 commit comments

Comments
 (0)