File size: 8,237 Bytes
22e9602
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import unittest
import torch
import torch.nn as nn
import random
import os
import numpy as np

# Note: The 'try...except' block has been removed to ensure that any
# ImportError during setup is reported clearly to the user, as it is the
# likely root cause of the previous errors. See the __main__ block for
# instructions on handling dependencies for standalone execution.
from peft.tuners.canonical import (
    LoraConfig as CanonicalLoraConfig,
    LoraModel as CanonicalLoraModel,
    Linear as CanonicalLinear,
    mark_only_lora_as_trainable as canonical_mark_only_lora_as_trainable,
)
from peft.tuners.lora import (
    LoraConfig as GeneratedLoraConfig,
    LoraModel as GeneratedLoraModel,
    Linear as GeneratedLinear,
    mark_only_lora_as_trainable as generated_mark_only_lora_as_trainable,
)


def set_seed(seed=2025):
    """Sets the seed for reproducibility across all relevant libraries."""
    random.seed(seed)
    os.environ['PYTHONHASHSEED'] = str(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    if torch.cuda.is_available():
        torch.cuda.manual_seed(seed)
        torch.cuda.manual_seed_all(seed)
    torch.backends.cudnn.benchmark = False
    torch.backends.cudnn.deterministic = True

class SimpleModel(nn.Module):
    """A simple dummy model for testing the model wrapper."""
    def __init__(self, in_features=16, out_features=16):
        super().__init__()
        self.q_proj = nn.Linear(in_features, out_features, bias=True)
        self.v_proj = nn.Linear(in_features, out_features, bias=False)
        self.unrelated = nn.Linear(in_features, out_features)

    def forward(self, x):
        return self.unrelated(self.v_proj(self.q_proj(x)))

class TestLoraMoeEquivalence(unittest.TestCase):
    """
    Test suite to evaluate the functional equivalence of a generated LoRAMoE
    implementation against a canonical ground truth implementation.
    """

    def setUp(self):
        """Set up common resources and configurations for all tests."""
        set_seed()
        self.batch_size = 2
        self.seq_len = 5
        self.in_features = 16
        self.out_features = 16

        self.input_tensor = torch.randn(self.batch_size, self.seq_len, self.in_features)
        self.task_types_tensor = torch.randint(0, 2, (self.batch_size,))

        self.lora_config_params = {
            'r': 4, 'lora_alpha': 8, 'lora_nums': 2,
            'blc_alpha': 0.1, 'blc_weight': 0.1, 'lora_dropout': 0.0,
            'target_modules': ["q_proj", "v_proj"], 'fan_in_fan_out': False,
            'merge_weights': False, 'bias': 'lora_only', 'modules_to_save': None
        }

        self.linear_layer_params = {
            key: self.lora_config_params[key]
            for key in ['r', 'lora_alpha', 'lora_nums', 'blc_alpha',
                        'blc_weight', 'lora_dropout', 'fan_in_fan_out', 'merge_weights']
        }

    def test_lora_config_initialization(self):
        """Instruction 1: Tests if LoraConfig initializes identically."""
        canonical_config = CanonicalLoraConfig(**self.lora_config_params)
        generated_config = GeneratedLoraConfig(**self.lora_config_params)
        self.assertDictEqual(canonical_config.__dict__, generated_config.__dict__)

    def test_cv_squared_utility(self):
        """Instruction 6: Tests the cv_squared utility function."""
        canonical_layer = CanonicalLinear(self.in_features, self.out_features, **self.linear_layer_params)
        generated_layer = GeneratedLinear(self.in_features, self.out_features, **self.linear_layer_params)
        for test_input in [torch.tensor([1., 2., 7., 10.]), torch.tensor([5., 5., 5.]), torch.tensor([10.])]:
            with self.subTest(input=test_input):
                self.assertAlmostEqual(canonical_layer.cv_squared(test_input).item(), generated_layer.cv_squared(test_input).item(), places=7)

    def test_mark_only_lora_as_trainable(self):
        """Instruction 3: Tests the parameter freezing utility."""
        for bias_mode in ['none', 'all', 'lora_only']:
            with self.subTest(bias=bias_mode):
                config = self.lora_config_params.copy()
                config['bias'] = bias_mode
                set_seed(); canonical_model = CanonicalLoraModel(CanonicalLoraConfig(**config), SimpleModel())
                set_seed(); generated_model = GeneratedLoraModel(GeneratedLoraConfig(**config), SimpleModel())
                self.assertDictEqual({n: p.requires_grad for n, p in canonical_model.named_parameters()},
                                     {n: p.requires_grad for n, p in generated_model.named_parameters()})

    def test_lora_model_wrapper_and_linear_initialization(self):
        """Instructions 2 & 4: Tests wrapper and layer initialization."""
        set_seed(); canonical_model = CanonicalLoraModel(CanonicalLoraConfig(**self.lora_config_params), SimpleModel())
        set_seed(); generated_model = GeneratedLoraModel(GeneratedLoraConfig(**self.lora_config_params), SimpleModel())
        self.assertIsInstance(canonical_model.model.q_proj, CanonicalLinear)
        self.assertIsInstance(generated_model.model.q_proj, GeneratedLinear)
        self.assertNotIsInstance(canonical_model.model.unrelated, CanonicalLinear)

    def test_reset_parameters_initialization(self):
        """Instruction 5: Tests the weight initialization of the Linear layer."""
        set_seed()
        canonical_layer = CanonicalLinear(self.in_features, self.out_features, bias=True, **self.linear_layer_params)
        set_seed()
        generated_layer = GeneratedLinear(self.in_features, self.out_features, bias=True, **self.linear_layer_params)
        torch.testing.assert_close(canonical_layer.lora_route.weight, generated_layer.lora_route.weight)
        for i in range(self.linear_layer_params['lora_nums']):
            torch.testing.assert_close(getattr(canonical_layer, f'lora_A{i}').weight, getattr(generated_layer, f'lora_A{i}').weight)
            torch.testing.assert_close(getattr(canonical_layer, f'lora_B{i}').weight, getattr(generated_layer, f'lora_B{i}').weight)

    def test_linear_layer_forward_pass_equivalence(self):
        """Instruction 7: Tests the forward pass of the custom Linear layer."""
        set_seed(); canonical_layer = CanonicalLinear(self.in_features, self.out_features, **self.linear_layer_params)
        set_seed(); generated_layer = GeneratedLinear(self.in_features, self.out_features, **self.linear_layer_params)

        with self.subTest(case="with_task_types"):
            canonical_output, canonical_loss = canonical_layer(self.input_tensor, self.task_types_tensor)
            generated_output, generated_loss = generated_layer(self.input_tensor, self.task_types_tensor)
            torch.testing.assert_close(canonical_output, generated_output)
            torch.testing.assert_close(canonical_loss, generated_loss)

        with self.subTest(case="without_task_types"):
            canonical_output, canonical_loss = canonical_layer(self.input_tensor, task_types=None)
            generated_output, generated_loss = generated_layer(self.input_tensor, task_types=None)
            torch.testing.assert_close(canonical_output, generated_output)
            self.assertEqual(canonical_loss.item(), 0.0)

if __name__ == '__main__':
    # This block helps run this test script standalone by mocking the `peft.utils`
    # dependency, which can cause an `ImportError` in the target code due to its
    # relative import (`from ..utils import ...`). If you encounter an
    # `ImportError`, it means your environment needs to be configured to find
    # the `peft` library, or you can rely on this mocking for isolated testing.
    import sys
    if 'peft.utils' not in sys.modules:
        print("\nNOTE: Mocking 'peft.utils' for standalone execution.\n")
        class PeftConfig: pass
        class PeftType: LORA = "LORA"
        def transpose(w, f): return w.T if f else w
        
        mock_utils = type(sys)('utils')
        mock_utils.PeftConfig = PeftConfig
        mock_utils.PeftType = PeftType
        mock_utils.transpose = transpose
        
        sys.modules['peft.utils'] = mock_utils
        sys.modules['..utils'] = mock_utils # For the relative import

    unittest.main(verbosity=2)