File size: 13,652 Bytes
302920f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Copyright 2025-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# This test file is for tests specific to SHiRA.

import os

import pytest
import torch
from accelerate.utils.imports import is_bf16_available
from torch import nn

from peft import PeftModel, ShiraConfig, get_peft_model


def custom_random_mask_function_with_custom_kwargs(custom_arg):
    def mask_fn(base_layer, r):
        """
        This mask function is similar to the random_mask provided in src/peft/tuners/shira/mask_functions.py except the
        seed is derived from custom_kwargs. Please use this as an example to create your own custom sparse masks that
        may use custom_kwargs. Remember, for a pretrained weight with shape m, n, mask_fn must return only one mask
        (shape: m, n) which must be binary 0 or 1 with num_shira_parameters = r(m+n) for linear layers. Device and
        dtype of mask must be same as base layer's weight's device and dtype.
        """
        new_seed = custom_arg
        shape = base_layer.weight.shape
        num_shira_weights = r * (shape[0] + shape[1])
        random_generator = torch.Generator()
        random_generator.manual_seed(new_seed)

        idx = (torch.randperm(base_layer.weight.numel(), generator=random_generator)[:num_shira_weights]).to(
            base_layer.weight.device
        )
        val = torch.ones_like(idx.type(base_layer.weight.dtype))
        mask = torch.zeros_like(base_layer.weight.view(1, -1))
        mask = mask.scatter_(1, idx.unsqueeze(0), val.unsqueeze(0)).view(shape)

        return mask

    return mask_fn


class MLP(nn.Module):
    def __init__(self, bias=True):
        super().__init__()
        self.relu = nn.ReLU()
        self.lin0 = nn.Linear(10, 20, bias=bias)
        self.lin1 = nn.Linear(20, 40, bias=bias)  # lin1 and lin2 have same shape
        self.lin2 = nn.Linear(40, 30, bias=bias)
        self.lin3 = nn.Linear(30, 10, bias=bias)
        self.sm = nn.LogSoftmax(dim=-1)

    def forward(self, X):
        X = self.lin0(X)
        X = self.relu(X)
        X = self.lin1(X)
        X = self.relu(X)
        X = self.lin2(X)
        X = self.relu(X)
        X = self.lin3(X)
        X = self.sm(X)
        return X


class TestShira:
    @pytest.fixture
    def mlp(self):
        torch.manual_seed(0)
        model = MLP()
        return model

    def test_mlp_single_adapter_shapes(self, mlp):
        # torch.manual_seed(0)

        r = 2
        config = ShiraConfig(r=r, target_modules=["lin1", "lin2"])
        # creates a default SHiRA adapter
        peft_model = get_peft_model(mlp, config)

        shira_weight1_size = peft_model.base_model.model.lin1.shira_weight["default"].shape[0]
        shira_weight2_size = peft_model.base_model.model.lin2.shira_weight["default"].shape[0]
        shira_indices1_size = peft_model.base_model.model.lin1.shira_indices["default"].shape[1]
        shira_indices2_size = peft_model.base_model.model.lin2.shira_indices["default"].shape[1]

        base_weight1_size = peft_model.base_model.model.lin1.base_layer.weight.shape
        base_weight2_size = peft_model.base_model.model.lin2.base_layer.weight.shape

        delta_weight1_shape = peft_model.base_model.model.lin1.get_delta_weight("default").shape
        delta_weight2_shape = peft_model.base_model.model.lin2.get_delta_weight("default").shape

        assert shira_weight1_size == r * (base_weight1_size[0] + base_weight1_size[1])
        assert shira_weight2_size == r * (base_weight2_size[0] + base_weight2_size[1])

        assert shira_weight1_size == shira_indices1_size
        assert shira_weight2_size == shira_indices2_size

        assert delta_weight1_shape == base_weight1_size
        assert delta_weight2_shape == base_weight2_size

        return peft_model

    def test_multiple_adapters_save_load(self, mlp, tmp_path):
        # check saving and loading works with multiple adapters
        # note, the random seeds in the below two configs are not the default values.
        # so it will lead to different random sparse masks between saving and loading.
        # our goal is to make sure that loaded indices are exactly the same as the saved indices regardless of what initial random mask gets generated.
        # we will also make sure that parameters are saved and loaded correctly, and the output remains the same.
        config = ShiraConfig(r=2, target_modules=["lin1", "lin2"], random_seed=56)
        # creates a default SHiRA adapter
        peft_model = get_peft_model(mlp, config, adapter_name="first")
        config2 = ShiraConfig(r=3, target_modules=["lin1", "lin2", "lin3"], random_seed=67)
        peft_model.add_adapter("second", config2)

        assert torch.all(peft_model.base_model.model.lin1.shira_weight["first"] == 0)
        assert torch.all(peft_model.base_model.model.lin2.shira_weight["first"] == 0)
        assert torch.all(peft_model.base_model.model.lin1.shira_weight["second"] == 0)
        assert torch.all(peft_model.base_model.model.lin2.shira_weight["second"] == 0)
        assert torch.all(peft_model.base_model.model.lin3.shira_weight["second"] == 0)

        shira_assign_val1_f = torch.randn_like(peft_model.base_model.model.lin1.shira_weight["first"])
        peft_model.base_model.model.lin1.shira_weight["first"] = shira_assign_val1_f
        shira_indices1_f = peft_model.base_model.model.lin1.shira_indices["first"]
        shira_assign_val2_f = torch.randn_like(peft_model.base_model.model.lin2.shira_weight["first"])
        peft_model.base_model.model.lin2.shira_weight["first"] = shira_assign_val2_f
        shira_indices2_f = peft_model.base_model.model.lin2.shira_indices["first"]

        shira_assign_val1_s = torch.randn_like(peft_model.base_model.model.lin1.shira_weight["second"])
        peft_model.base_model.model.lin1.shira_weight["second"] = shira_assign_val1_s
        shira_indices1_s = peft_model.base_model.model.lin1.shira_indices["second"]
        shira_assign_val2_s = torch.randn_like(peft_model.base_model.model.lin2.shira_weight["second"])
        peft_model.base_model.model.lin2.shira_weight["second"] = shira_assign_val2_s
        shira_indices2_s = peft_model.base_model.model.lin2.shira_indices["second"]
        shira_assign_val3_s = torch.randn_like(peft_model.base_model.model.lin3.shira_weight["second"])
        peft_model.base_model.model.lin3.shira_weight["second"] = shira_assign_val3_s
        shira_indices3_s = peft_model.base_model.model.lin3.shira_indices["second"]

        input = torch.randn(5, 10)
        peft_model.set_adapter("first")
        output_first = peft_model(input)
        peft_model.set_adapter("second")
        output_second = peft_model(input)

        # sanity check
        assert not torch.allclose(output_first, output_second, atol=1e-3, rtol=1e-3)

        save_path = os.path.join(tmp_path, "shira")
        peft_model.save_pretrained(save_path)
        assert os.path.exists(os.path.join(save_path, "first", "adapter_config.json"))
        assert os.path.exists(os.path.join(save_path, "second", "adapter_config.json"))
        del peft_model

        torch.manual_seed(0)
        mlp = MLP()
        peft_model = PeftModel.from_pretrained(mlp, os.path.join(save_path, "first"), adapter_name="first")
        peft_model.load_adapter(os.path.join(save_path, "second"), "second")

        peft_model.set_adapter("first")
        output_first_loaded = peft_model(input)
        peft_model.set_adapter("second")
        output_second_loaded = peft_model(input)

        assert torch.allclose(output_first, output_first_loaded)
        assert torch.allclose(output_second, output_second_loaded)

        assert torch.all(shira_assign_val1_f == peft_model.base_model.model.lin1.shira_weight["first"])
        assert torch.all(shira_assign_val2_f == peft_model.base_model.model.lin2.shira_weight["first"])
        assert torch.all(shira_indices1_f == peft_model.base_model.model.lin1.shira_indices["first"])
        assert torch.all(shira_indices2_f == peft_model.base_model.model.lin2.shira_indices["first"])
        assert torch.all(shira_assign_val1_s == peft_model.base_model.model.lin1.shira_weight["second"])
        assert torch.all(shira_assign_val2_s == peft_model.base_model.model.lin2.shira_weight["second"])
        assert torch.all(shira_assign_val3_s == peft_model.base_model.model.lin3.shira_weight["second"])
        assert torch.all(shira_indices1_s == peft_model.base_model.model.lin1.shira_indices["second"])
        assert torch.all(shira_indices2_s == peft_model.base_model.model.lin2.shira_indices["second"])
        assert torch.all(shira_indices3_s == peft_model.base_model.model.lin3.shira_indices["second"])

        return peft_model

    def test_save_load_custom_mask_function(self, mlp, tmp_path):
        # we want to see if saving and loading works when a custom mask is involved
        config = ShiraConfig(r=2, mask_type="custom", target_modules=["lin1", "lin2"], init_weights=False)
        custom_arg = 120
        custom_mask_fn = custom_random_mask_function_with_custom_kwargs(custom_arg)
        config.mask_fn = custom_mask_fn

        # create a custom mask SHiRA adapter
        peft_model = get_peft_model(mlp, config, adapter_name="first")

        shira_assign_val1_f = peft_model.base_model.model.lin1.shira_weight["first"]
        shira_indices1_f = peft_model.base_model.model.lin1.shira_indices["first"]
        shira_assign_val2_f = peft_model.base_model.model.lin2.shira_weight["first"]
        shira_indices2_f = peft_model.base_model.model.lin2.shira_indices["first"]

        input = torch.randn(5, 10)
        peft_model.set_adapter("first")
        output_first = peft_model(input)

        save_path = os.path.join(tmp_path, "shira")
        peft_model.save_pretrained(save_path)
        assert os.path.exists(os.path.join(save_path, "first", "adapter_config.json"))
        del peft_model

        torch.manual_seed(0)
        mlp = MLP()
        peft_model = PeftModel.from_pretrained(mlp, os.path.join(save_path, "first"), adapter_name="first")

        peft_model.set_adapter("first")
        output_first_loaded = peft_model(input)

        assert torch.allclose(output_first, output_first_loaded)

        assert torch.all(shira_assign_val1_f == peft_model.base_model.model.lin1.shira_weight["first"])
        assert torch.all(shira_assign_val2_f == peft_model.base_model.model.lin2.shira_weight["first"])
        assert torch.all(shira_indices1_f == peft_model.base_model.model.lin1.shira_indices["first"])
        assert torch.all(shira_indices2_f == peft_model.base_model.model.lin2.shira_indices["first"])

        return peft_model

    def test_save_load_default_random_mask_with_seed_function(self, mlp, tmp_path):
        # we want to see if saving and loading works when a random mask is involved but the random seed is fixed.
        config = ShiraConfig(r=2, target_modules=["lin1", "lin2"], random_seed=567, init_weights=False)

        # create a custom mask SHiRA adapter
        peft_model = get_peft_model(mlp, config, adapter_name="first")

        shira_assign_val1_f = peft_model.base_model.model.lin1.shira_weight["first"]
        shira_indices1_f = peft_model.base_model.model.lin1.shira_indices["first"]
        shira_assign_val2_f = peft_model.base_model.model.lin2.shira_weight["first"]
        shira_indices2_f = peft_model.base_model.model.lin2.shira_indices["first"]

        input = torch.randn(5, 10)
        peft_model.set_adapter("first")
        output_first = peft_model(input)

        save_path = os.path.join(tmp_path, "shira")
        peft_model.save_pretrained(save_path)
        assert os.path.exists(os.path.join(save_path, "first", "adapter_config.json"))
        del peft_model

        torch.manual_seed(0)
        mlp = MLP()
        peft_model = PeftModel.from_pretrained(mlp, os.path.join(save_path, "first"), adapter_name="first")

        peft_model.set_adapter("first")
        output_first_loaded = peft_model(input)

        assert torch.allclose(output_first, output_first_loaded)

        assert torch.all(shira_assign_val1_f == peft_model.base_model.model.lin1.shira_weight["first"])
        assert torch.all(shira_assign_val2_f == peft_model.base_model.model.lin2.shira_weight["first"])
        assert torch.all(shira_indices1_f == peft_model.base_model.model.lin1.shira_indices["first"])
        assert torch.all(shira_indices2_f == peft_model.base_model.model.lin2.shira_indices["first"])

        return peft_model

    @pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.bfloat16])
    def test_shira_dtypes(self, dtype):
        if dtype == torch.bfloat16:
            # skip if bf16 is not supported on hardware, see #1872
            if not is_bf16_available():
                pytest.skip("bfloat16 not supported on this system, skipping the test")

        model = MLP().to(dtype)
        config = ShiraConfig(r=2, target_modules=["lin1", "lin2"])
        peft_model = get_peft_model(model, config)
        inputs = torch.randn(5, 10).to(dtype)
        output = peft_model(inputs)  # should not raise
        assert output.dtype == dtype