assassinlike commited on
Commit
926779e
·
verified ·
1 Parent(s): 01546de

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/__pycache__/__init__.cpython-310.pyc +0 -0
  2. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/__pycache__/_buffer_dict.cpython-310.pyc +0 -0
  3. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/__pycache__/lycoris_utils.cpython-310.pyc +0 -0
  4. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/__pycache__/tuners_utils.cpython-310.pyc +0 -0
  5. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/aqlm.py +109 -0
  6. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/arrow.py +476 -0
  7. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/awq.py +104 -0
  8. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/bnb.py +587 -0
  9. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/dora.py +287 -0
  10. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/eva.py +734 -0
  11. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/hqq.py +244 -0
  12. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/intruders.py +160 -0
  13. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/loraga.py +191 -0
  14. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/multitask_prompt_tuning/__init__.py +25 -0
  15. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/multitask_prompt_tuning/__pycache__/config.cpython-310.pyc +0 -0
  16. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/multitask_prompt_tuning/__pycache__/model.cpython-310.pyc +0 -0
  17. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/multitask_prompt_tuning/config.py +62 -0
  18. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/multitask_prompt_tuning/model.py +120 -0
  19. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__init__.py +52 -0
  20. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/__init__.cpython-310.pyc +0 -0
  21. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/aqlm.cpython-310.pyc +0 -0
  22. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/awq.cpython-310.pyc +0 -0
  23. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/bnb.cpython-310.pyc +0 -0
  24. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/config.cpython-310.pyc +0 -0
  25. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/eetq.cpython-310.pyc +0 -0
  26. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/gptq.cpython-310.pyc +0 -0
  27. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/hqq.cpython-310.pyc +0 -0
  28. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/inc.cpython-310.pyc +0 -0
  29. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/layer.cpython-310.pyc +0 -0
  30. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/model.cpython-310.pyc +0 -0
  31. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/aqlm.py +105 -0
  32. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/awq.py +107 -0
  33. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/bnb.py +388 -0
  34. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/config.py +213 -0
  35. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/eetq.py +116 -0
  36. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/gptq.py +106 -0
  37. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/hqq.py +186 -0
  38. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/inc.py +78 -0
  39. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/layer.py +1229 -0
  40. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/model.py +200 -0
  41. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/__init__.py +15 -0
  42. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/__pycache__/__init__.cpython-310.pyc +0 -0
  43. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/__pycache__/config.cpython-310.pyc +0 -0
  44. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/__pycache__/layer.cpython-310.pyc +0 -0
  45. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/__pycache__/model.cpython-310.pyc +0 -0
  46. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/__pycache__/utils.cpython-310.pyc +0 -0
  47. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/config.py +80 -0
  48. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/layer.py +289 -0
  49. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/model.py +124 -0
  50. data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/utils.py +133 -0
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (3.59 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/__pycache__/_buffer_dict.cpython-310.pyc ADDED
Binary file (6.1 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/__pycache__/lycoris_utils.cpython-310.pyc ADDED
Binary file (8.36 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/__pycache__/tuners_utils.cpython-310.pyc ADDED
Binary file (70.6 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/aqlm.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import Any, Optional
16
+
17
+ import torch
18
+
19
+ from peft.import_utils import is_aqlm_available
20
+ from peft.tuners.lora.layer import LoraLayer
21
+ from peft.tuners.tuners_utils import BaseTunerLayer
22
+
23
+ from .config import LoraConfig
24
+
25
+
26
+ if is_aqlm_available():
27
+ from aqlm import QuantizedLinear
28
+
29
+
30
+ class AqlmLoraLinear(torch.nn.Module, LoraLayer):
31
+ def __init__(
32
+ self,
33
+ base_layer,
34
+ adapter_name: str,
35
+ config: LoraConfig,
36
+ r: int = 0,
37
+ lora_alpha: int = 1,
38
+ **kwargs,
39
+ ):
40
+ if config.use_dora:
41
+ raise ValueError(f"{self.__class__.__name__} does not support DoRA yet, please set it to False")
42
+
43
+ super().__init__()
44
+ LoraLayer.__init__(self, base_layer)
45
+
46
+ self._active_adapter = adapter_name
47
+ self.update_layer(
48
+ adapter_name,
49
+ r,
50
+ lora_alpha=lora_alpha,
51
+ config=config,
52
+ )
53
+
54
+ def forward(self, x: torch.Tensor):
55
+ # note: logic differs from default Linear because merging is not supported
56
+ result = self.base_layer(x)
57
+
58
+ if self.disable_adapters:
59
+ return result
60
+
61
+ for active_adapter in self.active_adapters:
62
+ if active_adapter not in self.lora_A.keys():
63
+ continue
64
+ lora_A = self.lora_A[active_adapter]
65
+ lora_B = self.lora_B[active_adapter]
66
+ dropout = self.lora_dropout[active_adapter]
67
+ scaling = self.scaling[active_adapter]
68
+
69
+ requires_conversion = not torch.is_autocast_enabled()
70
+ if requires_conversion:
71
+ expected_dtype = result.dtype
72
+ x = self._cast_input_dtype(x, lora_A.weight.dtype)
73
+
74
+ output = lora_B(lora_A(dropout(x)))
75
+ if requires_conversion:
76
+ output = output.to(expected_dtype)
77
+ output = output * scaling
78
+ result += output
79
+ return result
80
+
81
+ def __repr__(self) -> str:
82
+ rep = super().__repr__()
83
+ return "lora." + rep
84
+
85
+ # TODO: Check if it is better as suggested by users https://github.com/PanQiWei/AutoGPTQ/pull/102
86
+ # def reset_lora_parameters(self, adapter_name):
87
+ # if adapter_name in self.lora_A.keys():
88
+ # torch.nn.init.xavier_uniform_(self.lora_A[adapter_name].weight)
89
+ # torch.nn.init.zeros_(self.lora_B[adapter_name].weight)
90
+
91
+
92
+ def dispatch_aqlm(
93
+ target: torch.nn.Module,
94
+ adapter_name: str,
95
+ config: LoraConfig,
96
+ **kwargs: Any,
97
+ ) -> Optional[torch.nn.Module]:
98
+ new_module = None
99
+
100
+ if isinstance(target, BaseTunerLayer):
101
+ target_base_layer = target.get_base_layer()
102
+ else:
103
+ target_base_layer = target
104
+
105
+ if is_aqlm_available() and isinstance(target_base_layer, QuantizedLinear):
106
+ new_module = AqlmLoraLinear(target, adapter_name, config=config, **kwargs)
107
+ target.qweight = target_base_layer.codes
108
+
109
+ return new_module
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/arrow.py ADDED
@@ -0,0 +1,476 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from __future__ import annotations
15
+
16
+ import os
17
+ from typing import Any
18
+
19
+ import torch
20
+ from torch import nn
21
+ from transformers import PreTrainedModel
22
+
23
+ from .config import ArrowConfig
24
+
25
+
26
+ TASK_ADAPTER_PREFIX = "task_"
27
+ GKS_ADAPTER_PREFIX = "gks_"
28
+
29
+
30
+ class ArrowLoraLinearLayer(nn.Module):
31
+ """
32
+ This class represent the main logic of the arrow routing algorithm for linear layers.
33
+ """
34
+
35
+ def __init__(self, in_features, arrow_config):
36
+ super().__init__()
37
+ # extra parameters needed for arrow
38
+ self.in_features = in_features
39
+ self._protos_ready = False
40
+ self.top_k = arrow_config.top_k
41
+ self.temperature = arrow_config.router_temperature
42
+ self.rng_seed = arrow_config.rng_seed
43
+ self.task_adapter_names = (
44
+ arrow_config.task_adapter_names.copy()
45
+ ) # Set in create_arrow_model() with this format: task_0, task_1, ...
46
+ self.gks_adapter_names = (
47
+ arrow_config.gks_adapter_names
48
+ ) # Set in create_arrow_model() with this format: gks_0, gks_1, ...
49
+ self.use_gks = arrow_config.use_gks
50
+ self.gks_done = False
51
+ self.gks_added_adapter_names = []
52
+ self.in_features = in_features
53
+ self.cast_input_dtype_enabled = True
54
+
55
+ @torch.no_grad()
56
+ def on_adapter_change(self, lora_A, lora_B):
57
+ """
58
+ Called when adapters are added/removed/renamed so Arrow can refresh its internal state before the next forward
59
+ pass.
60
+ """
61
+ all_ts_adapter_names = [
62
+ k
63
+ for k in lora_A.keys()
64
+ if k in lora_B and k != "arrow_router" and not (k.startswith("gks_") and k[len("gks_") :].isdigit())
65
+ ]
66
+
67
+ if sorted(self.task_adapter_names) == sorted(all_ts_adapter_names): # No changes in the ts_adapters
68
+ return
69
+
70
+ # Getting the name(s) of added adapter(s)
71
+ if len(self.task_adapter_names) < len(all_ts_adapter_names): # Adapter(s) are added.
72
+ self.gks_added_adapter_names = [x for x in all_ts_adapter_names if x not in self.task_adapter_names]
73
+
74
+ # Updating the task_adapter_names
75
+ self.task_adapter_names = all_ts_adapter_names.copy()
76
+ # Invalidate caches so they’ll be rebuilt lazily on next forward()
77
+ self._protos_ready = False
78
+ # GKS will be handled by self.gks_added_adapter_names
79
+
80
+ def top_right_singular_vec_from_BA(self, A, B, iters=15, eps=1e-8):
81
+ """
82
+ Computes the top *right* singular vector of ΔW = B @ A without forming ΔW.
83
+
84
+ Theory:
85
+ For any matrix M, the right singular vectors are the eigenvectors of Mᵀ M. If ΔW = B @ A (with A ∈
86
+ ℝ^{r×in}, B ∈ ℝ^{out×r}), then
87
+ ΔWᵀ ΔW = (B @ A)ᵀ (B @ A) = Aᵀ (Bᵀ B) A ∈ ℝ^{in×in}.
88
+ Therefore, the dominant right singular vector of ΔW is the dominant eigenvector of M := Aᵀ (Bᵀ B) A. We
89
+ find it by *power iteration* on the linear operator
90
+ v ↦ Aᵀ (Bᵀ B) (A v),
91
+ which avoids materializing ΔW (out×in) or M (in×in). The result lives in the input/token space (size =
92
+ in_features), which is exactly what Arrow needs. (Right singular vectors ≡ eigenvectors of MᵀM; power
93
+ iteration converges to the dominant eigenvector under mild conditions.)
94
+ =============================== Practical notes:
95
+ - We perform all iteration in float32 for numerical stability, then cast back
96
+ to the LoRA dtype/device before storing/using the prototype.
97
+ - Convergence is checked with a simple fixed-iter cap (`iters`) and/or
98
+ `allclose` tolerance (`tol`).
99
+ - The returned vector is unique up to sign (±), as with any singular vector.
100
+ Downstream code should be sign-invariant.
101
+ """
102
+
103
+ # A: (r, in), B: (out, r)
104
+ A32 = A.to(torch.float32)
105
+ B32 = B.to(torch.float32)
106
+ C = B32.T @ B32 # (r, r)
107
+
108
+ # Private RNG on A's device
109
+ gen = None
110
+ if self.rng_seed is not None:
111
+ gen = torch.Generator(device=A32.device.type)
112
+ gen.manual_seed(int(self.rng_seed))
113
+
114
+ # init vector in input space
115
+ v = torch.randn(A32.size(1), dtype=A32.dtype, device=A32.device, generator=gen)
116
+ v = v / (v.norm() + eps)
117
+
118
+ for _ in range(iters):
119
+ # w = (ΔW���ΔW) v = Aᵀ (BᵀB) (A v)
120
+ w = A32.T @ (C @ (A32 @ v))
121
+ v = w / (w.norm() + eps)
122
+
123
+ return v # fp32
124
+
125
+ @torch.no_grad()
126
+ def build_prototypes(self, lora_A, lora_B):
127
+ """
128
+ Computes a prototype vector for each LoRA module in every layer by applying Singular Value Decomposition (SVD)
129
+ to the `lora_A` matrix and extracting the top right singular vector.
130
+
131
+ These prototypes are later used to calculate the cosine similarity between each input token and each expert.
132
+ The resulting similarity scores serve as coefficients to compute a weighted average of the corresponding LoRA
133
+ modules, effectively routing each token through its most relevant experts.
134
+
135
+ ** This prototype computation is done is done once for all experts and is re-done on newly added adapters.**
136
+
137
+ Args:
138
+ lora_A : Matrices A in LoRA layer.
139
+ lora_B (optional): Matrices B in LoRA layer. Defaults to None.
140
+ """
141
+
142
+ if self._protos_ready:
143
+ return
144
+ protos = []
145
+ for name in self.task_adapter_names:
146
+ A = lora_A[name].weight # (r, in_features)
147
+ B = lora_B[name].weight # (out_features, r)
148
+
149
+ # Efficiently computing right singular vector of A @ B
150
+ proto32 = self.top_right_singular_vec_from_BA(A, B)
151
+
152
+ proto = proto32.to(dtype=A.dtype, device=A.device)
153
+ protos.append(proto)
154
+
155
+ proto_stack = torch.stack(protos, dim=0) # (E, in_features)
156
+
157
+ # Register the prototypes buffer with correct dtype/device consistent with A and B weights
158
+ self.register_buffer("prototypes", proto_stack, persistent=False)
159
+ self._protos_ready = True
160
+
161
+ @torch.no_grad()
162
+ def gen_know_sub(self, lora_A, lora_B):
163
+ """
164
+ This function performs General Knowledge Subtraction. It takes an average of provided general_adapters, and
165
+ subtract it from each task_adapter. This subtraction tries to purify the task adapters, based on
166
+ "forgetting-via-negation" principle. Forgetting-via-negation is a task-arithmetic operation, explained in:
167
+ https://huggingface.co/papers/2212.04089 The task adapters will be more focused and isolated, enhancing the
168
+ performance on new tasks.
169
+
170
+ Args:
171
+ lora_A : Matrices A in LoRA layer.
172
+ lora_B : Matrices A in LoRA layer.
173
+ """
174
+ if not self.use_gks:
175
+ return
176
+ elif self.gks_done and not self.gks_added_adapter_names:
177
+ return
178
+ else:
179
+ # 1) compute average A/B over gks_adapter_names
180
+ avg_A = torch.stack([lora_A[n].weight for n in self.gks_adapter_names], dim=0).mean(
181
+ 0
182
+ ) # shape (r, in_features)
183
+ avg_B = torch.stack([lora_B[n].weight for n in self.gks_adapter_names], dim=0).mean(
184
+ 0
185
+ ) # shape (out_features, r)
186
+
187
+ # 2) Subtract the average from task-specific experts
188
+ if self.gks_done is False: # GKS is done for all the experts, since it hasn't been done yet.
189
+ for name in self.task_adapter_names:
190
+ lora_A[name].weight.data.sub_(avg_A)
191
+ lora_B[name].weight.data.sub_(avg_B)
192
+ else: # GKS is only done on new added experts, since GKS has been done previously.
193
+ for name in self.gks_added_adapter_names:
194
+ lora_A[name].weight.data.sub_(avg_A)
195
+ lora_B[name].weight.data.sub_(avg_B)
196
+
197
+ # 3) Set gks_done flag as true, so we won't do it again in ArrowLinearVariant.forward().
198
+ self.gks_done = True
199
+ # Clearing the self.gks_added_adapter_names
200
+ self.gks_added_adapter_names = []
201
+
202
+ def _cast_input_dtype(self, x, dtype: torch.dtype):
203
+ """
204
+ Whether to cast the dtype of the input of the forward method.
205
+
206
+ Usually, we want to enable this to align the input dtype with the dtype of the weight, but by setting
207
+ layer.cast_input_dtype=False, this can be disabled if necessary.
208
+
209
+ Enabling or disabling can be managed via the peft.helpers.disable_lora_input_dtype_casting context manager.
210
+ """
211
+ if x is None: # useful e.g. if x is the bias, which can be None
212
+ return None
213
+
214
+ cast_input_dtype_enabled = getattr(self, "cast_input_dtype_enabled", True)
215
+ if (not cast_input_dtype_enabled) or (x.dtype == dtype):
216
+ return x
217
+ return x.to(dtype=dtype)
218
+
219
+ def forward(self, x, lora_A, lora_B, dropout, scaling):
220
+ """
221
+ Applies Arrow routing inside a LoRA layer.
222
+
223
+ Steps:
224
+ 1. Compute cosine similarity between each token representation and all adapter prototypes.
225
+ 2. Select the top-k experts per token and normalize their scores with a softmax.
226
+ 3. Project tokens into each selected expert’s low-rank space (A weights).
227
+ 4. Map back to the output space (B weights).
228
+ 5. Aggregate expert outputs via the weighted sum of their contributions.
229
+ 6. Apply dropout, scaling, and return the reshaped delta.
230
+
231
+ - Conceptually, this is a Mixture-of-Experts (MoE) over LoRA adapters,
232
+ where coefficients are derived from prototype similarity.
233
+
234
+ Returns:
235
+ delta: LoRA output adjustment computed by Arrow routing.
236
+ """
237
+ x = self._cast_input_dtype(x, lora_A[self.task_adapter_names[0]].weight.dtype)
238
+ B, *rest, F_in = x.shape
239
+ tok = x.view(-1, F_in) # (t, F_in)
240
+ t, E = tok.size(0), self.prototypes.size(0)
241
+
242
+ # We now turn scaling, which is a dict, to tensors in order to use them later
243
+ scales_tens = torch.tensor(
244
+ [scaling[n] for n in self.task_adapter_names],
245
+ device=tok.device,
246
+ dtype=tok.dtype,
247
+ ) # shape (E,)
248
+
249
+ # 1) similarity — sign-agnostic
250
+ sim = torch.abs(tok @ self.prototypes.T) # (t, E)
251
+
252
+ # 2) top-k + softmax over full E (non-top-k = -inf)
253
+ top_v, idx = torch.topk(sim, self.top_k, dim=1)
254
+ full_score = tok.new_full((t, E), float("-inf"))
255
+ full_score.scatter_(1, idx, top_v)
256
+ coeff = torch.softmax(full_score / self.temperature, dim=1) # (t, E)
257
+
258
+ # 3) stack all A and B weights once
259
+ # A_stack: (E, r, in_features), B_stack: (E, out_features, r)
260
+ A_stack = torch.stack([lora_A[n].weight for n in self.task_adapter_names], dim=0)
261
+ B_stack = torch.stack([lora_B[n].weight for n in self.task_adapter_names], dim=0)
262
+
263
+ # 4) project tokens into each expert’s low‑rank space:
264
+ # z[e] = tok @ A_e.T → shape (t, E, r)
265
+ z = torch.einsum("tf, erf -> ter", tok, A_stack)
266
+
267
+ # 5) lift back each expert’s output:
268
+ # y[e] = z[e] @ B_e.T → shape (t, E, out_features)
269
+ y = torch.einsum("ter, eor -> teo", z, B_stack)
270
+
271
+ # 6) apply per-expert scaling before the weighted sum
272
+ # y_scaled[t, e, o] = scales[e] * y[t, e, o]
273
+ y = y * scales_tens.view(1, -1, 1)
274
+
275
+ # 6) weighted sum over experts:
276
+ # delta_flat[t,o] = Σ_e coeff[t,e] * y[t,e,o]
277
+ delta_flat = torch.einsum("te, teo -> to", coeff, y) # (t, out_features)
278
+
279
+ # 7) dropout, scale, and reshape
280
+ delta = dropout(delta_flat)
281
+ out_dim = delta_flat.size(-1)
282
+ return delta.view(B, *rest, out_dim)
283
+
284
+
285
+ def check_loaded_lora_compatibility_arrow(model, adapter_names: list[str]):
286
+ """
287
+ After loading all adapters into `model`, check they share:
288
+ - the same LoRA rank (r)
289
+ - identical weight shapes
290
+ - identical sets of target_modules
291
+ Returns (sorted list of target module names, agreed rank r).
292
+ """
293
+ reference = None # {'r':…, 'shapes':(Ashape,Bshape), 'modules':set([...])}
294
+
295
+ for name in adapter_names:
296
+ curr_modules = set()
297
+ curr_r = None
298
+ curr_shapes = None
299
+
300
+ for full_name, module in model.named_modules():
301
+ if hasattr(module, "lora_A") and name in module.lora_A:
302
+ A = module.lora_A[name].weight
303
+ B = module.lora_B[name].weight
304
+ mod_name = full_name.split(".")[-1]
305
+ curr_modules.add(mod_name)
306
+ # A has shape (r, in_features); B has shape (out_features, r)
307
+ curr_r = A.shape[0]
308
+ curr_shapes = (A.shape, B.shape)
309
+
310
+ if reference is None:
311
+ reference = {"r": curr_r, "shapes": curr_shapes, "modules": curr_modules}
312
+ else:
313
+ if curr_r != reference["r"]:
314
+ raise ValueError(f"[{name}] rank mismatch: {curr_r} != {reference['r']}")
315
+ if curr_shapes != reference["shapes"]:
316
+ raise ValueError(f"[{name}] shape mismatch: {curr_shapes} != {reference['shapes']}")
317
+ if curr_modules != reference["modules"]:
318
+ raise ValueError(
319
+ f"[{name}] target_modules mismatch:\n"
320
+ f" this adapter -> {sorted(curr_modules)}\n"
321
+ f" reference -> {sorted(reference['modules'])}"
322
+ )
323
+
324
+ agreed_modules = sorted(reference["modules"])
325
+ return agreed_modules, int(reference["r"])
326
+
327
+
328
+ def ensure_adapters_target_linear_layers_only(model, adapter_names: list[str]):
329
+ """
330
+ Validate that every module holding LoRA weights for any of `adapter_names` is Linear-like: nn.Linear,
331
+ bitsandbytes.nn.Linear4bit, nn.Conv1d, or transformers.models.gpt2.modeling_gpt2.Conv1D. If not, raise.
332
+ """
333
+ import torch.nn as nn
334
+
335
+ Linear4bit = None
336
+ try:
337
+ import bitsandbytes as bnb # type: ignore
338
+
339
+ Linear4bit = bnb.nn.Linear4bit
340
+ except ImportError:
341
+ pass
342
+
343
+ HFConv1D = None
344
+ try:
345
+ from transformers.models.gpt2.modeling_gpt2 import Conv1D as HFConv1D # type: ignore
346
+ except ImportError:
347
+ pass
348
+
349
+ allowed_types = (nn.Linear, nn.Conv1d)
350
+ if Linear4bit is not None:
351
+ allowed_types = allowed_types + (Linear4bit,)
352
+ if HFConv1D is not None:
353
+ allowed_types = allowed_types + (HFConv1D,)
354
+
355
+ offenders = []
356
+
357
+ for full_name, module in model.named_modules():
358
+ if hasattr(module, "lora_A"):
359
+ for name in adapter_names:
360
+ if name in getattr(module, "lora_A", {}):
361
+ base = getattr(module, "base_layer", None) or getattr(module, "original_module", None)
362
+ layer_to_check = base if base is not None else module
363
+
364
+ if not isinstance(layer_to_check, allowed_types):
365
+ offenders.append((name, full_name, type(layer_to_check).__name__))
366
+
367
+ if offenders:
368
+ lines = [
369
+ "LoRA adapters must only target Linear-like layers "
370
+ "(nn.Linear, nn.Conv1d, HF Conv1D, or bitsandbytes.nn.Linear4bit). Found:"
371
+ ]
372
+ for name, full_name, tname in offenders:
373
+ lines.append(f" - adapter '{name}' on module '{full_name}' of type {tname}")
374
+ raise TypeError("\n".join(lines))
375
+
376
+
377
+ def _resolve_adapter_source(path: str) -> tuple[str, str | None]:
378
+ """
379
+ Resolve a user-provided adapter `path` into (model_id, subfolder).
380
+
381
+ Supports:
382
+ - Local path to a folder that contains `adapter_config.json`
383
+ - Hub path with subfolder, e.g. "user/repo/ts_expert_0[/more/...]", which becomes:
384
+ model_id="user/repo", subfolder="ts_expert_0[/more/...]"
385
+ - Plain Hub repo id "user/repo" (no subfolder)
386
+ """
387
+ if os.path.isdir(path):
388
+ if not os.path.isfile(os.path.join(path, "adapter_config.json")):
389
+ raise ValueError(f"Local adapter path '{path}' does not contain 'adapter_config.json'.")
390
+ return path, None
391
+
392
+ parts = path.strip("/").split("/")
393
+ if len(parts) >= 2:
394
+ model_id = "/".join(parts[:2])
395
+ if len(parts) > 2:
396
+ subfolder = "/".join(parts[2:])
397
+ return model_id, subfolder
398
+ return model_id, None
399
+
400
+ return path, None
401
+
402
+
403
+ def create_arrow_model(
404
+ base_model: PreTrainedModel,
405
+ task_specific_adapter_paths: list[str],
406
+ arrow_config: ArrowConfig,
407
+ general_adapter_paths: list[str] | None = None,
408
+ **adapter_kwargs: Any,
409
+ ):
410
+ if task_specific_adapter_paths is None or len(task_specific_adapter_paths) == 0:
411
+ raise ValueError("`task_specific_adapter_paths` should contain at least one adapter path")
412
+
413
+ from peft import LoraConfig, PeftModel
414
+
415
+ model_id0, sub0 = _resolve_adapter_source(task_specific_adapter_paths[0])
416
+ initial_ts_expert_name = f"{TASK_ADAPTER_PREFIX}0"
417
+
418
+ first_kwargs = dict(adapter_kwargs)
419
+ if sub0 is not None and "subfolder" not in first_kwargs:
420
+ first_kwargs["subfolder"] = sub0
421
+
422
+ model = PeftModel.from_pretrained(
423
+ base_model,
424
+ model_id=model_id0,
425
+ adapter_name=initial_ts_expert_name,
426
+ **first_kwargs,
427
+ )
428
+
429
+ for i in range(1, len(task_specific_adapter_paths)):
430
+ ts_expert_name = f"{TASK_ADAPTER_PREFIX}{i}"
431
+ mid, sub = _resolve_adapter_source(task_specific_adapter_paths[i])
432
+ more_kwargs = dict(adapter_kwargs)
433
+ if sub is not None and "subfolder" not in more_kwargs:
434
+ more_kwargs["subfolder"] = sub
435
+ model.load_adapter(
436
+ model_id=mid,
437
+ adapter_name=ts_expert_name,
438
+ **more_kwargs,
439
+ )
440
+ arrow_config.task_adapter_names = [f"{TASK_ADAPTER_PREFIX}{i}" for i in range(len(task_specific_adapter_paths))]
441
+
442
+ if arrow_config.use_gks:
443
+ if general_adapter_paths is None or len(general_adapter_paths) == 0:
444
+ raise ValueError("You should provide general LoRA paths if you want to use GenKnowSub.")
445
+ for i in range(len(general_adapter_paths)):
446
+ gen_expert_name = f"{GKS_ADAPTER_PREFIX}{i}"
447
+ mid, sub = _resolve_adapter_source(general_adapter_paths[i])
448
+ gks_kwargs = dict(adapter_kwargs)
449
+ if sub is not None and "subfolder" not in gks_kwargs:
450
+ gks_kwargs["subfolder"] = sub
451
+ model.load_adapter(
452
+ model_id=mid,
453
+ adapter_name=gen_expert_name,
454
+ **gks_kwargs,
455
+ )
456
+ arrow_config.gks_adapter_names = [f"{GKS_ADAPTER_PREFIX}{i}" for i in range(len(general_adapter_paths))]
457
+ else:
458
+ arrow_config.gks_adapter_names = []
459
+
460
+ target_modules, r = check_loaded_lora_compatibility_arrow(
461
+ model, adapter_names=arrow_config.task_adapter_names + arrow_config.gks_adapter_names
462
+ )
463
+
464
+ ensure_adapters_target_linear_layers_only(
465
+ model, adapter_names=arrow_config.task_adapter_names + arrow_config.gks_adapter_names
466
+ )
467
+
468
+ router_cfg = LoraConfig(
469
+ arrow_config=arrow_config,
470
+ target_modules=target_modules,
471
+ r=r,
472
+ )
473
+ model.add_adapter(adapter_name="arrow_router", peft_config=router_cfg)
474
+ model.set_adapter("arrow_router")
475
+
476
+ return model
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/awq.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import Any, Optional
15
+
16
+ import torch
17
+
18
+ from peft.import_utils import is_gptqmodel_available
19
+ from peft.tuners.lora.layer import LoraLayer
20
+ from peft.tuners.tuners_utils import BaseTunerLayer
21
+
22
+ from .config import LoraConfig
23
+
24
+
25
+ class AwqLoraLinear(torch.nn.Module, LoraLayer):
26
+ def __init__(
27
+ self,
28
+ base_layer,
29
+ adapter_name,
30
+ config: LoraConfig,
31
+ r: int = 0,
32
+ lora_alpha: int = 1,
33
+ **kwargs,
34
+ ):
35
+ if config.use_dora:
36
+ raise ValueError(f"{self.__class__.__name__} does not support DoRA yet, please set it to False")
37
+
38
+ super().__init__()
39
+ LoraLayer.__init__(self, base_layer)
40
+
41
+ # self.base_layer and self.quant_linear_module are the same; we need the former for consistency and the latter
42
+ # for backwards compatibility
43
+ self.quant_linear_module = base_layer
44
+
45
+ self._active_adapter = adapter_name
46
+ self.update_layer(
47
+ adapter_name,
48
+ r,
49
+ lora_alpha=lora_alpha,
50
+ config=config,
51
+ )
52
+
53
+ def forward(self, x: torch.Tensor):
54
+ result = self.quant_linear_module(x)
55
+
56
+ if self.disable_adapters:
57
+ return result
58
+
59
+ for active_adapter in self.active_adapters:
60
+ if active_adapter not in self.lora_A.keys():
61
+ continue
62
+ lora_A = self.lora_A[active_adapter]
63
+ lora_B = self.lora_B[active_adapter]
64
+ dropout = self.lora_dropout[active_adapter]
65
+ scaling = self.scaling[active_adapter]
66
+
67
+ requires_conversion = not torch.is_autocast_enabled()
68
+ if requires_conversion:
69
+ expected_dtype = result.dtype
70
+ x = self._cast_input_dtype(x, lora_A.weight.dtype)
71
+
72
+ output = lora_B(lora_A(dropout(x)))
73
+ if requires_conversion:
74
+ output = output.to(expected_dtype)
75
+ output = output * scaling
76
+ result = result + output
77
+ return result
78
+
79
+ def __repr__(self) -> str:
80
+ rep = super().__repr__()
81
+ return "lora." + rep
82
+
83
+
84
+ def dispatch_awq(
85
+ target: torch.nn.Module,
86
+ adapter_name: str,
87
+ config: LoraConfig,
88
+ **kwargs: Any,
89
+ ) -> Optional[torch.nn.Module]:
90
+ new_module = None
91
+
92
+ if isinstance(target, BaseTunerLayer):
93
+ target_base_layer = target.get_base_layer()
94
+ else:
95
+ target_base_layer = target
96
+
97
+ if is_gptqmodel_available():
98
+ from gptqmodel.nn_modules.qlinear.gemm_awq import AwqGEMMQuantLinear
99
+
100
+ if isinstance(target_base_layer, AwqGEMMQuantLinear):
101
+ new_module = AwqLoraLinear(target, adapter_name, config=config, **kwargs)
102
+ target.qweight = target_base_layer.qweight
103
+
104
+ return new_module
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/bnb.py ADDED
@@ -0,0 +1,587 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from __future__ import annotations
15
+
16
+ import warnings
17
+ from typing import Any, Optional
18
+
19
+ import bitsandbytes as bnb
20
+ import torch
21
+
22
+ from peft.import_utils import is_bnb_4bit_available, is_bnb_available
23
+ from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge
24
+ from peft.utils.integrations import dequantize_bnb_weight
25
+ from peft.utils.other import transpose
26
+
27
+ from .config import LoraConfig
28
+ from .layer import LoraLayer, LoraVariant
29
+
30
+
31
+ VARIANT_KWARG_KEYS = ["alora_offsets"]
32
+
33
+ if is_bnb_available():
34
+
35
+ class Linear8bitLt(torch.nn.Module, LoraLayer):
36
+ # Lora implemented in a dense layer
37
+ def __init__(
38
+ self,
39
+ base_layer: torch.nn.Module,
40
+ adapter_name: str,
41
+ config: LoraConfig,
42
+ r: int = 0,
43
+ lora_alpha: int = 1,
44
+ **kwargs,
45
+ ) -> None:
46
+ super().__init__()
47
+ LoraLayer.__init__(self, base_layer)
48
+ self.fan_in_fan_out = False
49
+
50
+ self._active_adapter = adapter_name
51
+ self.update_layer(
52
+ adapter_name,
53
+ r,
54
+ lora_alpha=lora_alpha,
55
+ config=config,
56
+ )
57
+
58
+ def resolve_lora_variant(self, *, config, **kwargs) -> Optional[LoraVariant]:
59
+ if config.arrow_config is not None:
60
+ from .variants import ArrowLinearVariant
61
+
62
+ return ArrowLinearVariant()
63
+
64
+ use_alora = config.alora_invocation_tokens is not None
65
+ if not config.use_dora and not use_alora:
66
+ return None
67
+
68
+ from .variants import ALoraLinearVariant, DoraLinearVariant
69
+
70
+ if use_alora:
71
+ return ALoraLinearVariant()
72
+ else:
73
+ return DoraLinearVariant()
74
+
75
+ def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None:
76
+ """
77
+ Merge the active adapter weights into the base weights
78
+
79
+ Args:
80
+ safe_merge (`bool`, *optional*):
81
+ If True, the merge operation will be performed in a copy of the original weights and check for NaNs
82
+ before merging the weights. This is useful if you want to check if the merge operation will produce
83
+ NaNs. Defaults to `False`.
84
+ adapter_names (`list[str]`, *optional*):
85
+ The list of adapter names that should be merged. If None, all active adapters will be merged.
86
+ Defaults to `None`.
87
+ """
88
+ adapter_names = check_adapters_to_merge(self, adapter_names)
89
+ if not adapter_names:
90
+ # no adapter to merge
91
+ return
92
+
93
+ for active_adapter in adapter_names:
94
+ if active_adapter not in self.lora_A.keys():
95
+ continue
96
+
97
+ warnings.warn(
98
+ "Merge lora module to 8-bit linear may get different generations due to rounding errors."
99
+ )
100
+
101
+ weight = self.get_base_layer().weight
102
+ state = self.get_base_layer().state
103
+ if state.SCB is None:
104
+ state.SCB = weight.SCB
105
+
106
+ # Dequantize the result of identity matrix and int8 weight because bitsandbytes does not support int8
107
+ # dequantization directly
108
+ output = dequantize_bnb_weight(weight, state=state)
109
+ if active_adapter not in self.lora_variant: # vanilla LoRA
110
+ lora_data = self.get_delta_weight(active_adapter)
111
+ w_data = output.to(lora_data.dtype).to(lora_data.device) + lora_data
112
+ else:
113
+ w_data = self.lora_variant[active_adapter].merge_safe(self, active_adapter, output)
114
+
115
+ if safe_merge and not torch.isfinite(w_data).all():
116
+ raise ValueError(
117
+ f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken"
118
+ )
119
+
120
+ self.get_base_layer().weight = bnb.nn.Int8Params(
121
+ w_data.to("cpu"), requires_grad=False, has_fp16_weights=weight.has_fp16_weights
122
+ ).to(weight.device)
123
+
124
+ if self.lora_bias[active_adapter]:
125
+ bias_data = self.get_base_layer().bias.data + self.lora_B[active_adapter].bias
126
+ if safe_merge and not torch.isfinite(bias_data):
127
+ raise ValueError(
128
+ f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken"
129
+ )
130
+ self.get_base_layer().bias.data = bias_data
131
+
132
+ state.reset_grads()
133
+ self.merged_adapters.append(active_adapter)
134
+
135
+ def unmerge(self) -> None:
136
+ """
137
+ This method unmerges all merged adapter layers from the base weights.
138
+ """
139
+ if not self.merged:
140
+ warnings.warn("Already unmerged. Nothing to do.")
141
+ return
142
+
143
+ while len(self.merged_adapters) > 0:
144
+ active_adapter = self.merged_adapters.pop()
145
+ if active_adapter not in self.lora_A.keys():
146
+ continue
147
+ warnings.warn(
148
+ "Unmerge lora module to 8-bit linear may get different generations due to rounding errors."
149
+ )
150
+
151
+ weight = self.get_base_layer().weight
152
+ state = self.get_base_layer().state
153
+ if state.SCB is None:
154
+ state.SCB = weight.SCB
155
+ output = dequantize_bnb_weight(weight, state=state)
156
+
157
+ if active_adapter not in self.lora_variant: # vanilla LoRA
158
+ lora_data = self.get_delta_weight(active_adapter)
159
+ w_data = output.to(lora_data.dtype).to(lora_data.device) - lora_data
160
+ else:
161
+ w_data = self.lora_variant[active_adapter].unmerge(self, active_adapter, output)
162
+
163
+ self.get_base_layer().weight = bnb.nn.Int8Params(
164
+ w_data.to("cpu"), requires_grad=False, has_fp16_weights=weight.has_fp16_weights
165
+ ).to(weight.device)
166
+
167
+ if self.lora_bias[active_adapter]:
168
+ self.get_base_layer().bias.data -= self.lora_B[active_adapter].bias
169
+ state.reset_grads()
170
+
171
+ def get_delta_weight(self, adapter):
172
+ return (
173
+ transpose(
174
+ self.lora_B[adapter].weight @ self.lora_A[adapter].weight,
175
+ False,
176
+ )
177
+ * self.scaling[adapter]
178
+ )
179
+
180
+ def _mixed_batch_forward(
181
+ self, x: torch.Tensor, *args: Any, adapter_names: list[str], **kwargs: Any
182
+ ) -> torch.Tensor:
183
+ # This is a special method that handles the case when users pass the argument `adapter_names`. This is an
184
+ # extra argument that allows mixing different adapters in the same batch at inference time.
185
+ variant_kwargs = {k: kwargs.pop(k, None) for k in VARIANT_KWARG_KEYS} # don't pass these to base_layer
186
+ result = self.base_layer(x, *args, **kwargs)
187
+
188
+ unique_adapters = set(adapter_names)
189
+ sub_batch_indices_list = []
190
+ for adapter in unique_adapters:
191
+ sub_batch_indices_list.append([index for index, item in enumerate(adapter_names) if item == adapter])
192
+
193
+ for i, active_adapter in enumerate(unique_adapters):
194
+ if active_adapter == "__base__":
195
+ continue
196
+ if active_adapter not in self.lora_A.keys():
197
+ continue
198
+
199
+ lora_A = self.lora_A[active_adapter]
200
+ lora_B = self.lora_B[active_adapter]
201
+ dropout = self.lora_dropout[active_adapter]
202
+ scaling = self.scaling[active_adapter]
203
+
204
+ requires_conversion = not torch.is_autocast_enabled()
205
+ if requires_conversion:
206
+ expected_dtype = result.dtype
207
+ x = self._cast_input_dtype(x, lora_A.weight.dtype)
208
+
209
+ # getting the sub-batch, passing it to LoRA layers and updating the corresponding indices of the linear
210
+ # layer output
211
+ sub_batch = x[sub_batch_indices_list[i]]
212
+ if active_adapter not in self.lora_variant: # vanilla LoRA:
213
+ output = lora_B(lora_A(dropout(sub_batch))) * scaling
214
+ if requires_conversion:
215
+ output = output.to(expected_dtype)
216
+ result[sub_batch_indices_list[i]] += output
217
+ else:
218
+ alora_offsets = variant_kwargs.get("alora_offsets", None)
219
+ if alora_offsets is not None:
220
+ variant_kwargs["alora_offsets"] = [alora_offsets[j] for j in sub_batch_indices_list[i]]
221
+ output = self.lora_variant[active_adapter].forward(
222
+ self,
223
+ active_adapter=active_adapter,
224
+ x=sub_batch,
225
+ result=result[sub_batch_indices_list[i]],
226
+ **variant_kwargs,
227
+ **kwargs,
228
+ )
229
+ if requires_conversion:
230
+ output = output.to(expected_dtype)
231
+ result[sub_batch_indices_list[i]] = output
232
+
233
+ return result
234
+
235
+ def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor:
236
+ self._check_forward_args(x, *args, **kwargs)
237
+ adapter_names = kwargs.pop("adapter_names", None)
238
+ variant_kwargs = {k: kwargs.pop(k, None) for k in VARIANT_KWARG_KEYS} # don't pass these to base_layer
239
+
240
+ if self.disable_adapters:
241
+ if self.merged:
242
+ self.unmerge()
243
+ result = self.base_layer(x, *args, **kwargs)
244
+ elif adapter_names is not None:
245
+ result = self._mixed_batch_forward(x, *args, adapter_names=adapter_names, **variant_kwargs, **kwargs)
246
+ elif self.merged:
247
+ result = self.base_layer(x, *args, **kwargs)
248
+ else:
249
+ result = self.base_layer(x, *args, **kwargs)
250
+ for active_adapter in self.active_adapters:
251
+ if active_adapter not in self.lora_A.keys():
252
+ continue
253
+ lora_A = self.lora_A[active_adapter]
254
+ lora_B = self.lora_B[active_adapter]
255
+ dropout = self.lora_dropout[active_adapter]
256
+ scaling = self.scaling[active_adapter]
257
+
258
+ requires_conversion = not torch.is_autocast_enabled()
259
+ if requires_conversion:
260
+ expected_dtype = result.dtype
261
+ x = self._cast_input_dtype(x, lora_A.weight.dtype)
262
+
263
+ if active_adapter not in self.lora_variant: # vanilla LoRA
264
+ output = lora_B(lora_A(dropout(x))) * scaling
265
+ if requires_conversion:
266
+ output = output.to(expected_dtype)
267
+ result = result + output
268
+ else:
269
+ result = self.lora_variant[active_adapter].forward(
270
+ self,
271
+ active_adapter=active_adapter,
272
+ x=x,
273
+ result=result,
274
+ **variant_kwargs,
275
+ **kwargs,
276
+ )
277
+ if requires_conversion:
278
+ result = result.to(expected_dtype)
279
+
280
+ return result
281
+
282
+ def __repr__(self) -> str:
283
+ rep = super().__repr__()
284
+ return "lora." + rep
285
+
286
+ def dispatch_bnb_8bit(target: torch.nn.Module, adapter_name: str, config: LoraConfig, **kwargs):
287
+ new_module = None
288
+
289
+ if isinstance(target, BaseTunerLayer):
290
+ target_base_layer = target.get_base_layer()
291
+ else:
292
+ target_base_layer = target
293
+
294
+ loaded_in_8bit = kwargs.get("loaded_in_8bit", False)
295
+ if loaded_in_8bit and isinstance(target_base_layer, bnb.nn.Linear8bitLt):
296
+ eightbit_kwargs = kwargs.copy()
297
+ eightbit_kwargs.update(
298
+ {
299
+ "has_fp16_weights": target.state.has_fp16_weights,
300
+ "threshold": target.state.threshold,
301
+ "index": target.index,
302
+ }
303
+ )
304
+ new_module = Linear8bitLt(target, adapter_name, config=config, **eightbit_kwargs)
305
+
306
+ return new_module
307
+
308
+
309
+ if is_bnb_4bit_available():
310
+
311
+ class Linear4bit(torch.nn.Module, LoraLayer):
312
+ # Lora implemented in a dense layer
313
+ def __init__(
314
+ self,
315
+ base_layer: torch.nn.Module,
316
+ adapter_name: str,
317
+ config: LoraConfig,
318
+ r: int = 0,
319
+ lora_alpha: int = 1,
320
+ **kwargs,
321
+ ) -> None:
322
+ super().__init__()
323
+ LoraLayer.__init__(self, base_layer)
324
+ self.fan_in_fan_out = False
325
+
326
+ self._active_adapter = adapter_name
327
+ self.update_layer(
328
+ adapter_name,
329
+ r,
330
+ lora_alpha=lora_alpha,
331
+ config=config,
332
+ )
333
+
334
+ def resolve_lora_variant(self, *, config: LoraConfig, **kwargs) -> Optional[LoraVariant]:
335
+ if config.arrow_config is not None:
336
+ from .variants import ArrowLinearVariant
337
+
338
+ return ArrowLinearVariant()
339
+
340
+ use_alora = config.alora_invocation_tokens is not None
341
+ if not config.use_dora and not use_alora:
342
+ return None
343
+
344
+ from .variants import ALoraLinearVariant, DoraLinearVariant
345
+
346
+ if use_alora:
347
+ return ALoraLinearVariant()
348
+ else:
349
+ return DoraLinearVariant()
350
+
351
+ def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None:
352
+ """
353
+ Merge the active adapter weights into the base weights
354
+
355
+ Args:
356
+ safe_merge (`bool`, *optional*):
357
+ If True, the merge operation will be performed in a copy of the original weights and check for NaNs
358
+ before merging the weights. This is useful if you want to check if the merge operation will produce
359
+ NaNs. Defaults to `False`.
360
+ adapter_names (`list[str]`, *optional*):
361
+ The list of adapter names that should be merged. If None, all active adapters will be merged.
362
+ Defaults to `None`.
363
+ """
364
+ adapter_names = check_adapters_to_merge(self, adapter_names)
365
+ if not adapter_names:
366
+ # no adapter to merge
367
+ return
368
+
369
+ for active_adapter in adapter_names:
370
+ if active_adapter not in self.lora_A.keys():
371
+ continue
372
+
373
+ warnings.warn(
374
+ "Merge lora module to 4-bit linear may get different generations due to rounding errors."
375
+ )
376
+ # Refer to https://gist.github.com/ChrisHayduk/1a53463331f52dca205e55982baf9930
377
+ weight = self.get_base_layer().weight
378
+ kwargs = weight.__dict__
379
+
380
+ output = dequantize_bnb_weight(weight, state=weight.quant_state)
381
+ if active_adapter not in self.lora_variant: # vanilla LoRA
382
+ lora_data = self.get_delta_weight(active_adapter)
383
+ w_data = output + lora_data
384
+ else:
385
+ w_data = self.lora_variant[active_adapter].merge_safe(self, active_adapter, output)
386
+
387
+ if safe_merge and not torch.isfinite(w_data).all():
388
+ raise ValueError(
389
+ f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken"
390
+ )
391
+
392
+ if "bnb_quantized" in kwargs:
393
+ kwargs["bnb_quantized"] = False
394
+ kwargs["requires_grad"] = False
395
+ kwargs.pop("data", None)
396
+ # torch.compile can introduce attributes preceded by '_', remove them
397
+ kwargs = {k: v for k, v in kwargs.items() if not k.startswith("_")}
398
+ self.get_base_layer().weight = bnb.nn.Params4bit(w_data.to("cpu"), **kwargs).to(weight.device)
399
+
400
+ if self.lora_bias[active_adapter]:
401
+ bias_data = self.get_base_layer().bias.data + self.lora_B[active_adapter].bias
402
+ if safe_merge and not torch.isfinite(bias_data):
403
+ raise ValueError(
404
+ f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken"
405
+ )
406
+ self.get_base_layer().bias.data = bias_data
407
+
408
+ self.merged_adapters.append(active_adapter)
409
+
410
+ def unmerge(self) -> None:
411
+ """
412
+ This method unmerges all merged adapter layers from the base weights.
413
+ """
414
+ if not self.merged:
415
+ warnings.warn("Already unmerged. Nothing to do.")
416
+ return
417
+
418
+ while len(self.merged_adapters) > 0:
419
+ active_adapter = self.merged_adapters.pop()
420
+ if active_adapter not in self.lora_A.keys():
421
+ continue
422
+ warnings.warn(
423
+ "Unmerge lora module to 4-bit linear may get different generations due to rounding errors."
424
+ )
425
+
426
+ weight = self.get_base_layer().weight
427
+ kwargs = weight.__dict__
428
+ output = dequantize_bnb_weight(weight, state=weight.quant_state)
429
+
430
+ if active_adapter not in self.lora_variant: # vanilla LoRA
431
+ lora_data = self.get_delta_weight(active_adapter)
432
+ w_data = output - lora_data
433
+ else:
434
+ w_data = self.lora_variant[active_adapter].unmerge(self, active_adapter, output)
435
+
436
+ if "bnb_quantized" in kwargs:
437
+ kwargs["bnb_quantized"] = False
438
+ kwargs["requires_grad"] = False
439
+ kwargs.pop("data", None)
440
+ self.get_base_layer().weight = bnb.nn.Params4bit(w_data.to("cpu"), **kwargs).to(weight.device)
441
+
442
+ if self.lora_bias[active_adapter]:
443
+ self.get_base_layer().bias.data -= self.lora_B[active_adapter].bias
444
+
445
+ def get_delta_weight(self, adapter):
446
+ return (
447
+ transpose(
448
+ self.lora_B[adapter].weight @ self.lora_A[adapter].weight,
449
+ False,
450
+ )
451
+ * self.scaling[adapter]
452
+ )
453
+
454
+ def _mixed_batch_forward(
455
+ self, x: torch.Tensor, *args: Any, adapter_names: list[str], **kwargs: Any
456
+ ) -> torch.Tensor:
457
+ # This is a special method that handles the case when users pass the argument `adapter_names`. This is an
458
+ # extra argument that allows mixing different adapters in the same batch at inference time.
459
+ variant_kwargs = {k: kwargs.pop(k, None) for k in VARIANT_KWARG_KEYS} # don't pass these to base_layer
460
+ result = self.base_layer(x, *args, **kwargs)
461
+
462
+ unique_adapters = set(adapter_names)
463
+ sub_batch_indices_list = []
464
+ for adapter in unique_adapters:
465
+ sub_batch_indices_list.append([index for index, item in enumerate(adapter_names) if item == adapter])
466
+
467
+ for i, active_adapter in enumerate(unique_adapters):
468
+ if active_adapter == "__base__":
469
+ continue
470
+ if active_adapter not in self.lora_A.keys():
471
+ continue
472
+
473
+ lora_A = self.lora_A[active_adapter]
474
+ lora_B = self.lora_B[active_adapter]
475
+ dropout = self.lora_dropout[active_adapter]
476
+ scaling = self.scaling[active_adapter]
477
+
478
+ requires_conversion = not torch.is_autocast_enabled()
479
+ if requires_conversion:
480
+ expected_dtype = result.dtype
481
+ x = self._cast_input_dtype(x, lora_A.weight.dtype)
482
+
483
+ # getting the sub-batch, passing it to LoRA layers and updating the corresponding indices of the linear
484
+ # layer output
485
+ sub_batch = x[sub_batch_indices_list[i]]
486
+ if active_adapter not in self.lora_variant: # vanilla LoRA
487
+ output = lora_B(lora_A(dropout(sub_batch))) * scaling
488
+ if requires_conversion:
489
+ output = output.to(expected_dtype)
490
+ result[sub_batch_indices_list[i]] += output
491
+ else:
492
+ alora_offsets = variant_kwargs.get("alora_offsets", None)
493
+ if alora_offsets is not None:
494
+ variant_kwargs["alora_offsets"] = [alora_offsets[j] for j in sub_batch_indices_list[i]]
495
+ output = self.lora_variant[active_adapter].forward(
496
+ self,
497
+ active_adapter=active_adapter,
498
+ x=sub_batch,
499
+ result=result[sub_batch_indices_list[i]],
500
+ **variant_kwargs,
501
+ **kwargs,
502
+ )
503
+ if requires_conversion:
504
+ output = output.to(expected_dtype)
505
+ result[sub_batch_indices_list[i]] = output
506
+
507
+ return result
508
+
509
+ def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor:
510
+ self._check_forward_args(x, *args, **kwargs)
511
+ adapter_names = kwargs.pop("adapter_names", None)
512
+ variant_kwargs = {k: kwargs.pop(k, None) for k in VARIANT_KWARG_KEYS} # don't pass these to base_layer
513
+
514
+ if self.disable_adapters:
515
+ if self.merged:
516
+ self.unmerge()
517
+ result = self.base_layer(x, *args, **kwargs)
518
+ elif adapter_names is not None:
519
+ result = self._mixed_batch_forward(x, *args, adapter_names=adapter_names, **variant_kwargs, **kwargs)
520
+ elif self.merged:
521
+ result = self.base_layer(x, *args, **kwargs)
522
+ else:
523
+ result = self.base_layer(x, *args, **kwargs)
524
+ # As per Tim Dettmers, for 4bit, we need to defensively clone here.
525
+ # The reason is that in some cases, an error can occur that backprop
526
+ # does not work on a manipulated view. This issue may be solved with
527
+ # newer PyTorch versions but this would need extensive testing to be
528
+ # sure.
529
+ result = result.clone()
530
+
531
+ for active_adapter in self.active_adapters:
532
+ if active_adapter not in self.lora_A.keys():
533
+ continue
534
+ lora_A = self.lora_A[active_adapter]
535
+ lora_B = self.lora_B[active_adapter]
536
+ dropout = self.lora_dropout[active_adapter]
537
+ scaling = self.scaling[active_adapter]
538
+
539
+ requires_conversion = not torch.is_autocast_enabled()
540
+ if requires_conversion:
541
+ expected_dtype = result.dtype
542
+ x = self._cast_input_dtype(x, lora_A.weight.dtype)
543
+
544
+ if active_adapter not in self.lora_variant: # vanilla LoRA
545
+ output = lora_B(lora_A(dropout(x))) * scaling
546
+ if requires_conversion:
547
+ output = output.to(expected_dtype)
548
+ result = result + output
549
+ else:
550
+ result = self.lora_variant[active_adapter].forward(
551
+ self,
552
+ active_adapter=active_adapter,
553
+ x=x,
554
+ result=result,
555
+ **variant_kwargs,
556
+ **kwargs,
557
+ )
558
+ if requires_conversion:
559
+ result = result.to(expected_dtype)
560
+
561
+ return result
562
+
563
+ def __repr__(self) -> str:
564
+ rep = super().__repr__()
565
+ return "lora." + rep
566
+
567
+ def dispatch_bnb_4bit(target: torch.nn.Module, adapter_name: str, config: LoraConfig, **kwargs):
568
+ new_module = None
569
+
570
+ if isinstance(target, BaseTunerLayer):
571
+ target_base_layer = target.get_base_layer()
572
+ else:
573
+ target_base_layer = target
574
+
575
+ loaded_in_4bit = kwargs.get("loaded_in_4bit", False)
576
+ if loaded_in_4bit and is_bnb_4bit_available() and isinstance(target_base_layer, bnb.nn.Linear4bit):
577
+ fourbit_kwargs = kwargs.copy()
578
+ fourbit_kwargs.update(
579
+ {
580
+ "compute_dtype": target_base_layer.compute_dtype,
581
+ "compress_statistics": target_base_layer.weight.compress_statistics,
582
+ "quant_type": target_base_layer.weight.quant_type,
583
+ }
584
+ )
585
+ new_module = Linear4bit(target, adapter_name, config=config, **fourbit_kwargs)
586
+
587
+ return new_module
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/dora.py ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from copy import deepcopy
16
+ from functools import wraps
17
+ from typing import Any, Optional
18
+
19
+ import torch
20
+ import torch.nn.functional as F
21
+ from torch import nn
22
+
23
+ from peft.utils.integrations import dequantize_module_weight, gather_params_ctx
24
+ from peft.utils.other import transpose
25
+
26
+
27
+ ENABLE_DORA_CACHING = False
28
+ """Whether to enable DoRA caching, which makes it faster at inference but requires more memory"""
29
+
30
+
31
+ def cache_decorator(cache_key: str):
32
+ """Caching decorator for DoRA
33
+
34
+ Caching is only enabled if ENABLE_DORA_CACHING is set to True (default: False), when in eval mode, and when the
35
+ adapter_name is passed (e.g. not during layer initialization).
36
+
37
+ """
38
+
39
+ def cache_value(func):
40
+ @wraps(func)
41
+ def wrapper(self, *args, **kwargs):
42
+ # if adapter_name is not passed, no caching
43
+ adapter_name = kwargs.get("adapter_name")
44
+ if (not ENABLE_DORA_CACHING) or self.training or (adapter_name is None):
45
+ self._cache_clear()
46
+ return func(self, *args, **kwargs)
47
+
48
+ cache_key_adapter = f"{cache_key}-{adapter_name}"
49
+ output = self._cache_get(cache_key_adapter, None)
50
+ if output is not None:
51
+ return output
52
+
53
+ output = func(self, *args, **kwargs)
54
+ self._cache_store(cache_key_adapter, output)
55
+ return output
56
+
57
+ return wrapper
58
+
59
+ return cache_value
60
+
61
+
62
+ class DoraLinearLayer(nn.Module):
63
+ def __init__(self, fan_in_fan_out):
64
+ super().__init__()
65
+ self.fan_in_fan_out = fan_in_fan_out
66
+ self._dora_cache: dict[str, Any] = {} # small ad hoc cache; values are not part of the state_dict
67
+
68
+ def _cache_store(self, key: str, value: Any) -> None:
69
+ # cache intermediate values, e.g. weight norm of DoRA
70
+ self._dora_cache[key] = value
71
+
72
+ def _cache_get(self, key: str, default: Optional[Any]) -> Optional[Any]:
73
+ # retrieve from ad hoc cache
74
+ return self._dora_cache.get(key, default)
75
+
76
+ def _cache_clear(self) -> None:
77
+ self._dora_cache.clear()
78
+
79
+ def train(self, mode: bool = True):
80
+ if mode:
81
+ self._cache_clear()
82
+ super().train(mode=mode)
83
+ return self
84
+
85
+ @cache_decorator("weight-norm")
86
+ def get_weight_norm(self, weight, lora_weight, scaling, adapter_name: Optional[str] = None) -> torch.Tensor:
87
+ # calculate L2 norm of weight matrix, column-wise
88
+ weight = transpose(weight, self.fan_in_fan_out)
89
+ weight = weight + scaling * lora_weight
90
+ weight_norm = torch.linalg.norm(weight, dim=1).to(weight.dtype)
91
+ return weight_norm
92
+
93
+ @cache_decorator("lora-weight")
94
+ def get_lora_weight(self, lora_A, lora_B, adapter_name: Optional[str] = None):
95
+ # Don't use `lora_weight = lora_B.weight @ lora_A.weight` because this causes errors with FSDP. Instead,
96
+ # calculate the same but using forward.
97
+ x_eye = torch.eye(lora_A.weight.shape[1], device=lora_A.weight.device, dtype=lora_A.weight.dtype)
98
+ lora_weight = lora_B(lora_A(x_eye)).T
99
+ return lora_weight
100
+
101
+ def update_layer(self, *, base_layer, lora_A, lora_B, scaling, place_on_cpu=False) -> None:
102
+ # temporarily convert fp16 to fp32, as fp16 can cause trouble on CPU with PyTorch < 2.2
103
+ dtype_is_fp16 = lora_A.dtype == torch.float16
104
+ if dtype_is_fp16:
105
+ lora_A = lora_A.float()
106
+ lora_B = lora_B.float()
107
+
108
+ with gather_params_ctx(base_layer.parameters()):
109
+ if base_layer.__class__.__name__ == "Linear4bit":
110
+ # We have to create a copy of the base layer, otherwise, FSDP will throw an error. 8bit does not work
111
+ # yet because Int8Params cannot be correctly deep-copied (attributes vanish)
112
+ base_layer = deepcopy(base_layer)
113
+
114
+ weight = dequantize_module_weight(base_layer)
115
+ if weight.data.ndim >= 3: # For handling LoRAs applied to Conv layers.
116
+ r = lora_A.shape[0]
117
+ lora_weight = torch.mm(lora_B.view([-1, r]), lora_A.view([r, -1]))
118
+ lora_weight = lora_weight.reshape(weight.shape)
119
+ else:
120
+ lora_weight = lora_B @ lora_A
121
+
122
+ if dtype_is_fp16:
123
+ lora_weight = lora_weight.half()
124
+ weight_norm = self.get_weight_norm(
125
+ weight=weight.to(lora_A.device), lora_weight=lora_weight, scaling=scaling
126
+ )
127
+
128
+ if place_on_cpu:
129
+ weight_norm = weight_norm.to("cpu")
130
+ self.weight = nn.Parameter(weight_norm, requires_grad=True)
131
+
132
+ def forward(self, x, *, lora_A, lora_B, scaling, base_layer, base_result=None, adapter_name="default"):
133
+ """
134
+ For DoRA, calculate the extra output from LoRA with DoRA applied. This should be added on top of the base layer
135
+ output.
136
+ """
137
+ lora_weight = self.get_lora_weight(lora_A=lora_A, lora_B=lora_B, adapter_name=adapter_name)
138
+ lora_weight = lora_weight.to(x.dtype)
139
+
140
+ magnitude = self.weight
141
+ weight = dequantize_module_weight(base_layer)
142
+ weight = weight.to(x.dtype)
143
+ weight_norm = self.get_weight_norm(
144
+ weight=weight, lora_weight=lora_weight.detach(), scaling=scaling, adapter_name=adapter_name
145
+ )
146
+ # see section 4.3 of DoRA (https://huggingface.co/papers/2402.09353)
147
+ # "[...] we suggest treating ||V +∆V ||_c in
148
+ # Eq. (5) as a constant, thereby detaching it from the gradient
149
+ # graph. This means that while ||V + ∆V ||_c dynamically
150
+ # reflects the updates of ∆V , it won’t receive any gradient
151
+ # during backpropagation"
152
+ weight_norm = weight_norm.detach()
153
+ mag_norm_scale = (magnitude / weight_norm).view(1, -1)
154
+
155
+ lora_result = lora_B(lora_A(x))
156
+
157
+ bias = None
158
+ if base_result is not None:
159
+ bias = base_layer.bias
160
+ if bias is not None:
161
+ base_result = base_result - bias
162
+ else:
163
+ base_result = F.linear(x, transpose(weight, self.fan_in_fan_out))
164
+
165
+ result_dora = (mag_norm_scale - 1) * base_result + mag_norm_scale * lora_result * scaling
166
+ return result_dora
167
+
168
+ def __repr__(self) -> str:
169
+ rep = super().__repr__()
170
+ return "lora.dora." + rep
171
+
172
+
173
+ class DoraEmbeddingLayer(DoraLinearLayer):
174
+ @cache_decorator("lora-weight")
175
+ def get_lora_weight(self, lora_A, lora_B, adapter_name: Optional[str] = None):
176
+ return (lora_A @ lora_B).T
177
+
178
+ def forward(self, x, *, lora_A, lora_B, scaling, base_layer, embed_fn, adapter_name="default"):
179
+ """
180
+ For DoRA, calculate the extra output from LoRA with DoRA applied. This should be added on top of the base layer
181
+ output.
182
+ """
183
+ lora_weight = self.get_lora_weight(lora_A=lora_A, lora_B=lora_B, adapter_name=adapter_name)
184
+ magnitude = self.weight
185
+ weight = base_layer.weight
186
+ weight_norm = self.get_weight_norm(
187
+ weight=weight, lora_weight=lora_weight.detach(), scaling=scaling, adapter_name=adapter_name
188
+ )
189
+ # see section 4.3 of DoRA (https://huggingface.co/papers/2402.09353)
190
+ # "[...] we suggest treating ||V +∆V ||_c in
191
+ # Eq. (5) as a constant, thereby detaching it from the gradient
192
+ # graph. This means that while ||V + ∆V ||_c dynamically
193
+ # reflects the updates of ∆V , it won’t receive any gradient
194
+ # during backpropagation"
195
+ weight_norm = weight_norm.detach()
196
+ mag_norm_scale = magnitude / weight_norm
197
+ result_dora = mag_norm_scale * (embed_fn(x, lora_A) @ lora_B) * scaling
198
+ return mag_norm_scale, result_dora
199
+
200
+ def __repr__(self) -> str:
201
+ rep = super().__repr__()
202
+ return "lora.dora." + rep
203
+
204
+
205
+ class _DoraConvNdLayer(DoraLinearLayer):
206
+ @cache_decorator("weight-norm")
207
+ def get_weight_norm(self, weight, lora_weight, scaling, adapter_name: Optional[str] = None) -> torch.Tensor:
208
+ # calculate L2 norm of weight matrix, column-wise
209
+ weight = weight + scaling * lora_weight
210
+ # the following is needed to have compatibility with the 4/5D weight tensors of Conv2D/3D
211
+ dim = tuple(range(1, weight.dim()))
212
+ weight_norm = weight.norm(p=2, dim=dim, keepdim=True).transpose(1, 0)
213
+ return weight_norm
214
+
215
+ @cache_decorator("lora-weight")
216
+ def get_lora_weight(self, lora_A, lora_B, adapter_name: Optional[str] = None) -> torch.Tensor:
217
+ # Don't use `lora_weight = lora_B.weight @ lora_A.weight` because this causes errors with FSDP. Instead,
218
+ # calculate the same but using forward.
219
+ r = lora_A.weight.shape[0]
220
+ lora_weight = torch.mm(lora_B.weight.view([-1, r]), lora_A.weight.view([r, -1]))
221
+ return lora_weight
222
+
223
+ def forward(
224
+ self, x, *, lora_A, lora_B, scaling, base_layer, base_result=None, adapter_name: str = "default"
225
+ ) -> torch.Tensor:
226
+ """
227
+ For DoRA, calculate the extra output from LoRA with DoRA applied. This should be added on top of the base layer
228
+ output.
229
+ """
230
+ weight = base_layer.weight
231
+ lora_weight = self.get_lora_weight(lora_A=lora_A, lora_B=lora_B, adapter_name=adapter_name).reshape(
232
+ weight.shape
233
+ )
234
+ magnitude = self.weight
235
+ weight_norm = self.get_weight_norm(
236
+ weight=weight, lora_weight=lora_weight.detach(), scaling=scaling, adapter_name=adapter_name
237
+ )
238
+ # see section 4.3 of DoRA (https://huggingface.co/papers/2402.09353)
239
+ # "[...] we suggest treating ||V +∆V ||_c in
240
+ # Eq. (5) as a constant, thereby detaching it from the gradient
241
+ # graph. This means that while ||V + ∆V ||_c dynamically
242
+ # reflects the updates of ∆V , it won’t receive any gradient
243
+ # during backpropagation"
244
+ weight_norm = weight_norm.detach()
245
+ mag_norm_scale = magnitude / weight_norm
246
+
247
+ if base_result is None:
248
+ base_result = self.conv_fn(
249
+ x,
250
+ weight,
251
+ bias=None,
252
+ stride=base_layer.stride,
253
+ padding=base_layer.padding,
254
+ dilation=base_layer.dilation,
255
+ groups=base_layer.groups,
256
+ )
257
+ else:
258
+ bias = base_layer.bias
259
+ if bias is not None:
260
+ # reshape bias to (1, -1, 1, ...)
261
+ bias_shape = (1, -1) + (1,) * (base_result.dim() - 2)
262
+ base_result = base_result - bias.view(*bias_shape)
263
+
264
+ result_dora = (mag_norm_scale - 1) * base_result + mag_norm_scale * lora_B(lora_A(x)) * scaling
265
+ return result_dora
266
+
267
+ def __repr__(self) -> str:
268
+ rep = super().__repr__()
269
+ return "lora.dora." + rep
270
+
271
+
272
+ class DoraConv1dLayer(_DoraConvNdLayer):
273
+ def __init__(self, fan_in_fan_out):
274
+ super().__init__(fan_in_fan_out)
275
+ self.conv_fn = F.conv1d
276
+
277
+
278
+ class DoraConv2dLayer(_DoraConvNdLayer):
279
+ def __init__(self, fan_in_fan_out):
280
+ super().__init__(fan_in_fan_out)
281
+ self.conv_fn = F.conv2d
282
+
283
+
284
+ class DoraConv3dLayer(_DoraConvNdLayer):
285
+ def __init__(self, fan_in_fan_out):
286
+ super().__init__(fan_in_fan_out)
287
+ self.conv_fn = F.conv3d
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/eva.py ADDED
@@ -0,0 +1,734 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import warnings
16
+ from collections import Counter, defaultdict
17
+ from collections.abc import Callable, Iterable, Mapping
18
+ from contextlib import nullcontext
19
+ from copy import copy, deepcopy
20
+ from functools import partial
21
+ from itertools import cycle
22
+ from typing import Optional, Union
23
+
24
+ import torch
25
+ import torch.distributed as dist
26
+ from tqdm import tqdm
27
+ from transformers.pytorch_utils import Conv1D
28
+
29
+ from peft.tuners.tuners_utils import _find_minimal_target_modules, check_target_module_exists
30
+ from peft.utils.constants import MIN_TARGET_MODULES_FOR_OPTIMIZATION
31
+ from peft.utils.incremental_pca import IncrementalPCA
32
+ from peft.utils.other import _get_submodules, get_pattern_key
33
+
34
+ from .config import LoraConfig
35
+ from .layer import Embedding, LoraLayer, MultiheadAttention, _ConvNd
36
+
37
+
38
+ UNSUPPORTED_LORA_MODULES = (Embedding, MultiheadAttention, _ConvNd)
39
+
40
+
41
+ class _Hook:
42
+ """
43
+ A base class for hooks that prepares layer inputs for EVA.
44
+ """
45
+
46
+ def __init__(
47
+ self,
48
+ name: str,
49
+ prepare_layer_inputs_fn: Optional[Callable] = None,
50
+ gather_distributed_inputs: bool = True,
51
+ ):
52
+ self.name = name
53
+ self.gather_distributed_inputs = gather_distributed_inputs
54
+ if prepare_layer_inputs_fn is None:
55
+ self._prepare_layer_inputs_fn = self._prepare_layer_inputs_fn_default
56
+ else:
57
+ self._prepare_layer_inputs_fn = prepare_layer_inputs_fn
58
+ self.model_input = None
59
+
60
+ @staticmethod
61
+ def _prepare_layer_inputs_fn_default(layer_input, model_input, layer_name) -> torch.Tensor:
62
+ if isinstance(layer_input, torch.Tensor):
63
+ pass
64
+ elif isinstance(layer_input, (tuple, list)):
65
+ layer_input = layer_input[0]
66
+ else:
67
+ raise ValueError(
68
+ f"unsupported input type {type(layer_input)} for prepare_layer_inputs_fn in layer {layer_name}, "
69
+ "please provide a custom prepare_layer_inputs_fn"
70
+ )
71
+ # if the input has more than 2 dimensions, we flatten all but the last dimension
72
+ if layer_input.ndim > 2:
73
+ layer_input = layer_input.view(-1, layer_input.size(-1))
74
+ return layer_input
75
+
76
+ @torch.no_grad()
77
+ def prepare_layer_inputs(self, layer_input):
78
+ return self._prepare_layer_inputs_fn(layer_input, self.model_input, self.name)
79
+
80
+ def gather_layer_inputs(self, layer_input):
81
+ if dist.is_initialized() and self.gather_distributed_inputs:
82
+ world_size = dist.get_world_size()
83
+
84
+ # First gather sizes from all processes more efficiently
85
+ local_size = torch.tensor([layer_input.shape[0]], device=layer_input.device)
86
+ all_sizes = torch.empty(world_size, dtype=local_size.dtype, device=layer_input.device)
87
+ dist.all_gather_into_tensor(all_sizes, local_size)
88
+ all_sizes = all_sizes.tolist()
89
+
90
+ # Find maximum size and pad tensors
91
+ padded_input = layer_input.new_zeros((max(all_sizes), *layer_input.shape[1:]))
92
+ padded_input[: layer_input.shape[0]] = layer_input
93
+
94
+ # Gather padded tensors
95
+ gathered_inputs = [torch.zeros_like(padded_input) for _ in range(world_size)]
96
+ dist.all_gather(gathered_inputs, padded_input.contiguous())
97
+
98
+ # Remove padding for each gathered tensor
99
+ gathered_inputs = [tensor[:size] for tensor, size in zip(gathered_inputs, all_sizes)]
100
+
101
+ # Concatenate along batch dimension
102
+ return torch.cat(gathered_inputs, dim=0)
103
+ return layer_input
104
+
105
+
106
+ class SVDHook(_Hook):
107
+ """
108
+ A forward hook for calculating incremental SVD on layer inputs. The hook is designed to be registered to a PyTorch
109
+ module using the `register_forward_hook` method.
110
+
111
+ This hook performs a step of incremental Singular Value Decomposition (SVD) on the inputs of a specified layer
112
+ during the forward pass of a neural network. The hook also tracks convergence of the computed components using
113
+ cosine similarity between the current and previous components.
114
+
115
+ Args:
116
+ name (str): Name of the layer to which this hook is attached.
117
+ n_components (int): Number of principal components to compute.
118
+ sim_thresh (Union[float, torch.Tensor]): Similarity threshold for convergence.
119
+ prepare_layer_inputs_fn (Optional[Callable]): Function to prepare layer inputs for SVD.
120
+ """
121
+
122
+ def __init__(
123
+ self,
124
+ n_components: int,
125
+ sim_thresh: Union[float, torch.Tensor],
126
+ **base_class_kwargs,
127
+ ):
128
+ super().__init__(**base_class_kwargs)
129
+ self.n_components = n_components
130
+ self.sim_thresh = sim_thresh
131
+ if isinstance(sim_thresh, torch.Tensor) and len(sim_thresh.shape) > 0:
132
+ check1 = sim_thresh.size(0) == n_components or sim_thresh.size(0) == 1
133
+ check2 = len(sim_thresh.shape) == 1
134
+ if not (check1 and check2):
135
+ raise ValueError(
136
+ "if sim_thresh is a tensor with more than 0 dimensions it must have shape (n_components,) or (1,)"
137
+ )
138
+ self.svd = IncrementalPCA(
139
+ n_components=n_components,
140
+ copy=True,
141
+ lowrank=True,
142
+ lowrank_seed=42,
143
+ )
144
+ self.model_input = None
145
+ self.converged = torch.zeros((n_components,), dtype=torch.bool)
146
+
147
+ @torch.no_grad()
148
+ def __call__(self, model, input, output):
149
+ previous_components = None
150
+ if hasattr(self.svd, "components_"):
151
+ previous_components = self.svd.components_.clone().detach()
152
+ states = self.prepare_layer_inputs(input)
153
+ states = self.gather_layer_inputs(states)
154
+ # check if batch sizes is more than the number of components
155
+ if states.size(0) < self.n_components:
156
+ print(f"skipping SVD for {self.name} because there are less than {self.n_components} examples")
157
+ return
158
+ self.svd.partial_fit(states.to(torch.float32))
159
+ # add if statement to check if we are in the first step where previous_components is None
160
+ if previous_components is None:
161
+ return
162
+ components = self.svd.components_
163
+ if len(components.shape) == 1:
164
+ components = components.reshape(1, -1)
165
+ previous_components = previous_components.reshape(1, -1)
166
+ # consider as converged if enough components have converged via cossim
167
+ sim = torch.nn.functional.cosine_similarity(components, previous_components)
168
+ self.converged = sim >= self.sim_thresh
169
+
170
+
171
+ # This is used to determine if inputs of two different layers are equal. For such cases, SVD
172
+ # needs to be done for only for one of the equal inputs.
173
+ class HashHook(_Hook):
174
+ """
175
+ A forward hook for hashing layer inputs. The hook is designed to be registered to a PyTorch module using the
176
+ `register_forward_hook` method.
177
+
178
+ This hook hashes the inputs of a specified layer during the forward pass of a neural network and stores the hash
179
+ values for later analysis or comparison.
180
+
181
+ Args:
182
+ name (str): Name of the layer to which this hook is attached. hashed_inputs (list): List of hashed inputs.
183
+ prepare_layer_inputs_fn (Optional[Callable]): Function to prepare layer inputs for hashing.
184
+ """
185
+
186
+ def __init__(self, **base_class_kwargs):
187
+ super().__init__(**base_class_kwargs)
188
+ self.hashed_inputs = []
189
+
190
+ @staticmethod
191
+ def hash_fn(tensor):
192
+ return hash(tuple(tensor.view(-1).tolist()))
193
+
194
+ @torch.no_grad()
195
+ def __call__(self, model, input, output):
196
+ x = self.prepare_layer_inputs(input)
197
+ x = self.gather_layer_inputs(x)
198
+ self.hashed_inputs.append(self.hash_fn(x.cpu()))
199
+
200
+
201
+ def find_equal_values(dictionary: dict) -> dict:
202
+ """
203
+ Find keys in a dictionary that have the same value.
204
+
205
+ This function takes a dictionary and returns a new dictionary containing keys that have the same value. The keys in
206
+ the output dictionary are the values from the input dictionary, and the values are lists of keys that share the
207
+ same value.
208
+ """
209
+ value_dict = defaultdict(list)
210
+ for k, v in dictionary.items():
211
+ value_dict[v].append(k)
212
+ return {k: v for k, v in value_dict.items() if len(v) > 1}
213
+
214
+
215
+ def get_device_with_meta_params(model: torch.nn.Module) -> torch.device:
216
+ """
217
+ Get the device of the model's parameters. Useful if some parameters are on meta device.
218
+ """
219
+ devices = list({p.device for p in model.parameters() if p.device.type != "meta"})
220
+ if len(devices) > 1:
221
+ warnings.warn(f"Could not determine device, model has multiple devices: {devices}")
222
+ return
223
+ return devices[0]
224
+
225
+
226
+ def move_inputs_to_device(inputs, device: Union[str, torch.device]):
227
+ """
228
+ Move the inputs to the specified device. Adapted from hf.Trainer.
229
+ """
230
+ if hasattr(inputs, "to"):
231
+ return inputs.to(device)
232
+ if isinstance(inputs, Mapping):
233
+ return type(inputs)({k: move_inputs_to_device(v, device) for k, v in inputs.items()})
234
+ elif isinstance(inputs, (tuple, list)):
235
+ return type(inputs)(move_inputs_to_device(v, device) for v in inputs)
236
+ else:
237
+ warnings.warn(f"input of type {type(inputs)} could not be moved to the correct device")
238
+ return inputs
239
+
240
+
241
+ def prepare_model_inputs_fn_language_modeling(model_input, peft_config: LoraConfig):
242
+ """
243
+ Get the indices of the items that should be used for SVD.
244
+
245
+ Attributes:
246
+ model_input (dict): The model inputs.
247
+ peft_config (LoraConfig): The configuration for the LoRA layers.
248
+ """
249
+ if not isinstance(model_input, dict):
250
+ raise ValueError("When using `prepare_model_inputs_fn_language_modeling` inputs must be a dictionary")
251
+ mask = model_input.get("attention_mask", torch.ones_like(model_input["input_ids"])).bool()
252
+ if peft_config.eva_config.use_label_mask and hasattr(model_input, "labels"):
253
+ mask = torch.logical_and(mask, model_input["labels"] != peft_config.eva_config.label_mask_value)
254
+ return mask.nonzero()
255
+
256
+
257
+ def prepare_layer_inputs_fn_language_modeling(layer_input, model_input, layer_name) -> torch.Tensor:
258
+ """
259
+ if not all items in the input should be used for SVD, this function can be used to get the indices of the items
260
+ that should be used.
261
+
262
+ Attributes:
263
+ layer_input (torch.Tensor): The layer inputs.
264
+ model_input (torch.Tensor):
265
+ The model inputs or if `prepare_model_inputs_fn` is not None the output of this function.
266
+ layer_name (str): The name of the layer.
267
+
268
+ Returns:
269
+ torch.Tensor: The input to the SVD.
270
+ """
271
+ # if layer inputs are not a tensor, we simply get the first item
272
+ if isinstance(layer_input, torch.Tensor):
273
+ pass
274
+ elif isinstance(layer_input, (tuple, list)):
275
+ layer_input = layer_input[0]
276
+ else:
277
+ raise ValueError(
278
+ f"unsupported input type {type(layer_input)} for prepare_layer_inputs_fn in layer {layer_name}, "
279
+ "please provide a custom prepare_layer_inputs_fn"
280
+ )
281
+ # in this case model_input is the output of `prepare_model_inputs_fn_language_modeling`
282
+ return layer_input[model_input.T.unbind()]
283
+
284
+
285
+ def forward_fn_dict(model, inputs):
286
+ return model(**inputs)
287
+
288
+
289
+ def _get_eva_state_dict(
290
+ model: torch.nn.Module,
291
+ dataloader: Iterable,
292
+ peft_config: Optional[LoraConfig],
293
+ target_module_check_fn: Callable,
294
+ forward_fn: Optional[Callable],
295
+ prepare_model_inputs_fn: Optional[Callable],
296
+ prepare_layer_inputs_fn: Union[Callable, dict[str, Callable], None],
297
+ gather_distributed_inputs: bool,
298
+ show_progress_bar: bool,
299
+ ) -> dict:
300
+ # Computes the rank distribution for each layer based on the explained variance ratio.
301
+ # when rank_pattern flag is False, all values in max_components are the same
302
+ def _get_rank_distribution(hooks, layer_hook_map, equal_inputs_map, rank_budget, max_components):
303
+ exp_vars = {k: h[0].svd.explained_variance_ratio_[: max_components[k]] for k, h in hooks.items()}
304
+ keys, values = zip(*[(k, c) for k, name in layer_hook_map.items() for c in exp_vars[name]])
305
+ idx = torch.stack(values).argsort(descending=True)
306
+ counts = Counter([keys[i] for i in idx[:rank_budget]])
307
+ counts = {k: counts.get(k, 0) for k in layer_hook_map.keys()} # add layers with 0 rank
308
+ for k, k_hook in equal_inputs_map.items():
309
+ # ensure hook layers have the highest rank if they are equal to another layer
310
+ rank, rank_hook = counts[k], counts[k_hook]
311
+ if rank_hook >= rank:
312
+ continue
313
+ counts[k_hook], counts[k] = rank, rank_hook
314
+ return counts
315
+
316
+ # dataloader is not empty
317
+ if len(dataloader) == 0:
318
+ raise ValueError("dataloader is empty")
319
+
320
+ # check if dist is initialized
321
+ if dist.is_initialized() and gather_distributed_inputs:
322
+ warnings.warn(
323
+ "torch.distributed is initialized and `gather_distributed_inputs` is True, "
324
+ "therefore EVA initialization will gather tensors from all ranks. "
325
+ "Ensure the model does not receive the same inputs on different ranks."
326
+ )
327
+
328
+ # for unusually high rho values, define an upper limit
329
+ rho_threshold = 1000
330
+ rho = peft_config.eva_config.rho
331
+ if rho > rho_threshold:
332
+ max_dim = max(max(p.shape) for p in model.parameters())
333
+ rho_ceil = max_dim // peft_config.r
334
+ rho = min(rho, rho_ceil)
335
+
336
+ training = model.training
337
+ device = get_device_with_meta_params(model)
338
+ model.eval()
339
+
340
+ # get model inputs
341
+ inputs = next(iter(dataloader))
342
+ if device is not None:
343
+ inputs = move_inputs_to_device(inputs, device)
344
+ if prepare_model_inputs_fn is not None:
345
+ model_inputs_for_hooks = prepare_model_inputs_fn(inputs, peft_config)
346
+ else:
347
+ model_inputs_for_hooks = deepcopy(inputs)
348
+
349
+ hooks = {}
350
+ max_components = {}
351
+ rank_budget = 0
352
+ for name, module in model.named_modules():
353
+ if not target_module_check_fn(name, module):
354
+ continue
355
+ if isinstance(prepare_layer_inputs_fn, Mapping):
356
+ fn = prepare_layer_inputs_fn.pop(name, None)
357
+ else:
358
+ fn = prepare_layer_inputs_fn
359
+ hook = HashHook(name=name, prepare_layer_inputs_fn=fn, gather_distributed_inputs=gather_distributed_inputs)
360
+ hook.model_input = model_inputs_for_hooks
361
+ handle = module.register_forward_hook(hook)
362
+ hooks[name] = (hook, handle)
363
+ layer_rank = peft_config.rank_pattern.get(
364
+ get_pattern_key(peft_config.rank_pattern.keys(), name), peft_config.r
365
+ )
366
+ max_components[name] = round(layer_rank * rho)
367
+ rank_budget += layer_rank
368
+ if isinstance(prepare_layer_inputs_fn, Mapping) and len(prepare_layer_inputs_fn) > 0:
369
+ raise ValueError(
370
+ "prepare_layer_inputs_fn is a mapping but the following module names were not found in the model: "
371
+ f"{prepare_layer_inputs_fn.keys()}"
372
+ )
373
+
374
+ # forward for one batch to check which layer inputs are equal to avoid unneeded svd calculations
375
+ forward_fn(model, inputs)
376
+ hash_dict = {k: h[0].hashed_inputs[0] for k, h in hooks.items()}
377
+ # equal input maps groups layers which receive the same input. One layer is defined as the key and receives an svd
378
+ # hook. For the remaining layers the svd results can be skipped.
379
+ equal_inputs = list(find_equal_values(hash_dict).values())
380
+ equal_inputs_map = {vv: v[0] for v in equal_inputs for vv in v[1:]}
381
+ # for layers with equal inputs we need to make sure that the max_components are the same
382
+ for names in equal_inputs:
383
+ max_value = max(max_components[n] for n in names)
384
+ for n in names:
385
+ max_components[n] = max_value
386
+
387
+ # initialize svd hooks
388
+ for name in list(hooks.keys()):
389
+ hook, handle = hooks.pop(name)
390
+ handle.remove()
391
+ if name in equal_inputs_map:
392
+ continue
393
+ hook = SVDHook(
394
+ n_components=max_components[name],
395
+ sim_thresh=peft_config.eva_config.tau,
396
+ name=name,
397
+ prepare_layer_inputs_fn=hook._prepare_layer_inputs_fn,
398
+ gather_distributed_inputs=gather_distributed_inputs,
399
+ )
400
+ module = model.get_submodule(name)
401
+ handle = module.register_forward_hook(hook)
402
+ hooks[name] = (hook, handle) # adding the old handle here so we dont get errors in the first forward pass
403
+ layer_hook_map = {**dict(zip(hooks.keys(), hooks.keys())), **equal_inputs_map}
404
+
405
+ # start svd calculation
406
+ if show_progress_bar and (not dist.is_initialized() or dist.get_rank() == 0):
407
+ pbar = tqdm(iter(cycle(dataloader)), position=0, leave=False)
408
+ use_tqdm = True
409
+ else:
410
+ pbar = iter(cycle(dataloader))
411
+ use_tqdm = False
412
+ convergence_dict = {k: False for k in hooks.keys()}
413
+ rank_dist = max_components.copy()
414
+ for inputs in pbar:
415
+ if device is not None:
416
+ inputs = move_inputs_to_device(inputs, device)
417
+ if prepare_model_inputs_fn is not None:
418
+ model_inputs_for_hooks = prepare_model_inputs_fn(inputs, peft_config)
419
+ else:
420
+ model_inputs_for_hooks = deepcopy(inputs)
421
+
422
+ for name in list(hooks.keys()):
423
+ hook, handle = hooks[name]
424
+ # check if all components that are needed for the rank distribution have converged
425
+ converged = torch.all(hook.converged[: rank_dist[name]])
426
+ # if a layer has switched from not converged to converged in the current step
427
+ if (not convergence_dict[name]) and converged and handle:
428
+ handle.remove()
429
+ handle = None
430
+ convergence_dict[name] = True
431
+ continue
432
+ # if a layer has switched from converged to not converged in the current step
433
+ elif convergence_dict[name] and not converged:
434
+ module = model.get_submodule(name)
435
+ handle = module.register_forward_hook(hook)
436
+ convergence_dict[name] = False
437
+ hook.model_input = model_inputs_for_hooks
438
+ hooks[name] = (hook, handle)
439
+
440
+ if use_tqdm:
441
+ layer_converged = list(convergence_dict.values()) + [
442
+ convergence_dict[v] for v in equal_inputs_map.values()
443
+ ]
444
+ pbar.set_description(f"{sum(layer_converged)}/{len(layer_converged)} layers have converged")
445
+
446
+ if all(convergence_dict.values()):
447
+ break
448
+
449
+ forward_fn(model, inputs)
450
+
451
+ # in case some hooks have to skip the svd calculation because the number of tokens is less than the number of
452
+ # components
453
+ if not all(hasattr(h[0].svd, "components_") for h in hooks.values()):
454
+ continue
455
+
456
+ rank_dist = _get_rank_distribution(hooks, layer_hook_map, equal_inputs_map, rank_budget, max_components)
457
+
458
+ # check all custom hooks have been removed
459
+ remaining_hooks = {n for n, m in model.named_modules() for v in m._forward_hooks.values() if isinstance(v, _Hook)}
460
+ if len(remaining_hooks) > 0:
461
+ raise ValueError(
462
+ f"Found active hooks added by EVA that weren't properly removed: {remaining_hooks}. "
463
+ "Please report this issue at https://github.com/huggingface/peft/issues"
464
+ )
465
+
466
+ eva_state_dict = {}
467
+ for name, rank in rank_dist.items():
468
+ hook = hooks[layer_hook_map[name]][0]
469
+ if not torch.all(hook.converged[:rank]):
470
+ raise ValueError(
471
+ f"Layer {name} has not converged but was assigned rank {rank}. "
472
+ "Please report this issue at https://github.com/huggingface/peft/issues"
473
+ )
474
+ u = hook.svd.components_[:rank]
475
+ if peft_config.eva_config.whiten:
476
+ u /= hook.svd.singular_values_[:rank].sqrt().reshape(-1, 1)
477
+ eva_state_dict[name] = u
478
+
479
+ # restore model state
480
+ model.train(training)
481
+
482
+ # move tensors to device
483
+ if device is not None:
484
+ eva_state_dict = {k: v.to(device) for k, v in eva_state_dict.items()}
485
+
486
+ return eva_state_dict
487
+
488
+
489
+ def _load_eva_state_dict(
490
+ model: torch.nn.Module,
491
+ eva_state_dict: dict,
492
+ adapter_name: str,
493
+ ):
494
+ peft_config = copy(model.peft_config[adapter_name])
495
+ missing_eva_inits = []
496
+ new_target_modules = []
497
+ other_module_names = []
498
+ rank_pattern = {}
499
+ alpha_pattern = {}
500
+ for name, module in model.named_modules():
501
+ name_in_base_model = name.replace("base_model.model.", "")
502
+ if not isinstance(module, LoraLayer):
503
+ other_module_names.append(name_in_base_model)
504
+ continue
505
+ # Regexp matching - Find key which matches current target_name in patterns provided
506
+ r = peft_config.rank_pattern.get(get_pattern_key(peft_config.rank_pattern.keys(), name), peft_config.r)
507
+ alpha = peft_config.alpha_pattern.get(
508
+ get_pattern_key(peft_config.alpha_pattern.keys(), name), peft_config.lora_alpha
509
+ )
510
+ if name in eva_state_dict:
511
+ w = eva_state_dict.pop(name)
512
+ new_rank = w.size(0)
513
+ if new_rank == 0:
514
+ parent, _, target_name = _get_submodules(model, name)
515
+ setattr(parent, target_name, module.get_base_layer())
516
+ continue
517
+ elif new_rank != r:
518
+ if peft_config.eva_config.adjust_scaling_factors:
519
+ alpha *= new_rank / r
520
+ if new_rank != r or module.lora_A[adapter_name].weight.device.type == "meta":
521
+ peft_config.init_lora_weights = "eva"
522
+ module.update_layer(adapter_name=adapter_name, r=new_rank, lora_alpha=alpha, config=peft_config)
523
+ module.lora_A[adapter_name].weight.copy_(w)
524
+ new_target_modules.append(name_in_base_model)
525
+ else:
526
+ peft_config.init_lora_weights = True
527
+ module.update_layer(adapter_name=adapter_name, r=r, lora_alpha=alpha, config=peft_config)
528
+ missing_eva_inits.append(name_in_base_model)
529
+ new_rank = r
530
+ # update rank pattern and alpha pattern
531
+ if new_rank != peft_config.r:
532
+ rank_pattern[name_in_base_model] = new_rank
533
+ if alpha != peft_config.lora_alpha:
534
+ alpha_pattern[name_in_base_model] = alpha
535
+
536
+ # update target modules if some lora layers have been removed due to their EVA rank being 0
537
+ new_target_modules = new_target_modules + missing_eva_inits
538
+ if len(new_target_modules) >= MIN_TARGET_MODULES_FOR_OPTIMIZATION:
539
+ new_target_modules = _find_minimal_target_modules(new_target_modules, other_module_names)
540
+ model.peft_config[adapter_name].target_modules = new_target_modules
541
+
542
+ # set rank pattern obtained from EVA
543
+ model.peft_config[adapter_name].rank_pattern = rank_pattern
544
+
545
+ # when adjust_scaling_factors is True, lora scaling factors have been adjusted after the rank redistribution
546
+ model.peft_config[adapter_name].alpha_pattern = alpha_pattern
547
+
548
+ if missing_eva_inits:
549
+ warnings.warn(
550
+ "the following layers were initialized with init_lora_weights=True because they "
551
+ f"were not found in the eva state_dict: {missing_eva_inits}\ncurrently the "
552
+ f"following lora modules are not supported by EVA: {UNSUPPORTED_LORA_MODULES}"
553
+ )
554
+
555
+
556
+ @torch.no_grad()
557
+ def get_eva_state_dict(
558
+ model: torch.nn.Module,
559
+ dataloader: Iterable,
560
+ peft_config: Optional[LoraConfig] = None,
561
+ forward_fn: Optional[Callable] = forward_fn_dict,
562
+ prepare_model_inputs_fn: Optional[Callable] = prepare_model_inputs_fn_language_modeling,
563
+ prepare_layer_inputs_fn: Union[Callable, dict[str, Callable], None] = prepare_layer_inputs_fn_language_modeling,
564
+ adapter_name: str = "default",
565
+ gather_distributed_inputs: bool = True,
566
+ show_progress_bar: bool = True,
567
+ ) -> dict:
568
+ """
569
+ Compute the SVD for each layer in the model.
570
+
571
+ This function computes the Singular Value Decomposition (SVD) for each layer in the model. It uses the incremental
572
+ PCA method to compute the SVD components. The function also checks for convergence of the computed components using
573
+ cosine similarity. The rank distribution for each layer is determined based on the explained variance ratio.
574
+
575
+ Args:
576
+ model (torch.nn.Module): The model to compute the SVD for. Does not need to be a PeftModel.
577
+ dataloader (Iterable): The dataloader to use for the forward pass.
578
+ peft_config (Optional[LoraConfig]):
579
+ The configuration for the LoRA layers. Only required if `model` is not a PeftModel.
580
+ forward_fn (Callable):
581
+ The forward function to use for the forward pass. Takes two arguments: `model` and `inputs`. Default
582
+ behavior is `return model(**inputs)`
583
+ prepare_model_inputs_fn (Optional[Callable]):
584
+ This function receives the model inputs and the peft_config and passes the output to
585
+ `prepare_layer_inputs_fn`. Can be used to modify the input to the SVD computation based on the original
586
+ model inputs. For example for language modeling the attention mask is used to determine which indices are
587
+ padding tokens and should not be used for SVD. Any function defined here expects two arguments:
588
+ `model_input` and `peft_config`. `peft.tuners.lora.eva.prepare_model_inputs_fn_language_modeling` is used
589
+ by default.
590
+ prepare_layer_inputs_fn (Union[Callable, Dict[str, Callable], None]):
591
+ This function receives the layer inputs, the model inputs (potentially modified by
592
+ `prepare_model_inputs_fn`) and the name of the layer and returns the inputs that should be used for SVD for
593
+ that particular layer. Any custom function defined here expects three arguments: `layer_input`,
594
+ `model_input`, and `layer_name` and should return a 2d tensor. The default logic can be found in
595
+ peft.tuners.lora.eva.prepare_layer_inputs_fn_language_modeling and works for language modeling. In this
596
+ case model_inputs is the mask used to determine which indices should be used for SVD (created by
597
+ `prepare_model_inputs_fn_language_modeling`).
598
+ adapter_name (str): The name of the adapter to compute the SVD for.
599
+ gather_distributed_inputs (bool):
600
+ Whether to gather the layer inputs from all ranks. Default is True meaning in a distributed setting the
601
+ layer inputs will be gathered from all ranks for the SVD computation. For non-distributed settings this
602
+ argument is ignored. Set to False if you are using a non-distributed dataloader in a distributed setting.
603
+ show_progress_bar (bool): Whether to show a progress bar. Default is True.
604
+
605
+ Returns:
606
+ eva_state_dict (dict): The state dictionary containing the SVD components for each layer.
607
+ """
608
+
609
+ def target_module_check_fn_peft_model(name, module, unsupported_lora_modules):
610
+ "check if a module is an adapter module via base_layer attribute"
611
+ return hasattr(module, "base_layer") and not isinstance(module, unsupported_lora_modules)
612
+
613
+ def target_module_check_fn_default(name, module, peft_config):
614
+ "check if a module is an adapter module via target_modules"
615
+ is_target_module = True
616
+ if peft_config.target_modules is not None:
617
+ is_target_module = check_target_module_exists(peft_config, name)
618
+ # Conv1D for GPT2 support
619
+ return isinstance(module, (torch.nn.Linear, Conv1D)) and is_target_module
620
+
621
+ is_peft_model = hasattr(model, "peft_config")
622
+
623
+ # get peft_config
624
+ if is_peft_model and peft_config is None:
625
+ peft_config = model.peft_config[adapter_name]
626
+ elif peft_config is None:
627
+ raise ValueError("peft_config is required if model is not a PeftModel")
628
+
629
+ # setup context and target module check function
630
+ if is_peft_model:
631
+ ctx = model.disable_adapter()
632
+ target_module_check_fn = partial(
633
+ target_module_check_fn_peft_model, unsupported_lora_modules=UNSUPPORTED_LORA_MODULES
634
+ )
635
+ else:
636
+ ctx = nullcontext()
637
+ target_module_check_fn = partial(target_module_check_fn_default, peft_config=peft_config)
638
+
639
+ with ctx:
640
+ eva_state_dict = _get_eva_state_dict(
641
+ model=model,
642
+ dataloader=dataloader,
643
+ peft_config=peft_config,
644
+ target_module_check_fn=target_module_check_fn,
645
+ forward_fn=forward_fn,
646
+ prepare_model_inputs_fn=prepare_model_inputs_fn,
647
+ prepare_layer_inputs_fn=prepare_layer_inputs_fn,
648
+ gather_distributed_inputs=gather_distributed_inputs,
649
+ show_progress_bar=show_progress_bar,
650
+ )
651
+ return eva_state_dict
652
+
653
+
654
+ @torch.no_grad()
655
+ def initialize_lora_eva_weights(
656
+ model: torch.nn.Module,
657
+ dataloader: Optional[Iterable] = None,
658
+ eva_state_dict: Optional[dict] = None,
659
+ forward_fn: Optional[Callable] = forward_fn_dict,
660
+ prepare_model_inputs_fn: Optional[Callable] = prepare_model_inputs_fn_language_modeling,
661
+ prepare_layer_inputs_fn: Union[Callable, dict[str, Callable], None] = prepare_layer_inputs_fn_language_modeling,
662
+ adapter_name: str = "default",
663
+ gather_distributed_inputs: bool = True,
664
+ show_progress_bar: bool = True,
665
+ ):
666
+ """
667
+ Initialize the weights of the LoRA layers using the EVA method.
668
+
669
+ This function initializes the weights of the LoRA layers using the EVA method. It computes the SVD for each adapter
670
+ layer and updates the weights accordingly.
671
+
672
+ Args:
673
+ model (PeftModel): The peft model to compute the SVD for.
674
+ dataloader (Optional[Iterable]):
675
+ The dataloader to use for the forward pass. If None, eva_state_dict needs to be provided.
676
+ eva_state_dict (Optional[dict]):
677
+ The state_dict to load into the model. If None, a dataloader needs to be provided and the state_dict will
678
+ be computed using `get_eva_state_dict`.
679
+ forward_fn (Callable):
680
+ The forward function to use for the forward pass. Takes two arguments: `model` and `inputs`. Default
681
+ behavior is `return model(**inputs)`
682
+ prepare_model_inputs_fn (Optional[Callable]):
683
+ This function receives the model inputs and the peft_config and passes the output to
684
+ `prepare_layer_inputs_fn`. Can be used to modify the input to the SVD computation based on the original
685
+ model inputs. For example for language modeling the attention mask is used to determine which indices are
686
+ padding tokens and should not be used for SVD. Any function defined here expects two arguments:
687
+ `model_input` and `peft_config`. `peft.tuners.lora.eva.prepare_model_inputs_fn_language_modeling` is used
688
+ by default.
689
+ prepare_layer_inputs_fn (Union[Callable, Dict[str, Callable], None]):
690
+ This function receives the layer inputs, the model inputs (potentially modified by
691
+ `prepare_model_inputs_fn`) and the name of the layer and returns the inputs that should be used for SVD for
692
+ that particular layer. Any custom function defined here expects three arguments: `layer_input`,
693
+ `model_input`, and `layer_name` and should return a 2d tensor. The default logic can be found in
694
+ peft.tuners.lora.eva.prepare_layer_inputs_fn_language_modeling and works for language modeling. In this
695
+ case model_inputs is the mask used to determine which indices should be used for SVD (created by
696
+ `prepare_model_inputs_fn_language_modeling`).
697
+ adapter_name (str): The name of the adapter to initialize the weights for.
698
+ gather_distributed_inputs (bool):
699
+ Whether to gather the layer inputs from all ranks. Default is True meaning in a distributed setting the
700
+ layer inputs will be gathered from all ranks for the SVD computation. For non-distributed settings this
701
+ argument is ignored. Set to False if you are using a non-distributed dataloader in a distributed setting.
702
+ show_progress_bar (bool): Whether to show a progress bar. Default is True.
703
+
704
+ Returns:
705
+ model (torch.nn.Module): The model with the initialized LoRA weights.
706
+ """
707
+ if not hasattr(model, "peft_config"):
708
+ raise ValueError("model must be a PeftModel")
709
+
710
+ # eva currently only works with a single active adapter
711
+ # Important: when removing this requirement, make sure eva init works correctly if the new rank is 0.
712
+ if len(model.active_adapters) > 1:
713
+ raise ValueError("`initialize_lora_eva_weights` currently only works with a single active adapter")
714
+
715
+ # initialize_lora_eva_weights only works with `init_lora_weights='eva'`
716
+ if model.peft_config[adapter_name].init_lora_weights != "eva":
717
+ raise ValueError("`initialize_lora_eva_weights` can only be used with `init_lora_weights='eva'`")
718
+
719
+ # compute svd
720
+ if eva_state_dict is None:
721
+ if dataloader is None:
722
+ raise ValueError("dataloader is required if eva_state_dict is not provided")
723
+ eva_state_dict = get_eva_state_dict(
724
+ model=model,
725
+ dataloader=dataloader,
726
+ forward_fn=forward_fn,
727
+ prepare_model_inputs_fn=prepare_model_inputs_fn,
728
+ prepare_layer_inputs_fn=prepare_layer_inputs_fn,
729
+ adapter_name=adapter_name,
730
+ gather_distributed_inputs=gather_distributed_inputs,
731
+ show_progress_bar=show_progress_bar,
732
+ )
733
+
734
+ _load_eva_state_dict(model, eva_state_dict, adapter_name)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/hqq.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from __future__ import annotations
15
+
16
+ import copy
17
+ import warnings
18
+ from typing import Any, Optional
19
+
20
+ import torch
21
+
22
+ from peft.import_utils import is_hqq_available
23
+ from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge
24
+ from peft.utils.other import transpose
25
+
26
+ from .config import LoraConfig
27
+ from .layer import LoraLayer, LoraVariant
28
+
29
+
30
+ if is_hqq_available():
31
+ from hqq.core.quantize import HQQLinear
32
+
33
+ class HqqLoraLinear(torch.nn.Module, LoraLayer):
34
+ # Lora implemented in a dense layer
35
+ def __init__(
36
+ self,
37
+ base_layer: torch.nn.Module,
38
+ adapter_name: str,
39
+ config: LoraConfig,
40
+ r: int = 0,
41
+ lora_alpha: int = 1,
42
+ **kwargs,
43
+ ) -> None:
44
+ if config.lora_bias:
45
+ raise ValueError(f"{self.__class__.__name__} does not support lora_bias yet, set it to False")
46
+
47
+ super().__init__()
48
+ LoraLayer.__init__(self, base_layer)
49
+ self.fan_in_fan_out = False
50
+
51
+ self._active_adapter = adapter_name
52
+ self.update_layer(
53
+ adapter_name,
54
+ r,
55
+ lora_alpha=lora_alpha,
56
+ config=config,
57
+ )
58
+
59
+ def resolve_lora_variant(self, *, config: LoraConfig, **kwargs) -> Optional[LoraVariant]:
60
+ if not config.use_dora:
61
+ return None
62
+
63
+ from .variants import DoraLinearVariant
64
+
65
+ return DoraLinearVariant()
66
+
67
+ def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None:
68
+ """
69
+ Merge the active adapter weights into the base weights
70
+
71
+ Args:
72
+ safe_merge (`bool`, *optional*):
73
+ If True, the merge operation will be performed in a copy of the original weights and check for NaNs
74
+ before merging the weights. This is useful if you want to check if the merge operation will produce
75
+ NaNs. Defaults to `False`.
76
+ adapter_names (`list[str]`, *optional*):
77
+ The list of adapter names that should be merged. If None, all active adapters will be merged.
78
+ Defaults to `None`.
79
+ """
80
+ adapter_names = check_adapters_to_merge(self, adapter_names)
81
+ if not adapter_names:
82
+ # no adapter to merge
83
+ return
84
+
85
+ for active_adapter in adapter_names:
86
+ if active_adapter not in self.lora_A.keys():
87
+ continue
88
+
89
+ layer = self.get_base_layer()
90
+ quant_config = {**copy.deepcopy(layer.quant_config), "offload_meta": layer.offload_meta}
91
+
92
+ output = layer.dequantize()
93
+ if active_adapter not in self.lora_variant: # vanilla LoRA
94
+ lora_data = self.get_delta_weight(active_adapter)
95
+ w_data = output + lora_data
96
+ else:
97
+ w_data = self.lora_variant[active_adapter].merge_safe(self, active_adapter, output)
98
+
99
+ if safe_merge and not torch.isfinite(w_data).all():
100
+ raise ValueError(
101
+ f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken"
102
+ )
103
+
104
+ new_hqq_layer = HQQLinear(None, quant_config, compute_dtype=layer.compute_dtype, device=layer.device)
105
+ quant_config.pop("offload_meta", None)
106
+ new_hqq_layer.quantize(w_data, **quant_config)
107
+ self.base_layer = new_hqq_layer
108
+ self.merged_adapters.append(active_adapter)
109
+
110
+ def unmerge(self) -> None:
111
+ """
112
+ This method unmerges all merged adapter layers from the base weights.
113
+ """
114
+ if not self.merged:
115
+ warnings.warn("Already unmerged. Nothing to do.")
116
+ return
117
+
118
+ while len(self.merged_adapters) > 0:
119
+ active_adapter = self.merged_adapters.pop()
120
+ if active_adapter not in self.lora_A.keys():
121
+ continue
122
+
123
+ layer = self.get_base_layer()
124
+ quant_config = {**copy.deepcopy(layer.quant_config), "offload_meta": layer.offload_meta}
125
+ output = layer.dequantize()
126
+
127
+ if active_adapter not in self.lora_variant: # vanilla LoRA
128
+ lora_data = self.get_delta_weight(active_adapter)
129
+ w_data = output.to(lora_data.dtype).to(lora_data.device) - lora_data
130
+ else:
131
+ w_data = self.lora_variant[active_adapter].unmerge(self, active_adapter, output)
132
+
133
+ new_hqq_layer = HQQLinear(None, quant_config, compute_dtype=layer.compute_dtype, device=layer.device)
134
+ quant_config.pop("offload_meta", None)
135
+ new_hqq_layer.quantize(w_data, **quant_config)
136
+ self.base_layer = new_hqq_layer
137
+
138
+ def get_delta_weight(self, adapter):
139
+ return (
140
+ transpose(
141
+ self.lora_B[adapter].weight @ self.lora_A[adapter].weight,
142
+ False,
143
+ )
144
+ * self.scaling[adapter]
145
+ )
146
+
147
+ def _mixed_batch_forward(
148
+ self, x: torch.Tensor, *args: Any, adapter_names: list[str], **kwargs: Any
149
+ ) -> torch.Tensor:
150
+ # This is a special method that handles the case when users pass the argument `adapter_names`. This is an
151
+ # extra argument that allows mixing different adapters in the same batch at inference time.
152
+ result = self.base_layer(x, *args, **kwargs)
153
+
154
+ unique_adapters = set(adapter_names)
155
+ sub_batch_indices_list = []
156
+ for adapter in unique_adapters:
157
+ sub_batch_indices_list.append([index for index, item in enumerate(adapter_names) if item == adapter])
158
+
159
+ for i, active_adapter in enumerate(unique_adapters):
160
+ if active_adapter == "__base__":
161
+ continue
162
+ if active_adapter not in self.lora_A.keys():
163
+ continue
164
+
165
+ lora_A = self.lora_A[active_adapter]
166
+ lora_B = self.lora_B[active_adapter]
167
+ dropout = self.lora_dropout[active_adapter]
168
+ scaling = self.scaling[active_adapter]
169
+
170
+ requires_conversion = not torch.is_autocast_enabled()
171
+ if requires_conversion:
172
+ expected_dtype = result.dtype
173
+ x = self._cast_input_dtype(x, lora_A.weight.dtype)
174
+
175
+ # getting the sub-batch, passing it to LoRA layers and updating the corresponding indices of the linear
176
+ # layer output
177
+ sub_batch = x[sub_batch_indices_list[i]]
178
+ output = lora_B(lora_A(dropout(sub_batch))) * scaling
179
+ if requires_conversion:
180
+ output = output.to(expected_dtype)
181
+ result[sub_batch_indices_list[i]] += output
182
+
183
+ return result
184
+
185
+ def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor:
186
+ self._check_forward_args(x, *args, **kwargs)
187
+ adapter_names = kwargs.pop("adapter_names", None)
188
+
189
+ if self.disable_adapters:
190
+ if self.merged:
191
+ self.unmerge()
192
+ result = self.base_layer(x, *args, **kwargs)
193
+ elif adapter_names is not None:
194
+ result = self._mixed_batch_forward(x, *args, adapter_names=adapter_names, **kwargs)
195
+ elif self.merged:
196
+ result = self.base_layer(x, *args, **kwargs)
197
+ else:
198
+ result = self.base_layer(x, *args, **kwargs)
199
+
200
+ for active_adapter in self.active_adapters:
201
+ if active_adapter not in self.lora_A.keys():
202
+ continue
203
+ lora_A = self.lora_A[active_adapter]
204
+ lora_B = self.lora_B[active_adapter]
205
+ dropout = self.lora_dropout[active_adapter]
206
+ scaling = self.scaling[active_adapter]
207
+
208
+ requires_conversion = not torch.is_autocast_enabled()
209
+ if requires_conversion:
210
+ expected_dtype = result.dtype
211
+ x = self._cast_input_dtype(x, lora_A.weight.dtype)
212
+
213
+ if active_adapter not in self.lora_variant: # vanilla LoRA
214
+ result = result + lora_B(lora_A(dropout(x))) * scaling
215
+ else:
216
+ result = self.lora_variant[active_adapter].forward(
217
+ self,
218
+ active_adapter=active_adapter,
219
+ x=x,
220
+ result=result,
221
+ )
222
+
223
+ if requires_conversion:
224
+ result = result.to(expected_dtype)
225
+
226
+ return result
227
+
228
+ def __repr__(self) -> str:
229
+ rep = super().__repr__()
230
+ return "lora." + rep
231
+
232
+
233
+ def dispatch_hqq(target: torch.nn.Module, adapter_name: str, config: LoraConfig, **kwargs):
234
+ new_module = None
235
+
236
+ if isinstance(target, BaseTunerLayer):
237
+ target_base_layer = target.get_base_layer()
238
+ else:
239
+ target_base_layer = target
240
+
241
+ if is_hqq_available() and isinstance(target_base_layer, HQQLinear):
242
+ new_module = HqqLoraLinear(target_base_layer, adapter_name, config=config, **kwargs)
243
+
244
+ return new_module
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/intruders.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import torch
16
+
17
+ from .layer import LoraLayer
18
+
19
+
20
+ def reduce_intruder_dimension(
21
+ peft_model,
22
+ old_adapter_name="default",
23
+ new_adapter_name="intruder_reduced",
24
+ top_k=10,
25
+ threshold_epsilon=0.5,
26
+ mitigation_lambda=0.75,
27
+ logging_sink=print,
28
+ ):
29
+ """
30
+ Intruder dimension mitigation based on https://huggingface.co/papers/2410.21228 ("LoRA vs Full Fine-tuning: An
31
+ Illusion of Equivalence").
32
+
33
+ This method can recover previous knowledge (i.e. mitigate forgetting) by post-processing already trained low-rank
34
+ adapters. This comes at a cost of task accuracy - tuning the `migration_lambda` value can be used to trade between
35
+ these two factors.
36
+
37
+ After mitigation is done there will be a new adapter with the name set in `new_adapter_name` which is also set to
38
+ be the currently active adapter. Inference on the mitigated model will therefore use the modified adapter. To
39
+ switch back to the original adapter you can use `peft_model.set_adapter(<old_adapter_name>)`.
40
+
41
+ Currently only LoRA is supported as it is not clear whether this method generalizes to other delta-weight methods.
42
+
43
+ Parameters:
44
+ peft_model:
45
+ The PEFT model with a loaded LoRA adapter with the name provided in `old_adapter_name`. Currently mixed
46
+ models are not supported.
47
+
48
+ top_k (default: 10)
49
+ Consider the top-k dimensions for intruder detection. The larger the value, the more dimensions will be
50
+ considered for intruder detection analysis (and the more false-postiives there can be). Operates on the
51
+ cosine similarity between base weights and adapter weights roughly sorted by influence of dimension
52
+ (determined by singular value decomposition), so a top-k of 10 will look at the 10 most 'important'
53
+ dimensions.
54
+
55
+ threshold_epsilon (default: 0.5)
56
+ Threshold value when to consider a cosine similarity between base weight and adapter weight as intruder.
57
+ According to the paper, intruder dimensions show near-zero absolute cosine similarity with pre-trained
58
+ singular vectors. The lower this value, the less potential intruder dimensions are identified. The higher
59
+ the value, the more potential false-positives are considered as intruders.
60
+
61
+ mitigation_lambda (default: 0.75)
62
+ The relative portion of the intruder dimensions that is subtracted from the adapter's delta weight. The
63
+ higher the value the more of the intruder dimension is subtracted but the more information is lost. Refer
64
+ to Figure 8 in the paper for a trade-off analysis.
65
+
66
+ logging_sink (default: print)
67
+ Function that prints information about the mitigation process. Set to None if you don't want any output.
68
+ """
69
+ # Note that this function currently doesn't support `compile_kwargs` similar to the LoRA conversion tooling
70
+ # since there's was no clear way how `torch.compile` can be used to improve performance at the time of
71
+ # implementation. See discussion: https://github.com/huggingface/peft/pull/2999#discussion_r2717989613
72
+
73
+ def no_logging_sink(*args, **kwargs):
74
+ pass
75
+
76
+ if logging_sink is None:
77
+ logging_sink = no_logging_sink
78
+
79
+ if peft_model.peft_type != "LORA":
80
+ raise ValueError("The provided model is not using LoRA and is therefore not supported.")
81
+
82
+ peft_model.add_adapter(new_adapter_name, peft_model.peft_config[old_adapter_name])
83
+
84
+ # apply mitigation on the old adapter's weights and move them to the new adapter's weights
85
+ for layer_name, layer in peft_model.named_modules():
86
+ if not isinstance(layer, LoraLayer):
87
+ continue
88
+
89
+ W = layer.get_base_layer().weight.data
90
+ dW = layer.get_delta_weight(old_adapter_name)
91
+ W_merged = W + dW
92
+ is_embedding = old_adapter_name not in layer.lora_B
93
+
94
+ cast_to_fp32 = W.dtype in (torch.float16, torch.bfloat16)
95
+
96
+ if cast_to_fp32:
97
+ W_dtype = W.dtype
98
+ W = W.float()
99
+
100
+ # compare base weights and adapter weights using cosine similarity.
101
+ # based on this similarity we can find intruder dimensions using threshold_epsilon
102
+ # on the top_k dimensions
103
+ U_base, _S_base, _V_base = torch.linalg.svd(W, full_matrices=False)
104
+ U_merged, S_merged, V_merged = torch.linalg.svd(W_merged, full_matrices=False)
105
+
106
+ cos_sim = (U_merged.T @ U_base).abs().max(dim=1).values
107
+ intruder_idcs = torch.where(cos_sim[:top_k] < threshold_epsilon)[0].tolist()
108
+
109
+ if not intruder_idcs:
110
+ logging_sink(f"{layer_name}: No intruders")
111
+
112
+ # we're not modifying the weights since there are no intruders but we make sure to copy the
113
+ # adapter weights unmodified to the new adapter, otherwise these weights will be
114
+ # initialized randomly
115
+ if is_embedding:
116
+ layer.lora_embedding_B[new_adapter_name].data = layer.lora_embedding_B[old_adapter_name].data.clone()
117
+ layer.lora_embedding_A[new_adapter_name].data = layer.lora_embedding_A[old_adapter_name].data.clone()
118
+ else:
119
+ layer.lora_B[new_adapter_name].weight.data = layer.lora_B[old_adapter_name].weight.data.clone()
120
+ layer.lora_A[new_adapter_name].weight.data = layer.lora_A[old_adapter_name].weight.data.clone()
121
+ continue
122
+ else:
123
+ logging_sink(f"{layer_name}: Intruders: {len(intruder_idcs)}")
124
+
125
+ # the paper computes the intruder dimensions that are subtracted on (W + dW), so we do the same. experiments
126
+ # showed that this achieves better knowledge recovery than on dW alone.
127
+ B_intruder = U_merged[:, intruder_idcs] @ torch.diag(S_merged)[intruder_idcs, :].sqrt()
128
+ A_intruder = (torch.diag(S_merged)[:, intruder_idcs]).sqrt() @ V_merged[intruder_idcs, :]
129
+
130
+ # apply mitigation and recover dW = (B@A).
131
+ # (W+dW+mitigation)-W = dW+mitigation, so we can convert dW back to A/B using SVD
132
+ # since we know the effective rank from the adapter config.
133
+ #
134
+ # note that we also remove the scaling from dW which is applied in get_delta_weight() since
135
+ # it impacts mitigation performance both in task accuracy and forgetting.
136
+ W_mitigated = W_merged + (mitigation_lambda - 1) * (B_intruder @ A_intruder)
137
+ dW_mitigated = W_mitigated - W
138
+ dW_mitigated /= layer.scaling[old_adapter_name]
139
+
140
+ U_dW, S_dW, V_dW = torch.linalg.svd(dW_mitigated, full_matrices=False)
141
+
142
+ # Note: share scaling by S equally between B and A to avoid one matrix having a significantly
143
+ # different norm and avoid possibly weird training dynamics.
144
+ effective_rank = layer.r[old_adapter_name]
145
+ B_new = U_dW[:, :effective_rank] @ torch.diag(S_dW[:effective_rank]).sqrt()
146
+ A_new = torch.diag(S_dW[:effective_rank]).sqrt() @ V_dW[:effective_rank]
147
+
148
+ if is_embedding:
149
+ layer.lora_embedding_B[new_adapter_name].data = B_new
150
+ layer.lora_embedding_A[new_adapter_name].data = A_new
151
+ else:
152
+ layer.lora_B[new_adapter_name].weight.data = B_new
153
+ layer.lora_A[new_adapter_name].weight.data = A_new
154
+
155
+ # cast W back from float32 to whatever it was before to save memory in the long run
156
+ if cast_to_fp32:
157
+ W = W.to(W_dtype)
158
+
159
+ logging_sink(f"Enabling new adapter {new_adapter_name}")
160
+ peft_model.set_adapter(new_adapter_name)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/loraga.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # Reference code: https://github.com/Outsider565/LoRA-GA
16
+ # Reference paper: https://arxiv.org/abs/2407.05000
17
+
18
+ import os
19
+ from collections.abc import Callable
20
+ from typing import Any, Optional
21
+
22
+ import torch
23
+ import torch.nn as nn
24
+ from transformers.pytorch_utils import Conv1D
25
+
26
+ from peft.tuners.lora.config import LoraConfig
27
+ from peft.tuners.lora.model import LoraModel
28
+
29
+
30
+ def get_target_modules(model: nn.Module, config: LoraConfig):
31
+ """
32
+ Iterate over LoRA-GA target name and modules of a model. A module is a target if its name is in
33
+ `config.target_modules` and is `nn.Linear` or `Conv1D`.
34
+ """
35
+ for name, module in model.named_modules():
36
+ if LoraModel._check_target_module_exists(config, name) and isinstance(module, (nn.Linear, Conv1D)):
37
+ yield name, module
38
+
39
+
40
+ def get_model_device(model: nn.Module) -> str:
41
+ if hasattr(model, "module"): # Handle DeepSpeed/DataParallel
42
+ model = model.module
43
+ return next(iter(model.parameters())).device
44
+
45
+
46
+ @torch.no_grad()
47
+ def preprocess_loraga(
48
+ model: nn.Module,
49
+ lora_config: LoraConfig,
50
+ train_step: Callable[[], None],
51
+ cache_file: Optional[str] = None,
52
+ ):
53
+ """
54
+ Build necessary LoRA-GA fields for a model by estimating gradients.
55
+
56
+ For each linear layer, gradients will be estimated by running the provided train_step callback. These gradients are
57
+ then attached to the modules and used during initialization.
58
+
59
+ Args:
60
+ model (`nn.Module`):
61
+ Model to preprocess.
62
+ lora_config (`LoraConfig`):
63
+ Lora configuration of the model. `lora_config.lora_ga_config` should be set.
64
+ train_step (`Callable[[], None]`):
65
+ Callback to run gradient estimation. Typically you should run model forward and backward passes in this
66
+ callback. The gradients will be accumulated across all calls within this callback.
67
+ cache_file (`Optional[str]`):
68
+ Optional path to cache file for saving/loading gradients. If provided and the file exists, gradients will
69
+ be loaded from cache. Otherwise, gradients will be estimated and saved to this path.
70
+
71
+ Upon completion, the following fields are set for each target module:
72
+ _peft_loraga_grad (`torch.Tensor`):
73
+ Accumulated gradient for the weight matrix.
74
+ """
75
+ if lora_config.lora_ga_config is None:
76
+ raise ValueError(
77
+ "If you want to use LoRA-GA, please initialize the LoraConfig with "
78
+ "init_lora_weights='lora_ga' and lora_ga_config=LoraGAConfig(...)."
79
+ )
80
+
81
+ # Populate target_modules from defaults if empty
82
+ # This logic mirrors BaseTuner._prepare_adapter_config which runs after get_peft_model.
83
+ # Since preprocess_loraga is called before get_peft_model, we need to handle this ourselves.
84
+ if lora_config.target_modules is None:
85
+ model_config = LoraModel.get_model_config(model)
86
+ target_modules = LoraModel.target_module_mapping.get(model_config["model_type"])
87
+ if target_modules is None:
88
+ raise ValueError("Please specify `target_modules` in `peft_config`")
89
+ lora_config.target_modules = set(target_modules)
90
+
91
+ # Check for quantized models - LoRA-GA requires full-precision gradients
92
+ for name, module in get_target_modules(model, lora_config):
93
+ if hasattr(module, "quant_state"):
94
+ raise ValueError(
95
+ f"LoRA-GA does not support quantized models. Found quantized module: '{name}'. "
96
+ "LoRA-GA requires full-precision gradients during preprocessing."
97
+ )
98
+
99
+ # If cache exists, load from cache
100
+ if cache_file is not None and os.path.exists(cache_file) and os.path.getsize(cache_file) > 0:
101
+ cache = torch.load(cache_file, map_location=get_model_device(model))
102
+ for name, module in get_target_modules(model, lora_config):
103
+ module._peft_loraga_grad = cache[f"{name}._peft_loraga_grad"]
104
+ else:
105
+ # Estimate gradients by running train_step
106
+ estimate_gradients(model, lora_config, train_step)
107
+
108
+ # Save cache to disk if specified
109
+ if cache_file is not None:
110
+ cache: dict[str, Any] = {}
111
+ for name, module in get_target_modules(model, lora_config):
112
+ cache[f"{name}._peft_loraga_grad"] = module._peft_loraga_grad
113
+
114
+ os.makedirs(os.path.dirname(cache_file), exist_ok=True)
115
+ torch.save(cache, cache_file)
116
+
117
+
118
+ def estimate_gradients(
119
+ model: nn.Module,
120
+ lora_config: LoraConfig,
121
+ train_step: Callable[[], None],
122
+ ):
123
+ """
124
+ Estimate gradients for LoRA-GA initialization.
125
+
126
+ This function enables gradient computation ONLY on target module weights and runs the train_step callback. This is
127
+ more memory-efficient than enabling gradients globally.
128
+ """
129
+ # Remember original training state
130
+ was_training = model.training
131
+ model.train()
132
+
133
+ # Get target modules list once for efficiency
134
+ target_module_list = list(get_target_modules(model, lora_config))
135
+
136
+ # Check if any supported layers were found
137
+ if not target_module_list:
138
+ raise ValueError(
139
+ "No supported layers found for LoRA-GA initialization. "
140
+ "LoRA-GA only supports nn.Linear and Conv1D layers. "
141
+ "Please ensure your model contains at least one of these layer types in target_modules."
142
+ )
143
+
144
+ # Initialize gradient storage and count for each target module
145
+ for name, module in target_module_list:
146
+ module._peft_loraga_grad_count = 0
147
+
148
+ # Memory-efficient gradient computation: disable gradients for all parameters first,
149
+ # then enable only for target module weights
150
+ original_requires_grad = {}
151
+ for name, param in model.named_parameters():
152
+ original_requires_grad[name] = param.requires_grad
153
+ param.requires_grad = False
154
+
155
+ # Enable gradients ONLY for target module weights
156
+ for name, module in target_module_list:
157
+ module.weight.requires_grad = True
158
+
159
+ # Register backward hooks to count gradient computations
160
+ hooks = []
161
+
162
+ def backward_hook(module, grad_input, grad_output):
163
+ module._peft_loraga_grad_count += 1
164
+
165
+ for name, module in target_module_list:
166
+ hook = module.register_full_backward_hook(backward_hook)
167
+ hooks.append(hook)
168
+
169
+ # Enable gradient computation and run train_step
170
+ with torch.enable_grad():
171
+ train_step()
172
+
173
+ # Remove hooks
174
+ for hook in hooks:
175
+ hook.remove()
176
+
177
+ # Restore original requires_grad state for all parameters
178
+ for name, param in model.named_parameters():
179
+ if name in original_requires_grad:
180
+ param.requires_grad = original_requires_grad[name]
181
+
182
+ # Average gradients and clean up temporary fields
183
+ for name, module in target_module_list:
184
+ if module._peft_loraga_grad_count > 0:
185
+ module._peft_loraga_grad = module.weight.grad.detach() / module._peft_loraga_grad_count
186
+ module.weight.grad = None
187
+ del module._peft_loraga_grad_count
188
+
189
+ # Restore original training state
190
+ if not was_training:
191
+ model.eval()
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/multitask_prompt_tuning/__init__.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from peft.utils import register_peft_method
16
+
17
+ from .config import MultitaskPromptTuningConfig, MultitaskPromptTuningInit
18
+ from .model import MultitaskPromptEmbedding
19
+
20
+
21
+ __all__ = ["MultitaskPromptEmbedding", "MultitaskPromptTuningConfig", "MultitaskPromptTuningInit"]
22
+
23
+ register_peft_method(
24
+ name="multitask_prompt_tuning", config_cls=MultitaskPromptTuningConfig, model_cls=MultitaskPromptEmbedding
25
+ )
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/multitask_prompt_tuning/__pycache__/config.cpython-310.pyc ADDED
Binary file (1.9 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/multitask_prompt_tuning/__pycache__/model.cpython-310.pyc ADDED
Binary file (2.59 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/multitask_prompt_tuning/config.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import enum
16
+ from dataclasses import dataclass, field
17
+ from typing import Optional, Union
18
+
19
+ from peft.tuners.prompt_tuning import PromptTuningConfig
20
+ from peft.utils import PeftType
21
+
22
+
23
+ class MultitaskPromptTuningInit(str, enum.Enum):
24
+ # initialize prompt with text
25
+ TEXT = "TEXT"
26
+ # initialize prompt with random matrix
27
+ RANDOM = "RANDOM"
28
+ # average the prefix and column matrices obtained during source training
29
+ AVERAGE_SOURCE_TASKS = "AVERAGE_SOURCE_TASKS"
30
+ # pick prefix and column matrices for a particular task obtained during source training
31
+ EXACT_SOURCE_TASK = "EXACT_SOURCE_TASK"
32
+ # only use the prompt embeddings trained during source training
33
+ ONLY_SOURCE_SHARED = "ONLY_SOURCE_SHARED"
34
+
35
+
36
+ @dataclass
37
+ class MultitaskPromptTuningConfig(PromptTuningConfig):
38
+ prompt_tuning_init: Union[MultitaskPromptTuningInit, str] = field(
39
+ default=MultitaskPromptTuningInit.RANDOM,
40
+ metadata={
41
+ "help": (
42
+ "How to initialize the prompt tuning parameters. Can be one of TEXT, RANDOM, AVERAGE_SOURCE_TASKS, "
43
+ "EXACT_SOURCE_TASK, ONLY_SOURCE_SHARED."
44
+ ),
45
+ },
46
+ )
47
+ prompt_tuning_init_state_dict_path: Optional[str] = field(
48
+ default=None,
49
+ metadata={
50
+ "help": (
51
+ "The path of source state dict. This is required when training the downstream target prompt from "
52
+ "the pretrained source prompt"
53
+ ),
54
+ },
55
+ )
56
+ prompt_tuning_init_task: Optional[int] = field(default=0, metadata={"help": "source task id for initialization"})
57
+ num_ranks: Optional[int] = field(default=1, metadata={"help": "ranks"})
58
+ num_tasks: Optional[int] = field(default=1, metadata={"help": "number of tasks"})
59
+
60
+ def __post_init__(self):
61
+ super().__post_init__()
62
+ self.peft_type = PeftType.MULTITASK_PROMPT_TUNING
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/multitask_prompt_tuning/model.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import torch
16
+
17
+ from peft.tuners.prompt_tuning import PromptEmbedding
18
+ from peft.utils import TaskType
19
+ from peft.utils.save_and_load import torch_load
20
+
21
+ from .config import MultitaskPromptTuningConfig, MultitaskPromptTuningInit
22
+
23
+
24
+ # This code is adapted for the paper: https://huggingface.co/papers/2303.02861 and
25
+ # constitutes the work done at MIT-IBM Watson Research Lab.
26
+
27
+
28
+ class MultitaskPromptEmbedding(PromptEmbedding):
29
+ def __init__(self, config: MultitaskPromptTuningConfig, word_embeddings):
30
+ super().__init__(config, word_embeddings)
31
+
32
+ self.num_tasks = config.num_tasks
33
+ self.num_ranks = config.num_ranks
34
+ self.num_virtual_tokens = config.num_virtual_tokens
35
+
36
+ self.num_transformer_submodules = config.num_transformer_submodules
37
+ if self.num_transformer_submodules is None:
38
+ self.num_transformer_submodules = 2 if config.task_type == TaskType.SEQ_2_SEQ_LM else 1
39
+
40
+ self.token_dim = config.token_dim
41
+
42
+ total_virtual_tokens = self.num_virtual_tokens * self.num_transformer_submodules
43
+
44
+ self.prefix_task_cols = torch.nn.Parameter(
45
+ torch.normal(
46
+ mean=0,
47
+ std=0.02,
48
+ size=(self.num_tasks, total_virtual_tokens, self.num_ranks),
49
+ )
50
+ )
51
+ self.prefix_task_rows = torch.nn.Parameter(
52
+ torch.normal(
53
+ mean=0,
54
+ std=0.02,
55
+ size=(self.num_tasks, self.num_ranks, self.token_dim),
56
+ )
57
+ )
58
+
59
+ if config.prompt_tuning_init in [
60
+ MultitaskPromptTuningInit.AVERAGE_SOURCE_TASKS,
61
+ MultitaskPromptTuningInit.EXACT_SOURCE_TASK,
62
+ MultitaskPromptTuningInit.ONLY_SOURCE_SHARED,
63
+ ]:
64
+ if config.prompt_tuning_init_state_dict_path is None:
65
+ raise ValueError(
66
+ f"prompt_tuning_init_state_dict_path needs to be specified with {config.prompt_tuning_init} "
67
+ "init method"
68
+ )
69
+
70
+ if config.prompt_tuning_init_state_dict_path.endswith(".safetensors"):
71
+ from safetensors.torch import load_file
72
+
73
+ state_dict: dict = load_file(config.prompt_tuning_init_state_dict_path)
74
+ else:
75
+ state_dict: dict = torch_load(
76
+ config.prompt_tuning_init_state_dict_path,
77
+ map_location=word_embeddings.weight.device,
78
+ )
79
+
80
+ if config.prompt_tuning_init in [
81
+ MultitaskPromptTuningInit.AVERAGE_SOURCE_TASKS,
82
+ MultitaskPromptTuningInit.EXACT_SOURCE_TASK,
83
+ ]:
84
+ prefix_task_cols_: torch.Tensor = state_dict["prefix_task_cols"]
85
+ prefix_task_rows_: torch.Tensor = state_dict["prefix_task_rows"]
86
+
87
+ if config.prompt_tuning_init == MultitaskPromptTuningInit.AVERAGE_SOURCE_TASKS:
88
+ prefix_task_cols_ = prefix_task_cols_.mean(0, keepdim=True)
89
+ prefix_task_rows_ = prefix_task_rows_.mean(0, keepdim=True)
90
+ elif config.prompt_tuning_init == MultitaskPromptTuningInit.EXACT_SOURCE_TASK:
91
+ prefix_task_cols_ = prefix_task_cols_[config.prompt_tuning_init_task, ...].unsqueeze(0)
92
+ prefix_task_rows_ = prefix_task_rows_[config.prompt_tuning_init_task, ...].unsqueeze(0)
93
+
94
+ state_dict = {
95
+ "embedding.weight": state_dict["prompt_embeddings"],
96
+ "prefix_task_cols": prefix_task_cols_,
97
+ "prefix_task_rows": prefix_task_rows_,
98
+ }
99
+
100
+ self.load_state_dict(state_dict, strict=True)
101
+ elif config.prompt_tuning_init == MultitaskPromptTuningInit.ONLY_SOURCE_SHARED:
102
+ state_dict = {
103
+ "embedding.weight": state_dict["prompt_embeddings"],
104
+ }
105
+
106
+ self.load_state_dict(state_dict, strict=False)
107
+
108
+ def forward(self, indices, task_ids):
109
+ if task_ids is None:
110
+ raise ValueError("task_ids cannot be None")
111
+
112
+ prompt_embeddings = self.embedding(indices)
113
+
114
+ task_cols = torch.index_select(self.prefix_task_cols, 0, task_ids)
115
+ task_rows = torch.index_select(self.prefix_task_rows, 0, task_ids)
116
+ task_prompts = torch.matmul(task_cols, task_rows)
117
+
118
+ prompt_embeddings *= task_prompts
119
+
120
+ return prompt_embeddings
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__init__.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from peft.import_utils import is_bnb_4bit_available, is_bnb_available, is_eetq_available
16
+ from peft.utils import register_peft_method
17
+
18
+ from .config import OFTConfig
19
+ from .gptq import GPTQOFTLinear
20
+ from .layer import Conv2d, Linear, OFTLayer
21
+ from .model import OFTModel
22
+
23
+
24
+ __all__ = [
25
+ "Conv2d",
26
+ "GPTQOFTLinear",
27
+ "Linear",
28
+ "OFTConfig",
29
+ "OFTLayer",
30
+ "OFTModel",
31
+ ]
32
+
33
+ register_peft_method(name="oft", config_cls=OFTConfig, model_cls=OFTModel)
34
+
35
+
36
+ def __getattr__(name):
37
+ if (name == "Linear8bitLt") and is_bnb_available():
38
+ from .bnb import Linear8bitLt
39
+
40
+ return Linear8bitLt
41
+
42
+ if (name == "Linear4bit") and is_bnb_4bit_available():
43
+ from .bnb import Linear4bit
44
+
45
+ return Linear4bit
46
+
47
+ if (name == "EetqOFTLinear") and is_eetq_available():
48
+ from .eetq import EetqOFTLinear
49
+
50
+ return EetqOFTLinear
51
+
52
+ raise AttributeError(f"module {__name__} has no attribute {name}")
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.07 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/aqlm.cpython-310.pyc ADDED
Binary file (2.47 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/awq.cpython-310.pyc ADDED
Binary file (2.52 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/bnb.cpython-310.pyc ADDED
Binary file (8.88 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/config.cpython-310.pyc ADDED
Binary file (9.25 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/eetq.cpython-310.pyc ADDED
Binary file (2.96 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/gptq.cpython-310.pyc ADDED
Binary file (2.52 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/hqq.cpython-310.pyc ADDED
Binary file (5.24 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/inc.cpython-310.pyc ADDED
Binary file (2.48 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/layer.cpython-310.pyc ADDED
Binary file (26.3 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/model.cpython-310.pyc ADDED
Binary file (5.39 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/aqlm.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import Any, Optional
16
+
17
+ import torch
18
+
19
+ from peft.import_utils import is_aqlm_available
20
+ from peft.tuners.oft.layer import OFTLayer
21
+ from peft.tuners.tuners_utils import BaseTunerLayer
22
+
23
+
24
+ if is_aqlm_available():
25
+ from aqlm import QuantizedLinear
26
+
27
+
28
+ class AqlmOFTLinear(torch.nn.Module, OFTLayer):
29
+ def __init__(
30
+ self,
31
+ base_layer,
32
+ adapter_name: str,
33
+ r: int = 0,
34
+ oft_block_size: int = 32,
35
+ module_dropout: float = 0.0,
36
+ init_weights: bool = True,
37
+ coft: bool = False,
38
+ eps: float = 6e-5,
39
+ block_share: bool = False,
40
+ fan_in_fan_out: bool = False, # Set this to True if the layer to replace stores weight like (fan_in, fan_out)
41
+ use_cayley_neumann: bool = False,
42
+ num_cayley_neumann_terms: int = 5,
43
+ **kwargs,
44
+ ):
45
+ super().__init__()
46
+ OFTLayer.__init__(self, base_layer)
47
+
48
+ self._active_adapter = adapter_name
49
+ self.update_layer(
50
+ adapter_name,
51
+ r,
52
+ oft_block_size=oft_block_size,
53
+ module_dropout=module_dropout,
54
+ init_weights=init_weights,
55
+ coft=coft,
56
+ eps=eps,
57
+ block_share=block_share,
58
+ use_cayley_neumann=use_cayley_neumann,
59
+ num_cayley_neumann_terms=num_cayley_neumann_terms,
60
+ )
61
+
62
+ def forward(self, x: torch.Tensor):
63
+ # note: logic differs from default Linear because merging is not supported
64
+ if self.disable_adapters:
65
+ return self.base_layer(x)
66
+
67
+ for active_adapter in self.active_adapters:
68
+ if active_adapter not in self.oft_R.keys():
69
+ continue
70
+ oft_R = self.oft_R[active_adapter]
71
+
72
+ requires_conversion = not torch.is_autocast_enabled()
73
+ if requires_conversion:
74
+ expected_dtype = x.dtype
75
+ x = self._cast_input_dtype(x, oft_R.weight.dtype)
76
+
77
+ x = oft_R(x)
78
+
79
+ result = self.base_layer(x)
80
+ if requires_conversion:
81
+ result = result.to(expected_dtype)
82
+ return result
83
+
84
+ def __repr__(self) -> str:
85
+ rep = super().__repr__()
86
+ return "oft." + rep
87
+
88
+
89
+ def dispatch_aqlm(
90
+ target: torch.nn.Module,
91
+ adapter_name: str,
92
+ **kwargs: Any,
93
+ ) -> Optional[torch.nn.Module]:
94
+ new_module = None
95
+
96
+ if isinstance(target, BaseTunerLayer):
97
+ target_base_layer = target.get_base_layer()
98
+ else:
99
+ target_base_layer = target
100
+
101
+ if is_aqlm_available() and isinstance(target_base_layer, QuantizedLinear):
102
+ new_module = AqlmOFTLinear(target, adapter_name, **kwargs)
103
+ target.qweight = target_base_layer.codes
104
+
105
+ return new_module
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/awq.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import Any, Optional
15
+
16
+ import torch
17
+
18
+ from peft.import_utils import is_gptqmodel_available
19
+ from peft.tuners.oft.layer import OFTLayer
20
+ from peft.tuners.tuners_utils import BaseTunerLayer
21
+
22
+
23
+ class AwqOFTLinear(torch.nn.Module, OFTLayer):
24
+ def __init__(
25
+ self,
26
+ base_layer,
27
+ adapter_name,
28
+ r: int = 0,
29
+ oft_block_size: int = 32,
30
+ module_dropout: float = 0.0,
31
+ coft: bool = False,
32
+ eps: float = 6e-5,
33
+ block_share: bool = False,
34
+ fan_in_fan_out: bool = False, # Set this to True if the layer to replace stores weight like (fan_in, fan_out)
35
+ init_weights: bool = True,
36
+ use_cayley_neumann: bool = False,
37
+ num_cayley_neumann_terms: int = 5,
38
+ **kwargs,
39
+ ):
40
+ super().__init__()
41
+ OFTLayer.__init__(self, base_layer)
42
+
43
+ # self.base_layer and self.quant_linear_module are the same; we need the former for consistency and the latter
44
+ # for backwards compatibility
45
+ self.quant_linear_module = base_layer
46
+
47
+ self._active_adapter = adapter_name
48
+ self.update_layer(
49
+ adapter_name,
50
+ r,
51
+ oft_block_size=oft_block_size,
52
+ module_dropout=module_dropout,
53
+ coft=coft,
54
+ eps=eps,
55
+ block_share=block_share,
56
+ init_weights=init_weights,
57
+ use_cayley_neumann=use_cayley_neumann,
58
+ num_cayley_neumann_terms=num_cayley_neumann_terms,
59
+ )
60
+
61
+ def forward(self, x: torch.Tensor):
62
+ if self.disable_adapters:
63
+ result = self.quant_linear_module(x)
64
+ return result
65
+
66
+ for active_adapter in self.active_adapters:
67
+ if active_adapter not in self.oft_R.keys():
68
+ continue
69
+ oft_R = self.oft_R[active_adapter]
70
+
71
+ requires_conversion = not torch.is_autocast_enabled()
72
+ if requires_conversion:
73
+ expected_dtype = x.dtype
74
+ x = self._cast_input_dtype(x, oft_R.weight.dtype)
75
+
76
+ x = oft_R(x)
77
+ if requires_conversion:
78
+ x = x.to(expected_dtype)
79
+
80
+ result = self.quant_linear_module(x)
81
+ return result
82
+
83
+ def __repr__(self) -> str:
84
+ rep = super().__repr__()
85
+ return "oft." + rep
86
+
87
+
88
+ def dispatch_awq(
89
+ target: torch.nn.Module,
90
+ adapter_name: str,
91
+ **kwargs: Any,
92
+ ) -> Optional[torch.nn.Module]:
93
+ new_module = None
94
+
95
+ if isinstance(target, BaseTunerLayer):
96
+ target_base_layer = target.get_base_layer()
97
+ else:
98
+ target_base_layer = target
99
+
100
+ if is_gptqmodel_available():
101
+ from gptqmodel.nn_modules.qlinear.gemm_awq import AwqGEMMQuantLinear
102
+
103
+ if isinstance(target_base_layer, AwqGEMMQuantLinear):
104
+ new_module = AwqOFTLinear(target, adapter_name, **kwargs)
105
+ target.qweight = target_base_layer.qweight
106
+
107
+ return new_module
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/bnb.py ADDED
@@ -0,0 +1,388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from __future__ import annotations
15
+
16
+ import warnings
17
+ from typing import Optional
18
+
19
+ import bitsandbytes as bnb
20
+ import torch
21
+
22
+ from peft.import_utils import is_bnb_4bit_available, is_bnb_available
23
+ from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge
24
+ from peft.utils.integrations import dequantize_bnb_weight
25
+
26
+ from .layer import OFTLayer
27
+
28
+
29
+ if is_bnb_available():
30
+
31
+ class Linear8bitLt(torch.nn.Module, OFTLayer):
32
+ # OFT implemented in a dense layer
33
+ def __init__(
34
+ self,
35
+ base_layer: torch.nn.Module,
36
+ adapter_name: str,
37
+ r: int = 8,
38
+ oft_block_size: int = 0,
39
+ module_dropout: float = 0.0,
40
+ init_weights: bool = True,
41
+ coft: bool = False,
42
+ eps: float = 6e-5,
43
+ block_share: bool = False,
44
+ use_cayley_neumann: bool = False,
45
+ num_cayley_neumann_terms: int = 5,
46
+ **kwargs,
47
+ ) -> None:
48
+ super().__init__()
49
+ OFTLayer.__init__(self, base_layer)
50
+ self.fan_in_fan_out = False
51
+
52
+ self._active_adapter = adapter_name
53
+ self.update_layer(
54
+ adapter_name,
55
+ r,
56
+ oft_block_size=oft_block_size,
57
+ module_dropout=module_dropout,
58
+ coft=coft,
59
+ eps=eps,
60
+ block_share=block_share,
61
+ init_weights=init_weights,
62
+ use_cayley_neumann=use_cayley_neumann,
63
+ num_cayley_neumann_terms=num_cayley_neumann_terms,
64
+ )
65
+
66
+ def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None:
67
+ """
68
+ Merge the active adapter weights into the base weights
69
+
70
+ Args:
71
+ safe_merge (`bool`, *optional*):
72
+ If True, the merge operation will be performed in a copy of the original weights and check for NaNs
73
+ before merging the weights. This is useful if you want to check if the merge operation will produce
74
+ NaNs. Defaults to `False`.
75
+ adapter_names (`list[str]`, *optional*):
76
+ The list of adapter names that should be merged. If None, all active adapters will be merged.
77
+ Defaults to `None`.
78
+ """
79
+ adapter_names = check_adapters_to_merge(self, adapter_names)
80
+ if not adapter_names:
81
+ # no adapter to merge
82
+ return
83
+
84
+ for active_adapter in adapter_names:
85
+ if active_adapter not in self.oft_R.keys():
86
+ continue
87
+
88
+ warnings.warn("Merge oft module to 8-bit linear may get different generations due to rounding errors.")
89
+
90
+ weight = self.get_base_layer().weight
91
+ state = self.get_base_layer().state
92
+ if state.SCB is None:
93
+ state.SCB = weight.SCB
94
+
95
+ # Dequantize the result of identity matrix and int8 weight because bitsandbytes does not support int8
96
+ # dequantization directly
97
+ output = dequantize_bnb_weight(weight, state=state)
98
+ oft_data = self.get_delta_weight(active_adapter)
99
+
100
+ output = torch.transpose(output, 0, 1)
101
+ w_data = torch.mm(oft_data, output.to(oft_data.dtype))
102
+ w_data = torch.transpose(w_data, 0, 1)
103
+ w_data = output.to(oft_data.dtype).to(oft_data.device)
104
+
105
+ if safe_merge and not torch.isfinite(w_data).all():
106
+ raise ValueError(
107
+ f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken"
108
+ )
109
+
110
+ self.get_base_layer().weight = bnb.nn.Int8Params(
111
+ w_data.to("cpu"), requires_grad=False, has_fp16_weights=weight.has_fp16_weights
112
+ ).to(weight.device)
113
+
114
+ state.reset_grads()
115
+ self.merged_adapters.append(active_adapter)
116
+
117
+ def unmerge(self) -> None:
118
+ """
119
+ This method unmerges all merged adapter layers from the base weights.
120
+ """
121
+ if not self.merged:
122
+ warnings.warn("Already unmerged. Nothing to do.")
123
+ return
124
+
125
+ while len(self.merged_adapters) > 0:
126
+ active_adapter = self.merged_adapters.pop()
127
+ if active_adapter not in self.oft_R.keys():
128
+ continue
129
+ warnings.warn(
130
+ "Unmerge oft module to 8-bit linear may get different generations due to rounding errors."
131
+ )
132
+
133
+ weight = self.get_base_layer().weight
134
+ state = self.get_base_layer().state
135
+ if state.SCB is None:
136
+ state.SCB = weight.SCB
137
+ output = dequantize_bnb_weight(weight, state=state)
138
+
139
+ oft_data = self.get_delta_weight(active_adapter)
140
+
141
+ output = torch.transpose(output, 0, 1)
142
+ w_data = torch.mm(oft_data.t(), output.to(oft_data.dtype))
143
+ w_data = torch.transpose(w_data, 0, 1)
144
+ w_data = w_data.to(oft_data.dtype).to(oft_data.device)
145
+
146
+ self.get_base_layer().weight = bnb.nn.Int8Params(
147
+ w_data.to("cpu"), requires_grad=False, has_fp16_weights=weight.has_fp16_weights
148
+ ).to(weight.device)
149
+
150
+ state.reset_grads()
151
+
152
+ def get_delta_weight(self, adapter):
153
+ return self.oft_R[adapter].get_weight()
154
+
155
+ def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor:
156
+ if self.disable_adapters:
157
+ if self.merged:
158
+ self.unmerge()
159
+ result = self.base_layer(x, *args, **kwargs)
160
+ elif self.merged:
161
+ result = self.base_layer(x, *args, **kwargs)
162
+ else:
163
+ for active_adapter in self.active_adapters:
164
+ if active_adapter not in self.oft_R.keys():
165
+ continue
166
+ oft_R = self.oft_R[active_adapter]
167
+
168
+ requires_conversion = not torch.is_autocast_enabled()
169
+ if requires_conversion:
170
+ expected_dtype = x.dtype
171
+ x = self._cast_input_dtype(x, oft_R.weight.dtype)
172
+
173
+ x = oft_R(x)
174
+ if requires_conversion:
175
+ x = x.to(expected_dtype)
176
+
177
+ result = self.base_layer(x, *args, **kwargs)
178
+
179
+ return result
180
+
181
+ def __repr__(self) -> str:
182
+ rep = super().__repr__()
183
+ return "oft." + rep
184
+
185
+ def dispatch_bnb_8bit(target: torch.nn.Module, adapter_name: str, **kwargs):
186
+ new_module = None
187
+
188
+ if isinstance(target, BaseTunerLayer):
189
+ target_base_layer = target.get_base_layer()
190
+ else:
191
+ target_base_layer = target
192
+
193
+ loaded_in_8bit = kwargs.get("loaded_in_8bit", False)
194
+ if loaded_in_8bit and isinstance(target_base_layer, bnb.nn.Linear8bitLt):
195
+ eightbit_kwargs = kwargs.copy()
196
+ eightbit_kwargs.update(
197
+ {
198
+ "has_fp16_weights": target.state.has_fp16_weights,
199
+ "threshold": target.state.threshold,
200
+ "index": target.index,
201
+ }
202
+ )
203
+ new_module = Linear8bitLt(target, adapter_name, **eightbit_kwargs)
204
+
205
+ return new_module
206
+
207
+
208
+ if is_bnb_4bit_available():
209
+
210
+ class Linear4bit(torch.nn.Module, OFTLayer):
211
+ # OFT implemented in a dense layer
212
+ def __init__(
213
+ self,
214
+ base_layer: torch.nn.Module,
215
+ adapter_name: str,
216
+ r: int = 8,
217
+ oft_block_size: int = 0,
218
+ module_dropout: float = 0.0,
219
+ coft: bool = False,
220
+ eps: float = 6e-5,
221
+ block_share: bool = False,
222
+ init_weights: bool = True,
223
+ use_cayley_neumann: bool = False,
224
+ num_cayley_neumann_terms: int = 5,
225
+ **kwargs,
226
+ ) -> None:
227
+ super().__init__()
228
+ OFTLayer.__init__(self, base_layer)
229
+ self.fan_in_fan_out = False
230
+
231
+ self._active_adapter = adapter_name
232
+ self.update_layer(
233
+ adapter_name,
234
+ r,
235
+ oft_block_size=oft_block_size,
236
+ module_dropout=module_dropout,
237
+ coft=coft,
238
+ eps=eps,
239
+ block_share=block_share,
240
+ init_weights=init_weights,
241
+ use_cayley_neumann=use_cayley_neumann,
242
+ num_cayley_neumann_terms=num_cayley_neumann_terms,
243
+ )
244
+
245
+ def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None:
246
+ """
247
+ Merge the active adapter weights into the base weights
248
+
249
+ Args:
250
+ safe_merge (`bool`, *optional*):
251
+ If True, the merge operation will be performed in a copy of the original weights and check for NaNs
252
+ before merging the weights. This is useful if you want to check if the merge operation will produce
253
+ NaNs. Defaults to `False`.
254
+ adapter_names (`list[str]`, *optional*):
255
+ The list of adapter names that should be merged. If None, all active adapters will be merged.
256
+ Defaults to `None`.
257
+ """
258
+ adapter_names = check_adapters_to_merge(self, adapter_names)
259
+ if not adapter_names:
260
+ # no adapter to merge
261
+ return
262
+
263
+ for active_adapter in adapter_names:
264
+ if active_adapter not in self.oft_R.keys():
265
+ continue
266
+
267
+ warnings.warn("Merge oft module to 4-bit linear may get different generations due to rounding errors.")
268
+ # Refer to https://gist.github.com/ChrisHayduk/1a53463331f52dca205e55982baf9930
269
+ weight = self.get_base_layer().weight
270
+ kwargs = weight.__dict__
271
+
272
+ output = dequantize_bnb_weight(weight, state=weight.quant_state)
273
+
274
+ oft_data = self.get_delta_weight(active_adapter)
275
+ output = torch.transpose(output, 0, 1)
276
+ w_data = torch.mm(oft_data, output.to(oft_data.dtype))
277
+ w_data = torch.transpose(w_data, 0, 1)
278
+ w_data = output.to(oft_data.dtype).to(oft_data.device)
279
+
280
+ if safe_merge and not torch.isfinite(w_data).all():
281
+ raise ValueError(
282
+ f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken"
283
+ )
284
+
285
+ if "bnb_quantized" in kwargs:
286
+ kwargs["bnb_quantized"] = False
287
+ kwargs["requires_grad"] = False
288
+ kwargs.pop("data", None)
289
+ # torch.compile can introduce attributes preceded by '_', remove them
290
+ kwargs = {k: v for k, v in kwargs.items() if not k.startswith("_")}
291
+ self.get_base_layer().weight = bnb.nn.Params4bit(w_data.to("cpu"), **kwargs).to(weight.device)
292
+
293
+ self.merged_adapters.append(active_adapter)
294
+
295
+ def unmerge(self) -> None:
296
+ """
297
+ This method unmerges all merged adapter layers from the base weights.
298
+ """
299
+ if not self.merged:
300
+ warnings.warn("Already unmerged. Nothing to do.")
301
+ return
302
+
303
+ while len(self.merged_adapters) > 0:
304
+ active_adapter = self.merged_adapters.pop()
305
+ if active_adapter not in self.oft_R.keys():
306
+ continue
307
+ warnings.warn(
308
+ "Unmerge oft module to 4-bit linear may get different generations due to rounding errors."
309
+ )
310
+
311
+ weight = self.get_base_layer().weight
312
+ kwargs = weight.__dict__
313
+ output = dequantize_bnb_weight(weight, state=weight.quant_state)
314
+
315
+ oft_data = self.get_delta_weight(active_adapter)
316
+
317
+ output = torch.transpose(output, 0, 1)
318
+ w_data = torch.mm(oft_data.t(), output.to(oft_data.dtype))
319
+ w_data = torch.transpose(w_data, 0, 1)
320
+ w_data = output.to(oft_data.dtype).to(oft_data.device)
321
+
322
+ if "bnb_quantized" in kwargs:
323
+ kwargs["bnb_quantized"] = False
324
+ kwargs["requires_grad"] = False
325
+ kwargs.pop("data", None)
326
+ self.get_base_layer().weight = bnb.nn.Params4bit(w_data.to("cpu"), **kwargs).to(weight.device)
327
+
328
+ def get_delta_weight(self, adapter):
329
+ return self.oft_R[adapter].get_weight()
330
+
331
+ def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor:
332
+ if self.disable_adapters:
333
+ if self.merged:
334
+ self.unmerge()
335
+ result = self.base_layer(x, *args, **kwargs)
336
+ elif self.merged:
337
+ result = self.base_layer(x, *args, **kwargs)
338
+ else:
339
+ # As per Tim Dettmers, for 4bit, we need to defensively clone here.
340
+ # The reason is that in some cases, an error can occur that backprop
341
+ # does not work on a manipulated view. This issue may be solved with
342
+ # newer PyTorch versions but this would need extensive testing to be
343
+ # sure.
344
+ # result = result.clone()
345
+
346
+ for active_adapter in self.active_adapters:
347
+ if active_adapter not in self.oft_R.keys():
348
+ continue
349
+ oft_R = self.oft_R[active_adapter]
350
+
351
+ requires_conversion = not torch.is_autocast_enabled()
352
+ if requires_conversion:
353
+ expected_dtype = x.dtype
354
+ x = self._cast_input_dtype(x, oft_R.weight.dtype)
355
+
356
+ x = oft_R(x)
357
+ if requires_conversion:
358
+ x = x.to(expected_dtype)
359
+
360
+ result = self.base_layer(x, *args, **kwargs)
361
+
362
+ return result
363
+
364
+ def __repr__(self) -> str:
365
+ rep = super().__repr__()
366
+ return "oft." + rep
367
+
368
+ def dispatch_bnb_4bit(target: torch.nn.Module, adapter_name: str, **kwargs):
369
+ new_module = None
370
+
371
+ if isinstance(target, BaseTunerLayer):
372
+ target_base_layer = target.get_base_layer()
373
+ else:
374
+ target_base_layer = target
375
+
376
+ loaded_in_4bit = kwargs.get("loaded_in_4bit", False)
377
+ if loaded_in_4bit and is_bnb_4bit_available() and isinstance(target_base_layer, bnb.nn.Linear4bit):
378
+ fourbit_kwargs = kwargs.copy()
379
+ fourbit_kwargs.update(
380
+ {
381
+ "compute_dtype": target_base_layer.compute_dtype,
382
+ "compress_statistics": target_base_layer.weight.compress_statistics,
383
+ "quant_type": target_base_layer.weight.quant_type,
384
+ }
385
+ )
386
+ new_module = Linear4bit(target, adapter_name, **fourbit_kwargs)
387
+
388
+ return new_module
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/config.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ import warnings
18
+ from dataclasses import dataclass, field
19
+ from typing import Literal, Optional, Union
20
+
21
+ import packaging.version
22
+
23
+ from peft.config import PeftConfig
24
+ from peft.utils import PeftType
25
+
26
+
27
+ @dataclass
28
+ class OFTConfig(PeftConfig):
29
+ """
30
+ This is the configuration class to store the configuration of a [`OFTModel`].
31
+
32
+ Args:
33
+ r (`int`): OFT rank, number of OFT blocks per injected layer.
34
+ oft_block_size (`int`): OFT block size across different layers.
35
+ module_dropout (`float`):
36
+ The multiplicative dropout probability, by setting OFT blocks to identity during training, similar to the
37
+ dropout layer in LoRA.
38
+ target_modules (`Optional[Union[list[str], str]]`):
39
+ The names of the modules to apply the adapter to. If this is specified, only the modules with the specified
40
+ names will be replaced. When passing a string, a regex match will be performed. When passing a list of
41
+ strings, either an exact match will be performed or it is checked if the name of the module ends with any
42
+ of the passed strings. If this is specified as 'all-linear', then all linear modules are chosen, excluding
43
+ the output layer. If this is not specified, modules will be chosen according to the model architecture. If
44
+ the architecture is not known, an error will be raised -- in this case, you should specify the target
45
+ modules manually.
46
+ fan_in_fan_out (`bool`): Set this to True if the layer to replace stores weight like (fan_in, fan_out).
47
+ bias (`str`): Bias type for OFT. Can be 'none', 'all' or 'oft_only'. If 'all' or 'oft_only', the
48
+ corresponding biases will be updated during training. Be aware that this means that, even when disabling
49
+ the adapters, the model will not produce the same output as the base model would have without adaptation.
50
+ exclude_modules (`Optional[Union[List[str], str]]`):
51
+ The names of the modules to not apply the adapter. When passing a string, a regex match will be performed.
52
+ When passing a list of strings, either an exact match will be performed or it is checked if the name of the
53
+ module ends with any of the passed strings.
54
+ init_weights (`bool`):
55
+ Whether to perform initialization of OFT weights.
56
+ layers_to_transform (`Union[List[int], int]`):
57
+ The layer indices to transform. If a list of ints is passed, it will apply the adapter to the layer indices
58
+ that are specified in this list. If a single integer is passed, it will apply the transformations on the
59
+ layer at this index.
60
+ layers_pattern (`Optional[Union[List[str], str]]`):
61
+ The layer pattern name, used only if `layers_to_transform` is different from `None`. This should target the
62
+ `nn.ModuleList` of the model, which is often called `'layers'` or `'h'`.
63
+ modules_to_save (`List[str]`):
64
+ List of modules apart from adapter layers to be set as trainable and saved in the final checkpoint.
65
+ coft (`bool`):
66
+ Whether to use the constrained variant of OFT or not, off by default.
67
+ eps (`float`):
68
+ The control strength of COFT. The freedom of rotation. Only has an effect if `coft` is set to True.
69
+ block_share (`bool`):
70
+ Whether to share the OFT parameters between blocks or not. This is `False` by default.
71
+ """
72
+
73
+ r: int = field(default=0, metadata={"help": "OFT rank, number of OFT blocks per injected layer."})
74
+ oft_block_size: int = field(
75
+ default=32,
76
+ metadata={
77
+ "help": "OFT block size across different layers.",
78
+ "note": "You can only specify either r or oft_block_size, but not both simultaneously, because r x oft_block_size = layer dimension.",
79
+ },
80
+ )
81
+ module_dropout: float = field(
82
+ default=0.0,
83
+ metadata={
84
+ "help": "OFT multiplicative dropout, randomly setting blocks of OFT to be identity matrix, similar to the dropout layer in LoRA."
85
+ },
86
+ )
87
+ target_modules: Optional[Union[list[str], str]] = field(
88
+ default=None,
89
+ metadata={
90
+ "help": "List of module names or regex expression of the module names to replace with OFT."
91
+ "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$' "
92
+ "This can also be a wildcard 'all-linear' which matches all linear/Conv1D layers except the output layer."
93
+ },
94
+ )
95
+ fan_in_fan_out: bool = field(
96
+ default=False,
97
+ metadata={"help": "Set this to True if the layer to replace stores weight like (fan_in, fan_out)"},
98
+ )
99
+ bias: Literal["none", "all", "oft_only"] = field(
100
+ default="none", metadata={"help": "Bias type for OFT. Can be 'none', 'all' or 'oft_only'"}
101
+ )
102
+ exclude_modules: Optional[Union[list[str], str]] = field(
103
+ default=None,
104
+ metadata={"help": "List of module names or regex expression of the module names to exclude from OFT."},
105
+ )
106
+ init_weights: bool = field(
107
+ default=True,
108
+ metadata={
109
+ "help": (
110
+ "Whether to initialize the weights of the OFT layers with their default initialization. Don't change "
111
+ "this setting, except if you know exactly what you're doing."
112
+ ),
113
+ },
114
+ )
115
+ layers_to_transform: Optional[Union[list[int], int]] = field(
116
+ default=None,
117
+ metadata={
118
+ "help": "The layer indexes to transform, is this argument is specified, PEFT will transform only the layers indexes that are specified inside this list. If a single integer is passed, PEFT will transform only the layer at this index."
119
+ },
120
+ )
121
+ layers_pattern: Optional[Union[list[str], str]] = field(
122
+ default=None,
123
+ metadata={
124
+ "help": "The layer pattern name, used only if `layers_to_transform` is different to None and if the layer pattern is not in the common layers pattern. "
125
+ "This should target the `nn.ModuleList` of the model, which is often called `'layers'` or `'h'`."
126
+ },
127
+ )
128
+ modules_to_save: Optional[list[str]] = field(
129
+ default=None,
130
+ metadata={
131
+ "help": "List of modules apart from OFT layers to be set as trainable and saved in the final checkpoint. "
132
+ "For example, in Sequence Classification or Token Classification tasks, "
133
+ "the final layer `classifier/score` are randomly initialized and as such need to be trainable and saved."
134
+ },
135
+ )
136
+ coft: bool = field(
137
+ default=False,
138
+ metadata={"help": "Whether to use the constrained variant of OFT or not."},
139
+ )
140
+ eps: float = field(
141
+ default=6e-5,
142
+ metadata={
143
+ "help": "The control strength of COFT. The freedom of rotation. Only has an effect if `coft` is set to True."
144
+ },
145
+ )
146
+ block_share: bool = field(
147
+ default=False,
148
+ metadata={"help": "Whether to share the OFT parameters between blocks or not."},
149
+ )
150
+ use_cayley_neumann: bool = field(
151
+ default=True,
152
+ metadata={
153
+ "help": "Whether to use the Cayley-Neumann Formulation of OFT or not. Set to True to improve computational efficiency but comes at costs of bigger approximation error for orthogonality."
154
+ },
155
+ )
156
+ num_cayley_neumann_terms: int = field(
157
+ default=5,
158
+ metadata={
159
+ "help": "Number of Cayley-Neumann terms to use. Higher number results in less approximation error for orthogonality."
160
+ },
161
+ )
162
+
163
+ def __post_init__(self):
164
+ super().__post_init__()
165
+ self.peft_type = PeftType.OFT
166
+ self.target_modules = (
167
+ set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules
168
+ )
169
+ self.exclude_modules = (
170
+ set(self.exclude_modules) if isinstance(self.exclude_modules, list) else self.exclude_modules
171
+ )
172
+ # check for layers_to_transform and layers_pattern
173
+ if self.layers_pattern and not self.layers_to_transform:
174
+ raise ValueError("When `layers_pattern` is specified, `layers_to_transform` must also be specified. ")
175
+ if self.r == 0 and self.oft_block_size == 0:
176
+ raise ValueError(
177
+ f"Either `r` or `oft_block_size` must be non-zero. Currently, r = {self.r} and oft_block_size = {self.oft_block_size}."
178
+ )
179
+ if not (self.r != 0) ^ (self.oft_block_size != 0):
180
+ raise ValueError(
181
+ f"You can only specify either r ({self.r}) or oft_block_size ({self.oft_block_size}), but not both simultaneously, because r x oft_block_size == in_features."
182
+ )
183
+
184
+ @classmethod
185
+ def check_kwargs(cls, **kwargs):
186
+ r"""
187
+ Check if the kwargs are valid for the configuration.
188
+
189
+ Args:
190
+ kwargs (additional keyword arguments, *optional*):
191
+ Additional keyword arguments passed along to the child class initialization.
192
+ """
193
+ if "oft_block_size" not in kwargs:
194
+ raise ValueError(
195
+ "OFT has been updated since PEFT 0.14.0. Your trained adapter weights are incompatible "
196
+ "with the latest version of OFT. Please retrain your adapter weights with newer PEFT versions. "
197
+ "Alternatively, downgrade PEFT to version 0.13.0 to use the old adapter weights."
198
+ )
199
+ if kwargs.get("use_cayley_neumann", False):
200
+ peft_version = kwargs.get("peft_version", "0.0.0") # if not present, set a low dummy version
201
+ # remove commit hash, if present
202
+ peft_version = peft_version.partition("@")[0]
203
+ parsed_version = packaging.version.Version(peft_version)
204
+ min_version = packaging.version.Version("0.18.0")
205
+ # note: config.peft_version was added in 0.18.0, so if it's missing, it means we're below min version
206
+ if parsed_version < min_version:
207
+ msg = (
208
+ "The cayley-neumann parameterization has been slightly changed to be more numerically stable in "
209
+ "PEFT 0.18.0. Please retrain your adapter weights with newer PEFT versions. Alternatively, "
210
+ "downgrade PEFT to version 0.17.0 to use the old parameterization."
211
+ )
212
+ warnings.warn(msg)
213
+ return super().check_kwargs(**kwargs)
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/eetq.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import Any, Optional
15
+
16
+ import torch
17
+
18
+ from peft.import_utils import is_eetq_available
19
+ from peft.tuners.oft.layer import OFTLayer
20
+ from peft.tuners.tuners_utils import BaseTunerLayer
21
+
22
+
23
+ if is_eetq_available():
24
+ from eetq import EetqLinear
25
+
26
+ class EetqOFTLinear(torch.nn.Module, OFTLayer):
27
+ def __init__(
28
+ self,
29
+ base_layer,
30
+ adapter_name,
31
+ r: int = 0,
32
+ oft_block_size: int = 0,
33
+ module_dropout: float = 0.0,
34
+ init_weights: bool = True,
35
+ coft: bool = False,
36
+ eps: float = 6e-5,
37
+ block_share: bool = False,
38
+ use_cayley_neumann: bool = False,
39
+ num_cayley_neumann_terms: int = 5,
40
+ fan_in_fan_out: bool = False,
41
+ **kwargs,
42
+ ):
43
+ super().__init__()
44
+ OFTLayer.__init__(self, base_layer)
45
+
46
+ # self.base_layer and self.quant_linear_module are the same; we need the former for consistency and the latter
47
+ # for backwards compatibility
48
+ self.quant_linear_module = base_layer
49
+
50
+ self._active_adapter = adapter_name
51
+ self.update_layer(
52
+ adapter_name,
53
+ r,
54
+ oft_block_size=oft_block_size,
55
+ module_dropout=module_dropout,
56
+ init_weights=init_weights,
57
+ coft=coft,
58
+ eps=eps,
59
+ block_share=block_share,
60
+ fan_in_fan_out=fan_in_fan_out,
61
+ use_cayley_neumann=use_cayley_neumann,
62
+ num_cayley_neumann_terms=num_cayley_neumann_terms,
63
+ )
64
+
65
+ def forward(self, x: torch.Tensor):
66
+ if self.disable_adapters:
67
+ return self.quant_linear_module(x)
68
+
69
+ for active_adapter in self.active_adapters:
70
+ if active_adapter not in self.oft_R.keys():
71
+ continue
72
+ oft_R = self.oft_R[active_adapter]
73
+
74
+ requires_conversion = not torch.is_autocast_enabled()
75
+ if requires_conversion:
76
+ expected_dtype = x.dtype
77
+ x = self._cast_input_dtype(x, oft_R.weight.dtype)
78
+
79
+ x = oft_R(x)
80
+
81
+ result = self.quant_linear_module(x)
82
+ if requires_conversion:
83
+ result = result.to(expected_dtype)
84
+ return result
85
+
86
+ def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None:
87
+ raise AttributeError("Merging LoRA layers is not supported for Eetq layers.")
88
+
89
+ def unmerge(self) -> None:
90
+ raise AttributeError("Unmerging LoRA layers is not supported for Eetq layers.")
91
+
92
+ def __repr__(self) -> str:
93
+ rep = super().__repr__()
94
+ return "oft." + rep
95
+
96
+
97
+ def dispatch_eetq(
98
+ target: torch.nn.Module,
99
+ adapter_name: str,
100
+ **kwargs: Any,
101
+ ) -> Optional[torch.nn.Module]:
102
+ new_module = None
103
+
104
+ if isinstance(target, BaseTunerLayer):
105
+ target_base_layer = target.get_base_layer()
106
+ else:
107
+ target_base_layer = target
108
+
109
+ if is_eetq_available() and isinstance(target_base_layer, EetqLinear):
110
+ new_module = EetqOFTLinear(target, adapter_name, **kwargs)
111
+ target.weight = target_base_layer.weight
112
+
113
+ if hasattr(target, "bias"):
114
+ target.bias = target_base_layer.bias
115
+
116
+ return new_module
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/gptq.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import Any, Optional
15
+
16
+ import torch
17
+
18
+ from peft.import_utils import is_gptqmodel_available
19
+ from peft.tuners.oft.layer import OFTLayer
20
+ from peft.tuners.tuners_utils import BaseTunerLayer
21
+
22
+
23
+ class GPTQOFTLinear(torch.nn.Module, OFTLayer):
24
+ def __init__(
25
+ self,
26
+ base_layer,
27
+ adapter_name: str,
28
+ r: int = 8,
29
+ oft_block_size: int = 0,
30
+ module_dropout: float = 0.0,
31
+ coft: bool = False,
32
+ eps: float = 6e-5,
33
+ block_share: bool = False,
34
+ use_cayley_neumann: bool = False,
35
+ num_cayley_neumann_terms: int = 5,
36
+ fan_in_fan_out: bool = False, # Set this to True if the layer to replace stores weight like (fan_in, fan_out)
37
+ init_weights: bool = True,
38
+ **kwargs,
39
+ ):
40
+ super().__init__()
41
+ OFTLayer.__init__(self, base_layer)
42
+
43
+ # self.base_layer and self.quant_linear_module are the same; we need the former for consistency and the latter
44
+ # for backwards compatibility
45
+ self.quant_linear_module = base_layer
46
+ self._active_adapter = adapter_name
47
+ self.update_layer(
48
+ adapter_name,
49
+ r,
50
+ oft_block_size=oft_block_size,
51
+ module_dropout=module_dropout,
52
+ coft=coft,
53
+ eps=eps,
54
+ block_share=block_share,
55
+ init_weights=init_weights,
56
+ use_cayley_neumann=use_cayley_neumann,
57
+ num_cayley_neumann_terms=num_cayley_neumann_terms,
58
+ )
59
+
60
+ def forward(self, x: torch.Tensor):
61
+ # note: logic differs from default Linear because merging is not supported
62
+ if self.disable_adapters:
63
+ return self.quant_linear_module(x)
64
+
65
+ for active_adapter in self.active_adapters:
66
+ if active_adapter not in self.oft_R.keys():
67
+ continue
68
+
69
+ oft_R = self.oft_R[active_adapter]
70
+ requires_conversion = not torch.is_autocast_enabled()
71
+ if requires_conversion:
72
+ expected_dtype = x.dtype
73
+ x = self._cast_input_dtype(x, oft_R.weight.dtype)
74
+
75
+ x = oft_R(x)
76
+ if requires_conversion:
77
+ x = x.to(expected_dtype)
78
+
79
+ result = self.quant_linear_module(x)
80
+ return result
81
+
82
+ def __repr__(self) -> str:
83
+ rep = super().__repr__()
84
+ return "oft." + rep
85
+
86
+
87
+ def dispatch_gptq(
88
+ target: torch.nn.Module,
89
+ adapter_name: str,
90
+ **kwargs: Any,
91
+ ) -> Optional[torch.nn.Module]:
92
+ new_module = None
93
+
94
+ if isinstance(target, BaseTunerLayer):
95
+ target_base_layer = target.get_base_layer()
96
+ else:
97
+ target_base_layer = target
98
+
99
+ if is_gptqmodel_available():
100
+ from gptqmodel.nn_modules.qlinear import BaseQuantLinear
101
+
102
+ if isinstance(target_base_layer, BaseQuantLinear):
103
+ new_module = GPTQOFTLinear(target, adapter_name, **kwargs)
104
+ target.qweight = target_base_layer.qweight
105
+
106
+ return new_module
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/hqq.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from __future__ import annotations
15
+
16
+ import copy
17
+ import warnings
18
+ from typing import Optional
19
+
20
+ import torch
21
+
22
+ from peft.import_utils import is_hqq_available
23
+ from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge
24
+
25
+ from .layer import OFTLayer
26
+
27
+
28
+ if is_hqq_available():
29
+ from hqq.core.quantize import HQQLinear
30
+
31
+ class HqqOFTLinear(torch.nn.Module, OFTLayer):
32
+ # Lora implemented in a dense layer
33
+ def __init__(
34
+ self,
35
+ base_layer: torch.nn.Module,
36
+ adapter_name: str,
37
+ r: int = 8,
38
+ oft_block_size: int = 0,
39
+ module_dropout: float = 0.0,
40
+ init_weights: bool = True,
41
+ coft: bool = False,
42
+ eps: float = 6e-5,
43
+ block_share: bool = False,
44
+ use_cayley_neumann: bool = False,
45
+ num_cayley_neumann_terms: int = 5,
46
+ **kwargs,
47
+ ) -> None:
48
+ super().__init__()
49
+ OFTLayer.__init__(self, base_layer)
50
+ self.fan_in_fan_out = False
51
+
52
+ self._active_adapter = adapter_name
53
+ self.update_layer(
54
+ adapter_name,
55
+ r,
56
+ oft_block_size=oft_block_size,
57
+ module_dropout=module_dropout,
58
+ init_weights=init_weights,
59
+ coft=coft,
60
+ eps=eps,
61
+ block_share=block_share,
62
+ use_cayley_neumann=use_cayley_neumann,
63
+ num_cayley_neumann_terms=num_cayley_neumann_terms,
64
+ )
65
+
66
+ def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None:
67
+ """
68
+ Merge the active adapter weights into the base weights
69
+
70
+ Args:
71
+ safe_merge (`bool`, *optional*):
72
+ If True, the merge operation will be performed in a copy of the original weights and check for NaNs
73
+ before merging the weights. This is useful if you want to check if the merge operation will produce
74
+ NaNs. Defaults to `False`.
75
+ adapter_names (`list[str]`, *optional*):
76
+ The list of adapter names that should be merged. If None, all active adapters will be merged.
77
+ Defaults to `None`.
78
+ """
79
+ adapter_names = check_adapters_to_merge(self, adapter_names)
80
+ if not adapter_names:
81
+ # no adapter to merge
82
+ return
83
+
84
+ for active_adapter in adapter_names:
85
+ if active_adapter not in self.lora_A.keys():
86
+ continue
87
+
88
+ layer = self.get_base_layer()
89
+ quant_config = {**copy.deepcopy(layer.quant_config), "offload_meta": layer.offload_meta}
90
+
91
+ output = layer.dequantize()
92
+ oft_data = self.get_delta_weight(active_adapter)
93
+
94
+ output = torch.transpose(output, 0, 1)
95
+ w_data = torch.mm(oft_data, output.to(oft_data.dtype))
96
+ w_data = torch.transpose(w_data, 0, 1)
97
+ w_data = output.to(oft_data.dtype).to(oft_data.device)
98
+
99
+ if safe_merge and not torch.isfinite(w_data).all():
100
+ raise ValueError(
101
+ f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken"
102
+ )
103
+
104
+ new_hqq_layer = HQQLinear(None, quant_config, compute_dtype=layer.compute_dtype, device=layer.device)
105
+ quant_config.pop("offload_meta", None)
106
+ new_hqq_layer.quantize(w_data, **quant_config)
107
+ self.base_layer = new_hqq_layer
108
+ self.merged_adapters.append(active_adapter)
109
+
110
+ def unmerge(self) -> None:
111
+ """
112
+ This method unmerges all merged adapter layers from the base weights.
113
+ """
114
+ if not self.merged:
115
+ warnings.warn("Already unmerged. Nothing to do.")
116
+ return
117
+
118
+ while len(self.merged_adapters) > 0:
119
+ active_adapter = self.merged_adapters.pop()
120
+ if active_adapter not in self.oft_R.keys():
121
+ continue
122
+
123
+ layer = self.get_base_layer()
124
+ quant_config = {**copy.deepcopy(layer.quant_config), "offload_meta": layer.offload_meta}
125
+ output = layer.dequantize()
126
+
127
+ oft_data = self.get_delta_weight(active_adapter)
128
+
129
+ output = torch.transpose(output, 0, 1)
130
+ w_data = torch.mm(oft_data.t(), output.to(oft_data.dtype))
131
+ w_data = torch.transpose(w_data, 0, 1)
132
+ w_data = w_data.to(oft_data.dtype).to(oft_data.device)
133
+
134
+ new_hqq_layer = HQQLinear(None, quant_config, compute_dtype=layer.compute_dtype, device=layer.device)
135
+ quant_config.pop("offload_meta", None)
136
+ new_hqq_layer.quantize(w_data, **quant_config)
137
+ self.base_layer = new_hqq_layer
138
+
139
+ def get_delta_weight(self, adapter):
140
+ return self.oft_R[adapter].get_weight()
141
+
142
+ def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor:
143
+ self._check_forward_args(x, *args, **kwargs)
144
+ adapter_names = kwargs.pop("adapter_names", None)
145
+
146
+ if self.disable_adapters:
147
+ if self.merged:
148
+ self.unmerge()
149
+ result = self.base_layer(x, *args, **kwargs)
150
+ elif self.merged:
151
+ result = self.base_layer(x, *args, **kwargs)
152
+ else:
153
+ for active_adapter in self.active_adapters:
154
+ if active_adapter not in self.oft_R.keys():
155
+ continue
156
+ oft_R = self.oft_R[active_adapter]
157
+
158
+ requires_conversion = not torch.is_autocast_enabled()
159
+ if requires_conversion:
160
+ expected_dtype = x.dtype
161
+ x = self._cast_input_dtype(x, oft_R.weight.dtype)
162
+
163
+ x = oft_R(x)
164
+
165
+ result = self.base_layer(x, *args, **kwargs)
166
+ if requires_conversion:
167
+ result = result.to(expected_dtype)
168
+ return result
169
+
170
+ def __repr__(self) -> str:
171
+ rep = super().__repr__()
172
+ return "oft." + rep
173
+
174
+
175
+ def dispatch_hqq(target: torch.nn.Module, adapter_name: str, **kwargs):
176
+ new_module = None
177
+
178
+ if isinstance(target, BaseTunerLayer):
179
+ target_base_layer = target.get_base_layer()
180
+ else:
181
+ target_base_layer = target
182
+
183
+ if is_hqq_available() and isinstance(target_base_layer, HQQLinear):
184
+ new_module = HqqOFTLinear(target_base_layer, adapter_name, **kwargs)
185
+
186
+ return new_module
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/inc.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # NOTE: PEFT tests related to INC are handled under Optimum-Habana repository:
16
+ # - LLMs: https://github.com/huggingface/optimum-habana/blob/main/tests/test_peft_inference.py
17
+ # - Diffusers: https://github.com/huggingface/optimum-habana/blob/main/tests/test_diffusers.py
18
+
19
+ from typing import Optional
20
+
21
+ import torch
22
+
23
+ from peft.import_utils import is_inc_available
24
+ from peft.tuners.tuners_utils import BaseTunerLayer
25
+
26
+ from .layer import Linear
27
+
28
+
29
+ if is_inc_available():
30
+
31
+ class IncOFTLinear(Linear):
32
+ def __init__(
33
+ self,
34
+ base_layer: torch.nn.Module,
35
+ adapter_name: str,
36
+ **kwargs,
37
+ ):
38
+ super().__init__(base_layer, adapter_name, **kwargs)
39
+
40
+ def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None:
41
+ """
42
+ Merge the active adapter weights into the base weights
43
+
44
+ Args:
45
+ safe_merge (`bool`, *optional*):
46
+ If True, the merge operation will be performed in a copy of the original weights and check for NaNs
47
+ before merging the weights. This is useful if you want to check if the merge operation will produce
48
+ NaNs. Defaults to `False`.
49
+ adapter_names (`list[str]`, *optional*):
50
+ The list of adapter names that should be merged. If None, all active adapters will be merged.
51
+ Defaults to `None`.
52
+ """
53
+ raise NotImplementedError("Merging OFT with INC layers is not yet implemented")
54
+
55
+ def unmerge(self) -> None:
56
+ """
57
+ This method unmerges all merged adapter layers from the base weights.
58
+ """
59
+ raise NotImplementedError("Unmerging OFT from INC layers is not yet implemented")
60
+
61
+
62
+ def dispatch_inc(target: torch.nn.Module, adapter_name: str, **kwargs):
63
+ new_module = None
64
+
65
+ if isinstance(target, BaseTunerLayer):
66
+ target_base_layer = target.get_base_layer()
67
+ else:
68
+ target_base_layer = target
69
+
70
+ if is_inc_available():
71
+ from neural_compressor.torch.algorithms.fp8_quant._quant_common.helper_modules import (
72
+ PatchedLinear,
73
+ )
74
+
75
+ if isinstance(target_base_layer, PatchedLinear):
76
+ new_module = IncOFTLinear(target, adapter_name, **kwargs)
77
+
78
+ return new_module
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/layer.py ADDED
@@ -0,0 +1,1229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from __future__ import annotations
15
+
16
+ import warnings
17
+ from typing import Any, Optional, Union
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+ import torch.nn.functional as F
22
+
23
+ from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge
24
+
25
+ from .config import OFTConfig
26
+
27
+
28
+ class MultiplicativeDropoutLayer(nn.Module):
29
+ """
30
+ Implements the multiplicative dropout layer for OFT.
31
+ """
32
+
33
+ def __init__(self, p=0.0):
34
+ """
35
+ Initializes the multiplicative dropout layer.
36
+
37
+ Parameters:
38
+ p (float): The probability of dropping out a block. Defaults to 0.0.
39
+ """
40
+ super().__init__()
41
+ self.p = p
42
+
43
+ def forward(self, x):
44
+ """
45
+ Applies multiplicative dropout to the input tensor.
46
+
47
+ Parameters:
48
+ x (Tensor): The input tensor of shape (D, H, H), where `D` represents
49
+ the number of OFT blocks, and `H` is the size of the square blocks along the last two dimensions,
50
+ the block size in OFT.
51
+ """
52
+ if self.training and self.p > 0:
53
+ # Ensure the last two dimensions are the same
54
+ if x.shape[-1] != x.shape[-2]:
55
+ raise ValueError("The last two dimensions of input should be the same!")
56
+
57
+ D, H, _ = x.shape
58
+
59
+ # If block share, skip the multiplicative dropout
60
+ if D == 1:
61
+ return x
62
+
63
+ num_to_replace = int(self.p * D)
64
+ num_zeros = D - num_to_replace
65
+ mask = torch.cat([torch.ones(num_to_replace, device=x.device), torch.zeros(num_zeros, device=x.device)])
66
+ mask = mask[torch.randperm(D)].view(D, 1, 1)
67
+ eye_matrix = torch.eye(H, device=x.device).repeat(D, 1, 1)
68
+ x = (1 - mask) * x + mask * eye_matrix
69
+ return x
70
+
71
+
72
+ class OFTRotationModule(nn.Module):
73
+ def __init__(
74
+ self,
75
+ r,
76
+ n_elements,
77
+ block_size,
78
+ in_features,
79
+ coft=False,
80
+ eps=6e-5,
81
+ block_share=False,
82
+ kernel_size=(0, 0),
83
+ use_cayley_neumann=True,
84
+ num_cayley_neumann_terms=5,
85
+ ):
86
+ super().__init__()
87
+ self.r = r
88
+ self.n_elements = n_elements
89
+ self.block_size = block_size
90
+ self.in_features = in_features
91
+ self.weight = nn.Parameter(torch.empty(r, n_elements))
92
+ self.coft = coft
93
+ self.eps = eps
94
+ self.block_share = block_share
95
+ # Conv2d specific parameters
96
+ self.kernel_size = kernel_size
97
+ self.use_cayley_neumann = use_cayley_neumann
98
+ self.num_cayley_neumann_terms = num_cayley_neumann_terms
99
+ # Create indices for upper triangle (excluding diagonal)
100
+ rows, cols = torch.triu_indices(block_size, block_size, 1)
101
+ self.register_buffer("rows", rows, persistent=False)
102
+ self.register_buffer("cols", cols, persistent=False)
103
+
104
+ def _pytorch_skew_symmetric(self, vec, block_size):
105
+ batch_size = vec.shape[0]
106
+ matrix = torch.zeros(batch_size, block_size, block_size, device=vec.device, dtype=vec.dtype)
107
+
108
+ matrix[:, self.rows, self.cols] = vec
109
+ matrix = matrix - matrix.transpose(-2, -1)
110
+ return matrix
111
+
112
+ def _pytorch_skew_symmetric_inv(self, matrix, block_size):
113
+ batch_size = matrix.shape[0]
114
+
115
+ # Extract the upper triangular elements
116
+ vec = matrix[:, self.rows, self.cols]
117
+ return vec
118
+
119
+ def _cayley_batch(
120
+ self, Q: torch.Tensor, block_size: int, use_cayley_neumann: bool = True, num_neumann_terms: int = 5
121
+ ) -> torch.Tensor:
122
+ """
123
+ Perform the Cayley parametrization on a batch of skew-symmetric matrices.
124
+
125
+ Args:
126
+ data: A batch of skew-symmetric matrices of shape (b, r, c).
127
+ """
128
+
129
+ b, _ = Q.shape
130
+ previous_dtype = Q.dtype
131
+
132
+ # Q_skew = SkewSymmetric.apply(Q, block_size)
133
+ Q_skew = self._pytorch_skew_symmetric(Q, block_size)
134
+
135
+ if use_cayley_neumann:
136
+ R = torch.eye(block_size, device=Q.device, dtype=Q.dtype).repeat(b, 1, 1)
137
+ if num_neumann_terms > 1:
138
+ R.add_(Q_skew, alpha=2.0)
139
+ if num_neumann_terms > 2:
140
+ Q_squared = torch.bmm(Q_skew, Q_skew)
141
+ R.add_(Q_squared, alpha=2.0)
142
+
143
+ Q_power = Q_squared
144
+ for _ in range(3, num_neumann_terms - 1):
145
+ Q_power = torch.bmm(Q_power, Q_skew)
146
+ R.add_(Q_power, alpha=2.0)
147
+ Q_power = torch.bmm(Q_power, Q_skew)
148
+ R.add_(Q_power)
149
+ else:
150
+ id_mat = (
151
+ torch.eye(Q_skew.shape[-1], device=Q_skew.device)
152
+ .unsqueeze(0)
153
+ .expand(b, Q_skew.shape[-1], Q_skew.shape[-1])
154
+ )
155
+ R = torch.linalg.solve(id_mat + Q_skew, id_mat - Q_skew, left=False)
156
+
157
+ return R.to(previous_dtype)
158
+
159
+ # Copied from https://github.com/Zeju1997/oft/blob/84cebb965df69781e3d9c3c875f5980b421eaf24/oft-control/oft.py#L52
160
+ def _project_batch(self, Q, eps=1e-5):
161
+ oft_R = self._pytorch_skew_symmetric(Q, self.block_size)
162
+ # scaling factor for each of the smaller block matrix
163
+ eps = eps * 1 / torch.sqrt(torch.tensor(oft_R.shape[0]))
164
+ I = ( # noqa: E741
165
+ torch.zeros((oft_R.size(1), oft_R.size(1)), device=oft_R.device, dtype=oft_R.dtype)
166
+ .unsqueeze(0)
167
+ .expand_as(oft_R)
168
+ )
169
+ diff = oft_R - I
170
+ norm_diff = torch.norm(oft_R - I, dim=(1, 2), keepdim=True)
171
+ mask = (norm_diff <= eps).bool()
172
+ out = torch.where(mask, oft_R, I + eps * (diff / norm_diff))
173
+
174
+ return self._pytorch_skew_symmetric_inv(out, self.block_size)
175
+
176
+ # Copied from https://github.com/Zeju1997/oft/blob/84cebb965df69781e3d9c3c875f5980b421eaf24/oft-control/oft.py#L155
177
+ def _block_diagonal(self, oft_R: torch.Tensor, rank: int) -> torch.Tensor:
178
+ if oft_R.shape[0] == 1:
179
+ # block share
180
+ blocks = [oft_R[0, ...] for i in range(rank)]
181
+ else:
182
+ blocks = [oft_R[i, ...] for i in range(rank)]
183
+
184
+ # Use torch.block_diag to create the block diagonal matrix
185
+ A = torch.block_diag(*blocks)
186
+
187
+ return A
188
+
189
+ def _unfold(self, x):
190
+ """
191
+ Unfold with stride=1, padding=0 to preserve spatial dimensions. Only use kernel_size from base layer to define
192
+ patch size.
193
+ """
194
+ batch_size, in_channels, in_height, in_width = x.shape
195
+
196
+ if isinstance(self.kernel_size, int):
197
+ kernel_height, kernel_width = self.kernel_size, self.kernel_size
198
+ else:
199
+ kernel_height, kernel_width = self.kernel_size
200
+
201
+ stride_h = stride_w = 1
202
+ pad_h = pad_w = 0
203
+
204
+ # output dimensions
205
+ out_height = (in_height + 2 * pad_h - kernel_height) // stride_h + 1
206
+ out_width = (in_width + 2 * pad_w - kernel_width) // stride_w + 1
207
+
208
+ # Reshape input from [B, C, H, W] to [B, C, H_out, W_out, K_H, K_W]
209
+ x_unfolded = x.unfold(2, kernel_height, stride_h).unfold(3, kernel_width, stride_w)
210
+ x_unfolded = x_unfolded.permute(0, 2, 3, 1, 4, 5).contiguous()
211
+ x_unfolded = x_unfolded.view(batch_size * out_height * out_width, -1)
212
+
213
+ return x_unfolded
214
+
215
+ def _fold(self, x_unfolded, orig_shape):
216
+ """
217
+ Fold back to preserve spatial dimensions.
218
+ """
219
+ batch_size, in_channels, in_height, in_width = orig_shape
220
+
221
+ if isinstance(self.kernel_size, int):
222
+ kernel_height, kernel_width = self.kernel_size, self.kernel_size
223
+ else:
224
+ kernel_height, kernel_width = self.kernel_size
225
+
226
+ # With stride=1, padding=0:
227
+ out_height = in_height - kernel_height + 1
228
+ out_width = in_width - kernel_width + 1
229
+
230
+ # Reshape: [B*H_out*W_out, C*K_H*K_W] -> [B, H_out, W_out, C, K_H, K_W]
231
+ x_reshaped = x_unfolded.view(batch_size, out_height, out_width, in_channels, kernel_height, kernel_width)
232
+
233
+ # Permute to: [B, C, H_out, W_out, K_H, K_W]
234
+ x_reshaped = x_reshaped.permute(0, 3, 1, 2, 4, 5).contiguous()
235
+
236
+ # Use F.fold to reconstruct 4D tensor
237
+ x_folded = F.fold(
238
+ x_reshaped.view(batch_size, in_channels * kernel_height * kernel_width, out_height * out_width),
239
+ output_size=(in_height, in_width),
240
+ kernel_size=(kernel_height, kernel_width),
241
+ stride=(1, 1),
242
+ )
243
+
244
+ return x_folded
245
+
246
+ def forward(self, x):
247
+ # This module doesn't need to implement the orthogonal transform
248
+ # It's primarily a container for the parameter
249
+ # The actual transformation logic stays in your OFTLayer
250
+
251
+ required_dtype = x.dtype
252
+ if required_dtype != self.weight.dtype:
253
+ x = x.to(self.weight.dtype)
254
+
255
+ orig_shape = x.shape
256
+
257
+ if self.coft:
258
+ with torch.no_grad():
259
+ self.weight.copy_(self._project_batch(self.weight, eps=self.eps))
260
+
261
+ orth_rotate = self._cayley_batch(
262
+ self.weight, self.block_size, self.use_cayley_neumann, self.num_cayley_neumann_terms
263
+ )
264
+
265
+ # Unfold the input for Conv2d layer
266
+ if len(orig_shape) == 4:
267
+ x = self._unfold(x)
268
+
269
+ folded_shape = x.shape
270
+ rank = self.in_features // self.block_size if self.block_share else self.r
271
+ batch_dims = x.shape[:-1]
272
+ x_reshaped = x.reshape(*batch_dims, rank, self.block_size)
273
+
274
+ if self.block_share:
275
+ orth_rotate = orth_rotate.repeat(rank, 1, 1)
276
+ x_rotated_reshaped = torch.einsum("...rk,rkc->...rc", x_reshaped, orth_rotate)
277
+ else:
278
+ x_rotated_reshaped = torch.einsum("...rk,rkc->...rc", x_reshaped, orth_rotate)
279
+
280
+ x_rotated = x_rotated_reshaped.reshape(*folded_shape)
281
+
282
+ if len(orig_shape) == 4:
283
+ x_rotated = self._fold(x_rotated, orig_shape)
284
+
285
+ return x_rotated.to(required_dtype)
286
+
287
+ def get_weight(self):
288
+ """
289
+ Compute the delta weight for the given adapter.
290
+
291
+ Args:
292
+ adapter (str):
293
+ The name of the adapter for which the delta weight should be computed.
294
+ """
295
+ weight = self.weight
296
+
297
+ if self.coft:
298
+ with torch.no_grad():
299
+ weight = self._project_batch(weight, eps=self.eps)
300
+ self.weight.copy_(weight)
301
+
302
+ orth_rotate = self._cayley_batch(
303
+ weight, self.block_size, self.use_cayley_neumann, self.num_cayley_neumann_terms
304
+ )
305
+
306
+ rank = self.r if not self.block_share else self.in_features // self.block_size
307
+ return self._block_diagonal(orth_rotate, rank)
308
+
309
+
310
+ class OFTLayer(BaseTunerLayer):
311
+ """
312
+ Implements the OFT layer.
313
+ """
314
+
315
+ # All names of layers that may contain (trainable) adapter weights
316
+ adapter_layer_names: tuple[str, ...] = ("oft_R", "oft_embedding_R")
317
+ # All names of other parameters that may contain adapter-related parameters
318
+ other_param_names: tuple[str, ...] = ("r", "oft_block_size", "oft_dropout")
319
+
320
+ def __init__(self, base_layer: nn.Module, **kwargs) -> None:
321
+ """
322
+ Initializes the OFT layer.
323
+
324
+ Note, currently only support linear layer and convolutional layer, with further support for other layers to be
325
+ added soon.
326
+
327
+ Parameters:
328
+ base_layer: the pretrained model layer
329
+ """
330
+ self.base_layer = base_layer
331
+ self.oft_R = nn.ModuleDict({})
332
+ # For Embedding layer
333
+ self.oft_embedding_R = nn.ModuleDict({})
334
+ self.oft_block_size = {}
335
+ self.r = {}
336
+ self.oft_block_size = {}
337
+ self.oft_dropout = nn.ModuleDict({})
338
+ # Mark the weight as unmerged
339
+ self._disable_adapters = False
340
+ self.merged_adapters = []
341
+ # flag to enable/disable casting of input to weight dtype during forward call
342
+ self.cast_input_dtype_enabled = True
343
+ self.kwargs = kwargs
344
+
345
+ base_layer = self.get_base_layer()
346
+ if isinstance(base_layer, nn.Linear):
347
+ in_features, out_features = base_layer.in_features, base_layer.out_features
348
+ elif isinstance(base_layer, nn.Conv2d):
349
+ in_features, out_features = base_layer.in_channels, base_layer.out_channels
350
+ elif isinstance(base_layer, nn.Embedding):
351
+ in_features, out_features = base_layer.embedding_dim, base_layer.num_embeddings
352
+ elif hasattr(base_layer, "infeatures") and hasattr(base_layer, "outfeatures"):
353
+ # QuantLinear
354
+ in_features, out_features = base_layer.infeatures, base_layer.outfeatures
355
+ elif hasattr(base_layer, "input_size") and hasattr(base_layer, "output_size"):
356
+ # Megatron ColumnParallelLinear,RowParallelLinear
357
+ in_features, out_features = base_layer.input_size, base_layer.output_size
358
+ elif hasattr(base_layer, "codebooks") and base_layer.__class__.__name__ == "QuantizedLinear":
359
+ # AQLM QuantLinear
360
+ in_features, out_features = base_layer.in_features, base_layer.out_features
361
+ elif hasattr(base_layer, "bits") and base_layer.__class__.__name__ == "AwqGEMMQuantLinear":
362
+ # Awq layers
363
+ in_features, out_features = base_layer.in_features, base_layer.out_features
364
+ elif base_layer.__class__.__name__ == "EetqLinear":
365
+ # Eetq layers
366
+ in_features, out_features = base_layer.in_features, base_layer.out_features
367
+ elif hasattr(base_layer, "W_q") and base_layer.__class__.__name__ == "HQQLinear":
368
+ # HQQ layers
369
+ in_features, out_features = base_layer.in_features, base_layer.out_features
370
+ else:
371
+ # possibly support user provided custom layer types using dynamic dispatch
372
+ if hasattr(base_layer, "in_features") and hasattr(base_layer, "out_features"):
373
+ in_features, out_features = base_layer.in_features, base_layer.out_features
374
+ else:
375
+ in_features, out_features = None, None
376
+ warnings.warn(
377
+ f"Unsupported layer type '{type(base_layer)}' encountered, proceed at your own risk.", UserWarning
378
+ )
379
+
380
+ self.in_features = in_features
381
+ self.out_features = out_features
382
+
383
+ def set_scale(self, adapter, scale):
384
+ if adapter not in self.scaling:
385
+ # Ignore the case where the adapter is not in the layer
386
+ return
387
+
388
+ warnings.warn("Scaling operation for OFT not supported! Automatically set scale to 1.")
389
+
390
+ def scale_layer(self, scale: float) -> None:
391
+ if scale == 1:
392
+ return
393
+
394
+ for active_adapter in self.active_adapters:
395
+ if active_adapter not in self.oft_R.keys():
396
+ continue
397
+
398
+ warnings.warn("Scaling operation for OFT not supported! Automatically set scale to 1.")
399
+
400
+ def unscale_layer(self, scale=None) -> None:
401
+ for active_adapter in self.active_adapters:
402
+ if active_adapter not in self.oft_R.keys():
403
+ continue
404
+
405
+ warnings.warn("Unscaling operation for OFT not supported! Keeping scale to 1.")
406
+
407
+ def update_layer(
408
+ self,
409
+ adapter_name,
410
+ r,
411
+ oft_block_size,
412
+ module_dropout,
413
+ coft,
414
+ eps,
415
+ block_share,
416
+ init_weights,
417
+ use_cayley_neumann,
418
+ num_cayley_neumann_terms,
419
+ inference_mode: bool = False,
420
+ **kwargs,
421
+ ):
422
+ """
423
+ Update the linear layer with trainable OFT weights. Override for other layer types.
424
+ """
425
+ """Internal function to create oft adapter
426
+
427
+ Args:
428
+ adapter_name (`str`): Name for the adapter to add.
429
+ r (`int`): Rank for the added adapter.
430
+ oft_block_size (`int`): The block size for added adapter.
431
+ module_dropout (`float`):
432
+ The multiplicative dropout probability for disabling adapter blocks during training.
433
+ coft (`bool`): Whether to use the constrained variant of OFT or not.
434
+ eps (`float`):
435
+ The control strength of COFT. The freedom of rotation. Only has an effect if `coft` is set to True.
436
+ block_share (`bool`): Whether to share the OFT parameters between blocks or not.
437
+ init_weights (`bool`): Whether to initialize weights.
438
+ """
439
+ # Initialize the MultiplicativeDropoutLayer for module_dropout > 0.0.
440
+ if module_dropout > 0.0:
441
+ oft_dropout_layer = MultiplicativeDropoutLayer(p=module_dropout)
442
+ else:
443
+ oft_dropout_layer = nn.Identity()
444
+ self.oft_dropout.update(nn.ModuleDict({adapter_name: oft_dropout_layer}))
445
+
446
+ if r == 0 and oft_block_size != 0:
447
+ if self.in_features % oft_block_size != 0 or oft_block_size > self.in_features:
448
+ old_oft_block_size = oft_block_size
449
+ oft_block_size = self.adjust_oft_parameters(self.in_features, oft_block_size)
450
+ warnings.warn(
451
+ f"Invalid `oft_block_size` ({old_oft_block_size})! Adjusted `oft_block_size` to ({oft_block_size})."
452
+ )
453
+ r = int(self.in_features // oft_block_size)
454
+ elif r != 0 and oft_block_size == 0:
455
+ if self.in_features % r != 0 or r > self.in_features:
456
+ old_r = r
457
+ r = self.adjust_oft_parameters(self.in_features, r)
458
+ warnings.warn(f"Invalid `r` ({old_r})! Adjusted `r` to ({r}).")
459
+ oft_block_size = int(self.in_features // r)
460
+ else:
461
+ raise ValueError(
462
+ "Something went wrong, please report this error: https://github.com/huggingface/peft/issues"
463
+ )
464
+
465
+ # Create weights with provided shape
466
+ n_elements = oft_block_size * (oft_block_size - 1) // 2
467
+ self.oft_R[adapter_name] = OFTRotationModule(
468
+ r if not block_share else 1,
469
+ n_elements,
470
+ oft_block_size,
471
+ self.in_features,
472
+ coft=coft,
473
+ eps=eps,
474
+ block_share=block_share,
475
+ use_cayley_neumann=use_cayley_neumann,
476
+ num_cayley_neumann_terms=num_cayley_neumann_terms,
477
+ )
478
+
479
+ # Initialize weights
480
+ self.reset_oft_parameters(adapter_name, init_weights)
481
+
482
+ # set oft r and block size
483
+ self.r[adapter_name] = r
484
+ self.oft_block_size[adapter_name] = oft_block_size
485
+
486
+ # Move new weights to device
487
+ self._move_adapter_to_device_of_base_layer(adapter_name)
488
+ self.set_adapter(self.active_adapters, inference_mode=inference_mode)
489
+
490
+ def reset_oft_parameters(self, adapter_name, init_weights):
491
+ """
492
+ Reset the OFT parameters.
493
+ """
494
+ if init_weights is False:
495
+ if adapter_name in self.oft_R.keys():
496
+ nn.init.normal_(self.oft_R[adapter_name].weight, mean=0.0, std=0.1)
497
+ return
498
+ if adapter_name in self.oft_embedding_R.keys():
499
+ nn.init.normal_(self.oft_embedding_R[adapter_name].weight, mean=0.0, std=0.1)
500
+ return
501
+
502
+ if adapter_name in self.oft_R.keys():
503
+ if init_weights is True:
504
+ # initialize oft_R to zero
505
+ nn.init.zeros_(self.oft_R[adapter_name].weight)
506
+ else:
507
+ raise ValueError(f"Unknown initialization {init_weights=}")
508
+ if adapter_name in self.oft_embedding_R.keys():
509
+ if init_weights is True:
510
+ # initialize oft_embedding_R to zero
511
+ nn.init.zeros_(self.oft_embedding_R[adapter_name].weight)
512
+ else:
513
+ raise ValueError(f"Unknown initialization {init_weights=}")
514
+
515
+ def adjust_oft_parameters(self, in_features, params):
516
+ """
517
+ Adjust the OFT parameters to be divisible by the in_features dimension.
518
+ """
519
+ if params < in_features:
520
+ higher_params = params
521
+ while higher_params <= in_features and in_features % higher_params != 0:
522
+ higher_params += 1
523
+ else:
524
+ return in_features
525
+
526
+ lower_params = params
527
+ while lower_params > 1 and in_features % lower_params != 0:
528
+ lower_params -= 1
529
+
530
+ if (params - lower_params) <= (higher_params - params):
531
+ return lower_params
532
+ else:
533
+ return higher_params
534
+
535
+
536
+ class Linear(nn.Module, OFTLayer):
537
+ """OFT implemented in Linear layer"""
538
+
539
+ def __init__(
540
+ self,
541
+ base_layer,
542
+ adapter_name: str,
543
+ r: int = 8,
544
+ oft_block_size: int = 0,
545
+ module_dropout: float = 0.0,
546
+ coft: bool = False,
547
+ eps: float = 6e-5,
548
+ block_share: bool = False,
549
+ use_cayley_neumann: bool = False,
550
+ num_cayley_neumann_terms: int = 5,
551
+ fan_in_fan_out: bool = False, # Set this to True if the layer to replace stores weight like (fan_in, fan_out)
552
+ init_weights: Union[bool, str] = True,
553
+ is_target_conv_1d_layer: bool = False,
554
+ **kwargs,
555
+ ) -> None:
556
+ super().__init__()
557
+ OFTLayer.__init__(self, base_layer, **kwargs)
558
+ self.fan_in_fan_out = fan_in_fan_out
559
+
560
+ self._active_adapter = adapter_name
561
+
562
+ self.update_layer(
563
+ adapter_name,
564
+ r,
565
+ oft_block_size=oft_block_size,
566
+ module_dropout=module_dropout,
567
+ coft=coft,
568
+ eps=eps,
569
+ block_share=block_share,
570
+ init_weights=init_weights,
571
+ use_cayley_neumann=use_cayley_neumann,
572
+ num_cayley_neumann_terms=num_cayley_neumann_terms,
573
+ )
574
+ self.is_target_conv_1d_layer = is_target_conv_1d_layer
575
+
576
+ def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None:
577
+ """
578
+ Merge the active adapter weights into the base weights
579
+
580
+ Args:
581
+ safe_merge (`bool`, *optional*):
582
+ If `True`, the merge operation will be performed in a copy of the original weights and check for NaNs
583
+ before merging the weights. This is useful if you want to check if the merge operation will produce
584
+ NaNs. Defaults to `False`.
585
+ adapter_names (`List[str]`, *optional*):
586
+ The list of adapter names that should be merged. If `None`, all active adapters will be merged.
587
+ Defaults to `None`.
588
+ """
589
+ adapter_names = check_adapters_to_merge(self, adapter_names)
590
+ if not adapter_names:
591
+ # no adapter to merge
592
+ return
593
+
594
+ for active_adapter in adapter_names:
595
+ if active_adapter in self.oft_R.keys():
596
+ base_layer = self.get_base_layer()
597
+ orig_dtype = base_layer.weight.dtype
598
+ if safe_merge:
599
+ # Note that safe_merge will be slower than the normal merge
600
+ orig_weights = base_layer.weight.data
601
+ oft_mat = self.get_delta_weight(active_adapter)
602
+ orig_weights = torch.transpose(orig_weights, 0, 1)
603
+ orig_weights = torch.mm(oft_mat, orig_weights.to(oft_mat.dtype))
604
+ orig_weights = torch.transpose(orig_weights, 0, 1)
605
+
606
+ if not torch.isfinite(orig_weights).all():
607
+ raise ValueError(
608
+ f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken"
609
+ )
610
+
611
+ base_layer.weight.data = orig_weights.contiguous().to(orig_dtype)
612
+ else:
613
+ orig_weights = base_layer.weight.data
614
+ oft_mat = self.get_delta_weight(active_adapter)
615
+ orig_weights = torch.transpose(orig_weights, 0, 1)
616
+ orig_weights = torch.mm(oft_mat, orig_weights.to(oft_mat.dtype))
617
+ orig_weights = torch.transpose(orig_weights, 0, 1)
618
+
619
+ base_layer.weight.data = orig_weights.contiguous().to(orig_dtype)
620
+
621
+ self.merged_adapters.append(active_adapter)
622
+
623
+ def unmerge(self) -> None:
624
+ """
625
+ This method unmerges all merged adapter layers from the base weights.
626
+ """
627
+ if not self.merged:
628
+ warnings.warn("Already unmerged. Nothing to do.")
629
+ return
630
+
631
+ base_layer = self.get_base_layer()
632
+ orig_dtype = base_layer.weight.dtype
633
+ while len(self.merged_adapters) > 0:
634
+ active_adapter = self.merged_adapters.pop()
635
+ if active_adapter in self.oft_R.keys():
636
+ oft_mat = self.get_delta_weight(active_adapter)
637
+
638
+ previous_dtype = oft_mat.dtype
639
+ if previous_dtype != torch.float32:
640
+ oft_mat = oft_mat.to(torch.float32)
641
+
642
+ orig_weights = self.get_base_layer().weight.data
643
+ orig_weights = torch.transpose(orig_weights, 0, 1)
644
+ orig_weights = torch.mm(torch.linalg.inv(oft_mat).to(previous_dtype), orig_weights.to(previous_dtype))
645
+ orig_weights = torch.transpose(orig_weights, 0, 1)
646
+
647
+ base_layer.weight.data = orig_weights.to(orig_dtype)
648
+
649
+ def get_delta_weight(self, adapter) -> torch.Tensor:
650
+ """
651
+ Compute the delta weight for the given adapter.
652
+
653
+ Args:
654
+ adapter (str):
655
+ The name of the adapter for which the delta weight should be computed.
656
+ """
657
+ device = self.oft_R[adapter].weight.device
658
+ dtype = self.oft_R[adapter].weight.dtype
659
+
660
+ # In case users wants to merge the adapter weights that are in
661
+ # (b)float16 while being on CPU, we need to cast the weights to float32, perform the merge and then cast back to
662
+ # (b)float16 because some CPUs have slow bf16/fp16 matmuls.
663
+ cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16)
664
+
665
+ oft_R_module = self.oft_R[adapter]
666
+
667
+ if cast_to_fp32:
668
+ # Temporarily work in fp32 for faster CPU matmul
669
+ original_weight = oft_R_module.weight.data
670
+ oft_R_module.weight.data = oft_R_module.weight.data.float()
671
+ oft_mat = oft_R_module.get_weight()
672
+ oft_R_module.weight.data = original_weight # restore
673
+ return oft_mat.to(dtype)
674
+ else:
675
+ return oft_R_module.get_weight()
676
+
677
+ def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor:
678
+ previous_dtype = x.dtype
679
+
680
+ if self.disable_adapters:
681
+ if self.merged:
682
+ self.unmerge()
683
+ result = self.base_layer(x, *args, **kwargs)
684
+ elif self.merged:
685
+ result = self.base_layer(x, *args, **kwargs)
686
+ else:
687
+ for active_adapter in self.active_adapters:
688
+ if active_adapter not in self.oft_R.keys():
689
+ continue
690
+ oft_R = self.oft_R[active_adapter]
691
+
692
+ x = self._cast_input_dtype(x, oft_R.weight.dtype)
693
+ x = oft_R(x)
694
+
695
+ result = self.base_layer(x.to(previous_dtype), *args, **kwargs)
696
+
697
+ result = result.to(previous_dtype)
698
+ return result
699
+
700
+ def __repr__(self) -> str:
701
+ rep = super().__repr__()
702
+ return "oft." + rep
703
+
704
+
705
+ class Conv2d(nn.Module, OFTLayer):
706
+ """OFT implemented in Conv2d layer"""
707
+
708
+ def __init__(
709
+ self,
710
+ base_layer: nn.Module,
711
+ adapter_name: str,
712
+ r: int = 8,
713
+ oft_block_size: int = 0,
714
+ fan_in_fan_out: bool = False, # Set this to True if the layer to replace stores weight like (fan_in, fan_out)
715
+ module_dropout: float = 0.0,
716
+ coft: bool = False,
717
+ eps: float = 6e-5,
718
+ block_share: bool = False,
719
+ init_weights: Union[bool, str] = True,
720
+ use_cayley_neumann: bool = False,
721
+ num_cayley_neumann_terms: int = 5,
722
+ **kwargs,
723
+ ) -> None:
724
+ super().__init__()
725
+ OFTLayer.__init__(self, base_layer)
726
+ self.fan_in_fan_out = fan_in_fan_out
727
+
728
+ self._active_adapter = adapter_name
729
+
730
+ # Create adapter and set it active
731
+ self.update_layer(
732
+ adapter_name,
733
+ r,
734
+ oft_block_size=oft_block_size,
735
+ module_dropout=module_dropout,
736
+ coft=coft,
737
+ eps=eps,
738
+ block_share=block_share,
739
+ init_weights=init_weights,
740
+ use_cayley_neumann=use_cayley_neumann,
741
+ num_cayley_neumann_terms=num_cayley_neumann_terms,
742
+ )
743
+
744
+ def update_layer(
745
+ self,
746
+ adapter_name,
747
+ r,
748
+ oft_block_size,
749
+ module_dropout,
750
+ coft,
751
+ eps,
752
+ block_share,
753
+ init_weights,
754
+ use_cayley_neumann,
755
+ num_cayley_neumann_terms,
756
+ inference_mode: bool = False,
757
+ **kwargs,
758
+ ):
759
+ """
760
+ Update the conv2d layer with trainable OFT weights.
761
+ """
762
+ # Initialize the MultiplicativeDropoutLayer for module_dropout > 0.0.
763
+ if module_dropout > 0.0:
764
+ oft_dropout_layer = MultiplicativeDropoutLayer(p=module_dropout)
765
+ else:
766
+ oft_dropout_layer = nn.Identity()
767
+ self.oft_dropout.update(nn.ModuleDict({adapter_name: oft_dropout_layer}))
768
+
769
+ # layer information from the base layer
770
+ base_layer = self.get_base_layer()
771
+ if base_layer.dilation[0] > 1:
772
+ raise ValueError("Conv2d with dilation > 1 is not supported by OFT.")
773
+
774
+ conv_filter_dim = self.in_features * base_layer.kernel_size[0] * base_layer.kernel_size[0]
775
+
776
+ if r == 0 and oft_block_size != 0:
777
+ if conv_filter_dim % oft_block_size != 0 or oft_block_size > conv_filter_dim:
778
+ old_oft_block_size = oft_block_size
779
+ oft_block_size = self.adjust_oft_parameters(conv_filter_dim, oft_block_size)
780
+ warnings.warn(
781
+ f"Invalid `oft_block_size` ({old_oft_block_size})! Adjusted `oft_block_size` to ({oft_block_size})."
782
+ )
783
+ r = int(conv_filter_dim // oft_block_size)
784
+ elif r != 0 and oft_block_size == 0:
785
+ if conv_filter_dim % r != 0 or r > conv_filter_dim:
786
+ old_r = r
787
+ r = self.adjust_oft_parameters(conv_filter_dim, r)
788
+ warnings.warn(f"Invalid `r` ({old_r})! Adjusted `r` to ({r}).")
789
+ oft_block_size = int(conv_filter_dim // r)
790
+ else:
791
+ raise ValueError(
792
+ "Something went wrong, please report this error: https://github.com/huggingface/peft/issues"
793
+ )
794
+
795
+ # Create weights with provided shape
796
+ n_elements = oft_block_size * (oft_block_size - 1) // 2
797
+ self.oft_R[adapter_name] = OFTRotationModule(
798
+ r if not block_share else 1,
799
+ n_elements,
800
+ oft_block_size,
801
+ conv_filter_dim,
802
+ coft=coft,
803
+ eps=eps,
804
+ block_share=block_share,
805
+ kernel_size=base_layer.kernel_size,
806
+ use_cayley_neumann=use_cayley_neumann,
807
+ num_cayley_neumann_terms=num_cayley_neumann_terms,
808
+ )
809
+
810
+ # Initialize weights
811
+ self.reset_oft_parameters(adapter_name, init_weights)
812
+
813
+ # set oft r and block size
814
+ self.r[adapter_name] = r
815
+ self.oft_block_size[adapter_name] = oft_block_size
816
+
817
+ # Move new weights to device
818
+ self._move_adapter_to_device_of_base_layer(adapter_name)
819
+ self.set_adapter(self.active_adapters, inference_mode=inference_mode)
820
+
821
+ def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None:
822
+ """
823
+ Merge the active adapter weights into the base weights
824
+
825
+ Args:
826
+ safe_merge (`bool`, *optional*):
827
+ If True, the merge operation will be performed in a copy of the original weights and check for NaNs
828
+ before merging the weights. This is useful if you want to check if the merge operation will produce
829
+ NaNs. Defaults to `False`.
830
+ adapter_names (`List[str]`, *optional*):
831
+ The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults
832
+ to `None`.
833
+ """
834
+ adapter_names = check_adapters_to_merge(self, adapter_names)
835
+ if not adapter_names:
836
+ # no adapter to merge
837
+ return
838
+
839
+ for active_adapter in adapter_names:
840
+ if active_adapter in self.oft_R.keys():
841
+ base_layer = self.get_base_layer()
842
+ orig_dtype = base_layer.weight.dtype
843
+ if safe_merge:
844
+ # Note that safe_merge will be slower than the normal merge
845
+ # because of the copy operation.
846
+ orig_weights = base_layer.weight.data.clone()
847
+ oft_mat = self.get_delta_weight(active_adapter)
848
+
849
+ orig_weights = orig_weights.view(
850
+ self.out_features, self.in_features * base_layer.kernel_size[0] * base_layer.kernel_size[0]
851
+ )
852
+ orig_weights = torch.transpose(orig_weights, 0, 1)
853
+ orig_weights = torch.mm(oft_mat, orig_weights.to(oft_mat.dtype))
854
+ orig_weights = torch.transpose(orig_weights, 0, 1)
855
+ orig_weights = orig_weights.view(
856
+ self.out_features, self.in_features, base_layer.kernel_size[0], base_layer.kernel_size[0]
857
+ )
858
+
859
+ base_layer.weight.data = orig_weights.contiguous().to(orig_dtype)
860
+ else:
861
+ oft_mat = self.get_delta_weight(active_adapter)
862
+
863
+ orig_weights = base_layer.weight.data.clone()
864
+ orig_weights = orig_weights.view(
865
+ self.out_features, self.in_features * base_layer.kernel_size[0] * base_layer.kernel_size[0]
866
+ )
867
+ orig_weights = torch.transpose(orig_weights, 0, 1)
868
+ orig_weights = torch.mm(oft_mat, orig_weights.to(oft_mat.dtype))
869
+ orig_weights = torch.transpose(orig_weights, 0, 1)
870
+ orig_weights = orig_weights.view(
871
+ self.out_features, self.in_features, base_layer.kernel_size[0], base_layer.kernel_size[0]
872
+ )
873
+
874
+ base_layer.weight.data = orig_weights.contiguous().to(orig_dtype)
875
+
876
+ self.merged_adapters.append(active_adapter)
877
+
878
+ def unmerge(self) -> None:
879
+ """
880
+ This method unmerges all merged adapter layers from the base weights.
881
+ """
882
+ if not self.merged:
883
+ warnings.warn("Already unmerged. Nothing to do.")
884
+ return
885
+
886
+ base_layer = self.get_base_layer()
887
+ orig_dtype = base_layer.weight.dtype
888
+ while len(self.merged_adapters) > 0:
889
+ active_adapter = self.merged_adapters.pop()
890
+ if active_adapter in self.oft_R.keys():
891
+ oft_mat = self.get_delta_weight(active_adapter)
892
+
893
+ previous_dtype = oft_mat.dtype
894
+ if previous_dtype != torch.float32:
895
+ oft_mat = oft_mat.to(torch.float32)
896
+
897
+ orig_weights = self.get_base_layer().weight.data.clone()
898
+ orig_weights = orig_weights.view(
899
+ self.out_features,
900
+ self.in_features * self.get_base_layer().kernel_size[0] * self.get_base_layer().kernel_size[0],
901
+ )
902
+ orig_weights = torch.transpose(orig_weights, 0, 1)
903
+ orig_weights = torch.mm(torch.linalg.inv(oft_mat).to(previous_dtype), orig_weights.to(previous_dtype))
904
+ orig_weights = torch.transpose(orig_weights, 0, 1)
905
+ orig_weights = orig_weights.view(
906
+ self.out_features,
907
+ self.in_features,
908
+ self.get_base_layer().kernel_size[0],
909
+ self.get_base_layer().kernel_size[0],
910
+ )
911
+
912
+ base_layer.weight.data = orig_weights.to(orig_dtype)
913
+
914
+ def get_delta_weight(self, adapter) -> torch.Tensor:
915
+ """
916
+ Compute the delta weight for the given adapter.
917
+
918
+ Args:
919
+ adapter (str):
920
+ The name of the adapter for which the delta weight should be computed.
921
+ """
922
+ device = self.oft_R[adapter].weight.device
923
+ dtype = self.oft_R[adapter].weight.dtype
924
+
925
+ # In case users wants to merge the adapter weights that are in
926
+ # (b)float16 while being on CPU, we need to cast the weights to float32, perform the merge and then cast back to
927
+ # (b)float16 because some CPUs have slow bf16/fp16 matmuls.
928
+ cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16)
929
+
930
+ oft_R_module = self.oft_R[adapter]
931
+
932
+ if cast_to_fp32:
933
+ # Temporarily work in fp32 for faster CPU matmul
934
+ original_weight = oft_R_module.weight.data
935
+ oft_R_module.weight.data = oft_R_module.weight.data.float()
936
+ oft_mat = oft_R_module.get_weight()
937
+ oft_R_module.weight.data = original_weight # restore
938
+ return oft_mat.to(dtype)
939
+ else:
940
+ return oft_R_module.get_weight()
941
+
942
+ def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor:
943
+ previous_dtype = x.dtype
944
+
945
+ if self.disable_adapters:
946
+ if self.merged:
947
+ self.unmerge()
948
+ result = self.base_layer(x, *args, **kwargs)
949
+ elif self.merged:
950
+ result = self.base_layer(x, *args, **kwargs)
951
+ else:
952
+ for active_adapter in self.active_adapters:
953
+ if active_adapter not in self.oft_R.keys():
954
+ continue
955
+
956
+ oft_R = self.oft_R[active_adapter]
957
+ x = self._cast_input_dtype(x, oft_R.weight.dtype)
958
+ x = oft_R(x)
959
+
960
+ result = self.base_layer(x.to(previous_dtype), *args, **kwargs)
961
+
962
+ result = result.to(previous_dtype)
963
+ return result
964
+
965
+ def __repr__(self) -> str:
966
+ rep = super().__repr__()
967
+ return "oft." + rep
968
+
969
+
970
+ class Embedding(nn.Module, OFTLayer):
971
+ # OFT implemented in a Embedding layer
972
+ def __init__(
973
+ self,
974
+ base_layer: nn.Module,
975
+ adapter_name: str,
976
+ r: int = 8,
977
+ oft_block_size: int = 0,
978
+ module_dropout: float = 0.0,
979
+ coft: bool = False,
980
+ eps: float = 6e-5,
981
+ block_share: bool = False,
982
+ use_cayley_neumann: bool = False,
983
+ num_cayley_neumann_terms: int = 5,
984
+ fan_in_fan_out: bool = False, # unused for embedding, kept for API parity
985
+ init_weights: Union[bool, str] = True,
986
+ **kwargs,
987
+ ) -> None:
988
+ super().__init__()
989
+ OFTLayer.__init__(self, base_layer)
990
+ self.fan_in_fan_out = fan_in_fan_out
991
+
992
+ self._active_adapter = adapter_name
993
+ self.update_layer(
994
+ adapter_name,
995
+ r,
996
+ oft_block_size=oft_block_size,
997
+ module_dropout=module_dropout,
998
+ coft=coft,
999
+ eps=eps,
1000
+ block_share=block_share,
1001
+ init_weights=init_weights,
1002
+ use_cayley_neumann=use_cayley_neumann,
1003
+ num_cayley_neumann_terms=num_cayley_neumann_terms,
1004
+ )
1005
+
1006
+ def update_layer(
1007
+ self,
1008
+ adapter_name,
1009
+ r,
1010
+ oft_block_size,
1011
+ module_dropout,
1012
+ coft,
1013
+ eps,
1014
+ block_share,
1015
+ init_weights,
1016
+ use_cayley_neumann,
1017
+ num_cayley_neumann_terms,
1018
+ inference_mode: bool = False,
1019
+ **kwargs,
1020
+ ):
1021
+ # collect the kwargs
1022
+ kwargs = locals().copy()
1023
+ del kwargs["self"]
1024
+
1025
+ if r == 0 and oft_block_size != 0:
1026
+ if self.in_features % oft_block_size != 0 or oft_block_size > self.in_features:
1027
+ old_oft_block_size = oft_block_size
1028
+ oft_block_size = self.adjust_oft_parameters(self.in_features, oft_block_size)
1029
+ warnings.warn(
1030
+ f"Invalid `oft_block_size` ({old_oft_block_size})! Adjusted `oft_block_size` to ({oft_block_size})."
1031
+ )
1032
+ r = int(self.in_features // oft_block_size)
1033
+ elif r != 0 and oft_block_size == 0:
1034
+ if self.in_features % r != 0 or r > self.in_features:
1035
+ old_r = r
1036
+ r = self.adjust_oft_parameters(self.in_features, r)
1037
+ warnings.warn(f"Invalid `r` ({old_r})! Adjusted `r` to ({r}).")
1038
+ oft_block_size = int(self.in_features // r)
1039
+ else:
1040
+ raise ValueError(
1041
+ "Something went wrong, please report this error: https://github.com/huggingface/peft/issues"
1042
+ )
1043
+
1044
+ # Create weights with provided shape
1045
+ n_elements = oft_block_size * (oft_block_size - 1) // 2
1046
+ self.oft_embedding_R[adapter_name] = OFTRotationModule(
1047
+ r if not block_share else 1,
1048
+ n_elements,
1049
+ oft_block_size,
1050
+ self.in_features,
1051
+ coft=coft,
1052
+ eps=eps,
1053
+ block_share=block_share,
1054
+ use_cayley_neumann=use_cayley_neumann,
1055
+ num_cayley_neumann_terms=num_cayley_neumann_terms,
1056
+ )
1057
+
1058
+ # Initialize weights
1059
+ self.reset_oft_parameters(adapter_name, init_weights)
1060
+
1061
+ # set oft r and block size
1062
+ self.r[adapter_name] = r
1063
+ self.oft_block_size[adapter_name] = oft_block_size
1064
+
1065
+ # Move new weights to device
1066
+ self._move_adapter_to_device_of_base_layer(adapter_name)
1067
+ self.set_adapter(self.active_adapters, inference_mode=inference_mode)
1068
+
1069
+ def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None:
1070
+ """
1071
+ Merge the active adapter weights into the base weights
1072
+
1073
+ Args:
1074
+ safe_merge (`bool`, *optional*):
1075
+ If True, the merge operation will be performed in a copy of the original weights and check for NaNs
1076
+ before merging the weights. This is useful if you want to check if the merge operation will produce
1077
+ NaNs. Defaults to `False`.
1078
+ adapter_names (`list[str]`, *optional*):
1079
+ The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults
1080
+ to `None`.
1081
+ """
1082
+ adapter_names = check_adapters_to_merge(self, adapter_names)
1083
+ if not adapter_names:
1084
+ # no adapter to merge
1085
+ return
1086
+
1087
+ for active_adapter in adapter_names:
1088
+ if active_adapter in self.oft_embedding_R.keys():
1089
+ base_layer = self.get_base_layer()
1090
+ orig_dtype = base_layer.weight.dtype
1091
+ if safe_merge:
1092
+ # Note that safe_merge will be slower than the normal merge
1093
+ orig_weights = base_layer.weight.data
1094
+ oft_mat = self.get_delta_weight(active_adapter)
1095
+ orig_weights = torch.mm(orig_weights.to(oft_mat.dtype), oft_mat)
1096
+
1097
+ if not torch.isfinite(orig_weights).all():
1098
+ raise ValueError(
1099
+ f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken"
1100
+ )
1101
+
1102
+ base_layer.weight.data = orig_weights.contiguous().to(orig_dtype)
1103
+ else:
1104
+ orig_weights = base_layer.weight.data
1105
+ oft_mat = self.get_delta_weight(active_adapter)
1106
+ orig_weights = torch.mm(orig_weights.to(oft_mat.dtype), oft_mat)
1107
+
1108
+ base_layer.weight.data = orig_weights.contiguous().to(orig_dtype)
1109
+ self.merged_adapters.append(active_adapter)
1110
+
1111
+ def unmerge(self) -> None:
1112
+ """
1113
+ This method unmerges all merged adapter layers from the base weights.
1114
+ """
1115
+ if not self.merged:
1116
+ warnings.warn("Already unmerged. Nothing to do.")
1117
+ return
1118
+
1119
+ base_layer = self.get_base_layer()
1120
+ orig_dtype = base_layer.weight.dtype
1121
+ while len(self.merged_adapters) > 0:
1122
+ active_adapter = self.merged_adapters.pop()
1123
+ if active_adapter in self.oft_embedding_R.keys():
1124
+ oft_mat = self.get_delta_weight(active_adapter)
1125
+
1126
+ previous_dtype = oft_mat.dtype
1127
+ if previous_dtype != torch.float32:
1128
+ oft_mat = oft_mat.to(torch.float32)
1129
+
1130
+ orig_weights = self.get_base_layer().weight.data
1131
+ orig_weights = torch.mm(orig_weights.to(oft_mat.dtype), torch.linalg.inv(oft_mat))
1132
+
1133
+ base_layer.weight.data = orig_weights.to(orig_dtype)
1134
+
1135
+ def get_delta_weight(self, adapter) -> torch.Tensor:
1136
+ """
1137
+ Compute the delta weight for the given adapter.
1138
+
1139
+ Args:
1140
+ adapter (str):
1141
+ The name of the adapter for which the delta weight should be computed.
1142
+ """
1143
+ device = self.oft_embedding_R[adapter].weight.device
1144
+ dtype = self.oft_embedding_R[adapter].weight.dtype
1145
+
1146
+ # In case users wants to merge the adapter weights that are in
1147
+ # (b)float16 while being on CPU, we need to cast the weights to float32, perform the merge and then cast back to
1148
+ # (b)float16 because some CPUs have slow bf16/fp16 matmuls.
1149
+ cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16)
1150
+
1151
+ oft_R_module = self.oft_embedding_R[adapter]
1152
+
1153
+ if cast_to_fp32:
1154
+ # Temporarily work in fp32 for faster CPU matmul
1155
+ original_weight = oft_R_module.weight.data
1156
+ oft_R_module.weight.data = oft_R_module.weight.data.float()
1157
+ oft_mat = oft_R_module.get_weight()
1158
+ oft_R_module.weight.data = original_weight # restore
1159
+ return oft_mat.to(dtype)
1160
+ else:
1161
+ return oft_R_module.get_weight()
1162
+
1163
+ def _embed(self, input: torch.Tensor, weight: torch.Tensor) -> torch.Tensor:
1164
+ base_layer = self.get_base_layer()
1165
+ return F.embedding(
1166
+ input,
1167
+ weight,
1168
+ padding_idx=base_layer.padding_idx,
1169
+ max_norm=base_layer.max_norm,
1170
+ norm_type=base_layer.norm_type,
1171
+ scale_grad_by_freq=base_layer.scale_grad_by_freq,
1172
+ sparse=base_layer.sparse,
1173
+ )
1174
+
1175
+ def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor:
1176
+ # x is token ids (usually LongTensor); rotation is applied to embedding outputs
1177
+ if self.disable_adapters:
1178
+ if self.merged:
1179
+ self.unmerge()
1180
+ return self.base_layer(x, *args, **kwargs)
1181
+ if self.merged:
1182
+ return self.base_layer(x, *args, **kwargs)
1183
+
1184
+ result = self.base_layer(x, *args, **kwargs)
1185
+ out_dtype = result.dtype
1186
+
1187
+ for active_adapter in self.active_adapters:
1188
+ if active_adapter not in self.oft_embedding_R:
1189
+ continue
1190
+ oft_embedding_R = self.oft_embedding_R[active_adapter]
1191
+ result = self._cast_input_dtype(result, oft_embedding_R.weight.dtype)
1192
+ result = oft_embedding_R(result)
1193
+
1194
+ return result.to(out_dtype)
1195
+
1196
+ def __repr__(self) -> str:
1197
+ rep = super().__repr__()
1198
+ return "oft." + rep
1199
+
1200
+
1201
+ def dispatch_default(
1202
+ target: torch.nn.Module,
1203
+ adapter_name: str,
1204
+ oft_config: OFTConfig,
1205
+ **kwargs,
1206
+ ) -> Optional[torch.nn.Module]:
1207
+ new_module = None
1208
+
1209
+ if isinstance(target, BaseTunerLayer):
1210
+ target_base_layer = target.get_base_layer()
1211
+ else:
1212
+ target_base_layer = target
1213
+
1214
+ if isinstance(target_base_layer, torch.nn.Conv2d):
1215
+ new_module = Conv2d(target, adapter_name, **kwargs)
1216
+ elif isinstance(target_base_layer, torch.nn.Linear):
1217
+ if kwargs["fan_in_fan_out"]:
1218
+ warnings.warn(
1219
+ "fan_in_fan_out is set to True but the target module is `torch.nn.Linear`. "
1220
+ "Setting fan_in_fan_out to False."
1221
+ )
1222
+ kwargs["fan_in_fan_out"] = oft_config.fan_in_fan_out = False
1223
+ new_module = Linear(target, adapter_name, **kwargs)
1224
+ elif isinstance(target_base_layer, torch.nn.Embedding):
1225
+ embedding_kwargs = kwargs.copy()
1226
+ embedding_kwargs.pop("fan_in_fan_out", None)
1227
+ new_module = Embedding(target, adapter_name, **embedding_kwargs)
1228
+
1229
+ return new_module
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/model.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from peft.import_utils import is_bnb_4bit_available, is_bnb_available
17
+ from peft.tuners.tuners_utils import (
18
+ BaseTuner,
19
+ get_device_map,
20
+ )
21
+ from peft.utils import (
22
+ TRANSFORMERS_MODELS_TO_OFT_TARGET_MODULES_MAPPING,
23
+ get_quantization_config,
24
+ )
25
+
26
+ from .aqlm import dispatch_aqlm
27
+ from .awq import dispatch_awq
28
+ from .eetq import dispatch_eetq
29
+ from .gptq import dispatch_gptq
30
+ from .hqq import dispatch_hqq
31
+ from .inc import dispatch_inc
32
+ from .layer import OFTLayer, dispatch_default
33
+
34
+
35
+ class OFTModel(BaseTuner):
36
+ """
37
+ Creates Orthogonal Finetuning model from a pretrained model. The method is described in
38
+ https://huggingface.co/papers/2306.07280
39
+
40
+ Args:
41
+ model (`torch.nn.Module`): The model to which the adapter tuner layers will be attached.
42
+ config ([`OFTConfig`]): The configuration of the OFT model.
43
+ adapter_name (`str`): The name of the adapter, defaults to `"default"`.
44
+ low_cpu_mem_usage (`bool`, `optional`, defaults to `False`):
45
+ Create empty adapter weights on meta device. Useful to speed up the loading process.
46
+
47
+ Returns:
48
+ `torch.nn.Module`: The OFT model.
49
+
50
+ Example:
51
+ ```py
52
+ >>> from diffusers import StableDiffusionPipeline
53
+ >>> from peft import OFTModel, OFTConfig
54
+
55
+ >>> config_te = OFTConfig(
56
+ ... r=8,
57
+ ... target_modules=["k_proj", "q_proj", "v_proj", "out_proj", "fc1", "fc2"],
58
+ ... module_dropout=0.0,
59
+ ... init_weights=True,
60
+ ... )
61
+ >>> config_unet = OFTConfig(
62
+ ... r=8,
63
+ ... target_modules=[
64
+ ... "proj_in",
65
+ ... "proj_out",
66
+ ... "to_k",
67
+ ... "to_q",
68
+ ... "to_v",
69
+ ... "to_out.0",
70
+ ... "ff.net.0.proj",
71
+ ... "ff.net.2",
72
+ ... ],
73
+ ... module_dropout=0.0,
74
+ ... init_weights=True,
75
+ ... )
76
+
77
+ >>> model = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5")
78
+ >>> model.text_encoder = OFTModel(model.text_encoder, config_te, "default")
79
+ >>> model.unet = OFTModel(model.unet, config_unet, "default")
80
+ ```
81
+
82
+ **Attributes**:
83
+ - **model** ([`~torch.nn.Module`]) -- The model to be adapted.
84
+ - **peft_config** ([`OFTConfig`]): The configuration of the OFT model.
85
+ """
86
+
87
+ prefix: str = "oft_"
88
+ tuner_layer_cls = OFTLayer
89
+ target_module_mapping = TRANSFORMERS_MODELS_TO_OFT_TARGET_MODULES_MAPPING
90
+
91
+ def _create_and_replace(
92
+ self,
93
+ oft_config,
94
+ adapter_name,
95
+ target,
96
+ target_name,
97
+ parent,
98
+ current_key,
99
+ **optional_kwargs,
100
+ ):
101
+ if current_key is None:
102
+ raise ValueError("Current Key shouldn't be `None`")
103
+
104
+ kwargs = {
105
+ "r": oft_config.r,
106
+ "oft_block_size": oft_config.oft_block_size,
107
+ "module_dropout": oft_config.module_dropout,
108
+ "coft": oft_config.coft,
109
+ "eps": oft_config.eps,
110
+ "block_share": oft_config.block_share,
111
+ "use_cayley_neumann": oft_config.use_cayley_neumann,
112
+ "num_cayley_neumann_terms": oft_config.num_cayley_neumann_terms,
113
+ "fan_in_fan_out": oft_config.fan_in_fan_out,
114
+ "init_weights": oft_config.init_weights,
115
+ "loaded_in_8bit": getattr(self.model, "is_loaded_in_8bit", False),
116
+ "loaded_in_4bit": getattr(self.model, "is_loaded_in_4bit", False),
117
+ }
118
+
119
+ quant_methods = ["gptq", "aqlm", "awq"]
120
+ for quant_method in quant_methods:
121
+ quantization_config = get_quantization_config(self.model, method=quant_method)
122
+ if quantization_config is not None:
123
+ kwargs[f"{quant_method}_quantization_config"] = quantization_config
124
+
125
+ # If it is not a OFTLayer, create a new module, else update it with new adapters
126
+ if not isinstance(target, OFTLayer):
127
+ device_map = get_device_map(self.model)
128
+ new_module = self._create_new_module(oft_config, adapter_name, target, device_map=device_map, **kwargs)
129
+ if adapter_name not in self.active_adapters:
130
+ # adding an additional adapter: it is not automatically trainable
131
+ new_module.requires_grad_(False)
132
+ self._replace_module(parent, target_name, new_module, target)
133
+ else:
134
+ target.update_layer(
135
+ adapter_name,
136
+ r=oft_config.r,
137
+ oft_block_size=oft_config.oft_block_size,
138
+ module_dropout=oft_config.module_dropout,
139
+ coft=oft_config.coft,
140
+ eps=oft_config.eps,
141
+ block_share=oft_config.block_share,
142
+ use_cayley_neumann=oft_config.use_cayley_neumann,
143
+ num_cayley_neumann_terms=oft_config.num_cayley_neumann_terms,
144
+ init_weights=oft_config.init_weights,
145
+ )
146
+
147
+ @staticmethod
148
+ def _create_new_module(oft_config, adapter_name, target, **kwargs):
149
+ # Collect dispatcher functions to decide what backend to use for the replaced OFT layer. The order matters,
150
+ # because the first match is always used. Therefore, the default layers should be checked last.
151
+ dispatchers = []
152
+
153
+ # avoid eager bnb import
154
+ if is_bnb_available():
155
+ from .bnb import dispatch_bnb_8bit
156
+
157
+ dispatchers.append(dispatch_bnb_8bit)
158
+
159
+ if is_bnb_4bit_available():
160
+ from .bnb import dispatch_bnb_4bit
161
+
162
+ dispatchers.append(dispatch_bnb_4bit)
163
+
164
+ dispatchers.extend(
165
+ [
166
+ dispatch_eetq,
167
+ dispatch_aqlm,
168
+ dispatch_awq,
169
+ dispatch_gptq,
170
+ dispatch_hqq,
171
+ dispatch_inc,
172
+ dispatch_default,
173
+ ]
174
+ )
175
+
176
+ new_module = None
177
+ for dispatcher in dispatchers:
178
+ new_module = dispatcher(target, adapter_name, oft_config=oft_config, **kwargs)
179
+ if new_module is not None: # first match wins
180
+ break
181
+
182
+ if new_module is None:
183
+ # no module could be matched
184
+ raise ValueError(
185
+ f"Target module {target} is not supported. Currently, only the following modules are supported: "
186
+ "`torch.nn.Linear`, `torch.nn.Conv2d`."
187
+ )
188
+
189
+ return new_module
190
+
191
+ def _check_merge_allowed(self):
192
+ """Verify that the configuration supports merging.
193
+
194
+ Currently gptq quantization and replicated layers do not support merging.
195
+ """
196
+ super()._check_merge_allowed()
197
+ if getattr(self.model, "quantization_method", None) == "gptq":
198
+ raise ValueError("Cannot merge OFT layers when the model is gptq quantized")
199
+ if self.peft_config.get("layer_replication"):
200
+ raise ValueError("Cannot merge OFT layers when base model layers are replicated")
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from peft.utils import register_peft_method
2
+
3
+ from .config import OSFConfig
4
+ from .layer import Linear, OSFLayer
5
+ from .model import OSFModel
6
+
7
+
8
+ __all__ = ["Linear", "OSFConfig", "OSFLayer", "OSFModel"]
9
+
10
+ register_peft_method(
11
+ name="osf",
12
+ config_cls=OSFConfig,
13
+ model_cls=OSFModel,
14
+ is_mixed_compatible=False,
15
+ )
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (509 Bytes). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/__pycache__/config.cpython-310.pyc ADDED
Binary file (3.47 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/__pycache__/layer.cpython-310.pyc ADDED
Binary file (7.55 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/__pycache__/model.cpython-310.pyc ADDED
Binary file (3.79 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/__pycache__/utils.cpython-310.pyc ADDED
Binary file (3.58 kB). View file
 
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/config.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from typing import Optional, Union
5
+
6
+ from peft.config import PeftConfig
7
+ from peft.utils import PeftType
8
+
9
+
10
+ @dataclass
11
+ class OSFConfig(PeftConfig):
12
+ """
13
+ Configuration for Orthogonal Subspace Fine-tuning (OSF).
14
+
15
+ Args:
16
+ effective_rank (`int` or `float`, *optional*):
17
+ Preserved SVD rank ("high" subspace). The top-``effective_rank`` singular directions are frozen and
18
+ retained across tasks; the remaining dimensions form the trainable low-rank subspace. If `None`, defaults
19
+ to 50% of the smaller weight dimension per target module. Note: This differs from LoRA's `r` (trainable
20
+ rank). In OSF, the trainable rank is `min(weight.shape) - effective_rank`.
21
+ target_modules (`Union[list[str], str]`, *optional*):
22
+ The names of the modules to apply OSF to. Can be a list of module names or `"all-linear"`.
23
+ rank_pattern (`dict[str, int|float]`, *optional*):
24
+ A dictionary of regex patterns to override `effective_rank` for specific modules. Values can be absolute
25
+ integers or fractions in (0, 1], interpreted as a fraction of the smaller matrix dimension per target.
26
+ """
27
+
28
+ effective_rank: Optional[Union[int, float]] = field(
29
+ default=None,
30
+ metadata={
31
+ "help": (
32
+ 'Preserved SVD rank ("high" subspace). The top-`effective_rank` singular directions are frozen '
33
+ "and retained across tasks; the remaining dimensions form the trainable low-rank subspace. "
34
+ "Trainable rank equals min(weight.shape) - effective_rank. If None, defaults to 50% of the smaller "
35
+ "weight dimension per target module. Floats in (0, 1] are interpreted as a fraction of the smaller "
36
+ "matrix dimension per target."
37
+ )
38
+ },
39
+ )
40
+ target_modules: Optional[Union[list[str], str]] = field(
41
+ default=None,
42
+ metadata={"help": "The names of the modules to apply OSF to. Can be a list of module names or 'all-linear'."},
43
+ )
44
+ rank_pattern: Optional[dict[str, Union[int, float]]] = field(
45
+ default=None,
46
+ metadata={
47
+ "help": (
48
+ "A dictionary of regex patterns to override effective_rank per module. Values can be absolute "
49
+ "integers or fractions in (0, 1], interpreted as a fraction of the smaller matrix dimension."
50
+ )
51
+ },
52
+ )
53
+
54
+ # Additional optional fields for compatibility with generic test harnesses
55
+ init_weights: Optional[bool] = field(
56
+ default=None,
57
+ metadata={
58
+ "help": (
59
+ "If provided, toggles custom weight initialization behavior for certain methods. OSF ignores this "
60
+ "flag but accepts it for config compatibility."
61
+ )
62
+ },
63
+ )
64
+ modules_to_save: Optional[list[str]] = field(
65
+ default=None,
66
+ metadata={"help": "Optional list of module names to save separately (ignored by OSF but accepted)."},
67
+ )
68
+ target_svd_config: Optional[dict[str, int]] = field(
69
+ default=None,
70
+ metadata={
71
+ "help": (
72
+ "Optional per-parameter SVD target rank mapping (e.g., {'lin0.weight': 8}). OSF currently ignores "
73
+ "this field but accepts it for forward compatibility."
74
+ )
75
+ },
76
+ )
77
+
78
+ def __post_init__(self):
79
+ super().__post_init__()
80
+ self.peft_type = PeftType.OSF
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/layer.py ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from __future__ import annotations
15
+
16
+ import warnings
17
+ from functools import partial
18
+ from typing import Any, Optional
19
+
20
+ import torch
21
+ import torch.nn as nn
22
+ import torch.nn.functional as F
23
+
24
+ from peft.tuners._buffer_dict import BufferDict
25
+ from peft.tuners.tuners_utils import BaseTunerLayer
26
+
27
+ from .utils import (
28
+ decompose_weight_matrix,
29
+ reconstruct_weight_matrix,
30
+ )
31
+
32
+
33
+ class OSFLayer(BaseTunerLayer):
34
+ # All names of layers that may contain (trainable) adapter weights
35
+ adapter_layer_names: tuple[str, ...] = ("osf_svd_params",)
36
+ # All names of other parameters that may contain adapter-related parameters
37
+ other_param_names: tuple[str, ...] = ("_osf_U_high", "_osf_S_high", "_osf_V_high")
38
+
39
+ def __init__(self, base_layer: nn.Module, **kwargs) -> None:
40
+ self.base_layer = base_layer
41
+ self.effective_rank = {}
42
+ # Map adapter_name -> ParameterDict{"U_low", "S_low", "V_low"}
43
+ self.osf_svd_params = nn.ModuleDict({})
44
+ # Store high-rank (frozen) components as buffers that track device moves
45
+ self._osf_U_high = BufferDict({})
46
+ self._osf_S_high = BufferDict({})
47
+ self._osf_V_high = BufferDict({})
48
+ # Track hook handles for cleanup
49
+ self.hook_handles = []
50
+ # Mark the weight as unmerged
51
+ self._disable_adapters = False
52
+ self.merged_adapters = []
53
+
54
+ # Get layer dimensions
55
+ base_layer = self.get_base_layer()
56
+ # Prefer the universally available weight shape when possible.
57
+ if (
58
+ hasattr(base_layer, "weight")
59
+ and isinstance(base_layer.weight, torch.Tensor)
60
+ and base_layer.weight.ndim == 2
61
+ ):
62
+ # For Linear-like modules, weight is [out_features, in_features]
63
+ out_features, in_features = base_layer.weight.shape
64
+ elif isinstance(base_layer, nn.Linear):
65
+ in_features, out_features = base_layer.in_features, base_layer.out_features
66
+ elif hasattr(base_layer, "infeatures") and hasattr(base_layer, "outfeatures"):
67
+ # QuantLinear
68
+ in_features, out_features = base_layer.infeatures, base_layer.outfeatures
69
+ elif hasattr(base_layer, "input_size") and hasattr(base_layer, "output_size"):
70
+ # Megatron ColumnParallelLinear, RowParallelLinear
71
+ in_features, out_features = base_layer.input_size, base_layer.output_size
72
+ elif hasattr(base_layer, "in_features") and hasattr(base_layer, "out_features"):
73
+ in_features, out_features = base_layer.in_features, base_layer.out_features
74
+ else:
75
+ in_features, out_features = None, None
76
+ warnings.warn(
77
+ f"Unsupported layer type '{type(base_layer)}' encountered; could not infer in/out features.",
78
+ UserWarning,
79
+ )
80
+
81
+ self.in_features = in_features
82
+ self.out_features = out_features
83
+
84
+ def update_layer(self, adapter_name: str, effective_rank: int, **kwargs):
85
+ """Update layer to add a new OSF adapter."""
86
+ if effective_rank <= 0:
87
+ raise ValueError(
88
+ f"`effective_rank` should be a positive integer value but the value passed is {effective_rank}"
89
+ )
90
+
91
+ # Store the rank for this adapter
92
+ self.effective_rank[adapter_name] = effective_rank
93
+
94
+ # Perform SVD decomposition on the base layer weight
95
+ base_layer = self.get_base_layer()
96
+ weight = base_layer.weight.data
97
+ svd_dict = decompose_weight_matrix(weight, top_k=effective_rank)
98
+
99
+ # Store high-rank (frozen) components as buffers
100
+ self._osf_U_high[adapter_name] = svd_dict["U_high"]
101
+ self._osf_S_high[adapter_name] = svd_dict["S_high"]
102
+ self._osf_V_high[adapter_name] = svd_dict["V_high"]
103
+
104
+ # Create ParameterDict for trainable low-rank components
105
+ svd_params = nn.ParameterDict(
106
+ {
107
+ "U_low": svd_dict["U_low"],
108
+ "S_low": svd_dict["S_low"],
109
+ "V_low": svd_dict["V_low"],
110
+ }
111
+ )
112
+ self.osf_svd_params[adapter_name] = svd_params
113
+
114
+ # Attach gradient hooks for orthogonal projection
115
+ self._attach_hooks(adapter_name)
116
+
117
+ # Set the adapter as active
118
+ self.set_adapter(self.active_adapters)
119
+
120
+ def _attach_hooks(self, adapter_name: str):
121
+ """Attach gradient hooks for the given adapter."""
122
+ if adapter_name not in self.osf_svd_params:
123
+ return
124
+
125
+ svd_module = self.osf_svd_params[adapter_name]
126
+
127
+ def hook(grad, name: str, adapter: str, layer: OSFLayer):
128
+ # Project gradient to be orthogonal to high-rank subspace for U_low/V_low
129
+ # Access buffers dynamically to ensure they're on the correct device
130
+ if name == "U_low":
131
+ U_high = layer._osf_U_high[adapter]
132
+ proj = U_high @ (U_high.transpose(0, 1) @ grad)
133
+ return grad - proj
134
+ elif name == "V_low":
135
+ V_high = layer._osf_V_high[adapter]
136
+ proj = (grad @ V_high.transpose(0, 1)) @ V_high
137
+ return grad - proj
138
+ return grad
139
+
140
+ # Store hook handles for later cleanup
141
+ handle_u = svd_module["U_low"].register_hook(partial(hook, name="U_low", adapter=adapter_name, layer=self))
142
+ handle_v = svd_module["V_low"].register_hook(partial(hook, name="V_low", adapter=adapter_name, layer=self))
143
+
144
+ self.hook_handles.extend([handle_u, handle_v])
145
+
146
+ def _detach_hooks(self):
147
+ """Remove all gradient hooks."""
148
+ for handle in self.hook_handles:
149
+ handle.remove()
150
+ self.hook_handles.clear()
151
+
152
+ def _reconstruct_weight(self, adapter_name: str) -> torch.Tensor:
153
+ """Reconstruct weight matrix from SVD components for given adapter."""
154
+ if adapter_name not in self.osf_svd_params:
155
+ return self.get_base_layer().weight
156
+
157
+ svd_module = self.osf_svd_params[adapter_name]
158
+ svd_dict = {
159
+ "U_high": self._osf_U_high[adapter_name],
160
+ "S_high": self._osf_S_high[adapter_name],
161
+ "V_high": self._osf_V_high[adapter_name],
162
+ "U_low": svd_module["U_low"],
163
+ "S_low": svd_module["S_low"],
164
+ "V_low": svd_module["V_low"],
165
+ }
166
+ return reconstruct_weight_matrix(svd_dict)
167
+
168
+ def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None:
169
+ """
170
+ Merge the active adapter weights into the base weights
171
+
172
+ Args:
173
+ safe_merge (`bool`, *optional*):
174
+ If True, the merge operation will be performed in a copy of the original weights and check for NaNs
175
+ before merging the weights. This is useful if you want to check if the merge operation will produce
176
+ NaNs. Defaults to `False`.
177
+ adapter_names (`list[str]`, *optional*):
178
+ The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults
179
+ to `None`.
180
+ """
181
+ if adapter_names is None:
182
+ adapter_names = self.active_adapters
183
+
184
+ for active_adapter in adapter_names:
185
+ if active_adapter in self.osf_svd_params.keys():
186
+ base_layer = self.get_base_layer()
187
+ if safe_merge:
188
+ # Note that safe_merge will be slower than the normal merge
189
+ # because of the copy operation.
190
+ orig_weight = base_layer.weight.data.clone()
191
+ new_weight = self._reconstruct_weight(active_adapter)
192
+
193
+ if not torch.isfinite(new_weight).all():
194
+ raise ValueError(
195
+ f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken"
196
+ )
197
+
198
+ base_layer.weight.data = new_weight.to(orig_weight.dtype)
199
+ else:
200
+ new_weight = self._reconstruct_weight(active_adapter)
201
+ base_layer.weight.data = new_weight
202
+
203
+ self.merged_adapters.append(active_adapter)
204
+
205
+ def unmerge(self) -> None:
206
+ """
207
+ This method unmerges all merged adapter layers from the base weights.
208
+ """
209
+ if not self.merged:
210
+ warnings.warn("Already unmerged. Nothing to do.")
211
+ return
212
+
213
+ # For OSF, unmerging means restoring the original weight
214
+ # Since we modify the weight in-place, we need to store the original weight
215
+ # This is a limitation of the current OSF implementation
216
+ warnings.warn("OSF does not support unmerging. Original weights are permanently modified.")
217
+
218
+ def __del__(self):
219
+ """Cleanup hooks on deletion."""
220
+ self._detach_hooks()
221
+
222
+
223
+ class Linear(nn.Module, OSFLayer):
224
+ # OSF implemented in a dense layer
225
+ def __init__(
226
+ self,
227
+ base_layer,
228
+ adapter_name: str,
229
+ effective_rank: int = None,
230
+ **kwargs,
231
+ ) -> None:
232
+ super().__init__()
233
+ OSFLayer.__init__(self, base_layer, **kwargs)
234
+
235
+ # Set default effective_rank if not provided
236
+ if effective_rank is None:
237
+ # Default to 50% of min dimension
238
+ effective_rank = min(self.in_features, self.out_features) // 2
239
+
240
+ self._active_adapter = adapter_name
241
+ self.update_layer(adapter_name, effective_rank, **kwargs)
242
+
243
+ def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor:
244
+ if self.disable_adapters:
245
+ result = self.base_layer(x, *args, **kwargs)
246
+ elif self.merged:
247
+ result = self.base_layer(x, *args, **kwargs)
248
+ else:
249
+ # Use reconstructed weight for forward pass
250
+ base_layer = self.get_base_layer()
251
+ bias = base_layer.bias
252
+
253
+ # Use the active adapter's reconstructed weight
254
+ active_adapter = self.active_adapters[0] if self.active_adapters else None
255
+ if active_adapter and active_adapter in self.osf_svd_params:
256
+ weight = self._reconstruct_weight(active_adapter)
257
+ orig_dtype = x.dtype # assume that the intended dtype is that of the input
258
+ x = self._cast_input_dtype(x, weight.dtype)
259
+ if bias is not None:
260
+ bias = bias.to(weight.dtype)
261
+ result = F.linear(x, weight, bias)
262
+ result = result.to(orig_dtype)
263
+ else:
264
+ result = self.base_layer(x, *args, **kwargs)
265
+
266
+ return result
267
+
268
+ def __repr__(self) -> str:
269
+ rep = super().__repr__()
270
+ return "osf." + rep
271
+
272
+
273
+ def dispatch_default(
274
+ target: torch.nn.Module,
275
+ adapter_name: str,
276
+ osf_config,
277
+ **kwargs,
278
+ ) -> Optional[torch.nn.Module]:
279
+ new_module = None
280
+
281
+ if isinstance(target, BaseTunerLayer):
282
+ target_base_layer = target.get_base_layer()
283
+ else:
284
+ target_base_layer = target
285
+
286
+ if isinstance(target_base_layer, torch.nn.Linear):
287
+ new_module = Linear(target, adapter_name, **kwargs)
288
+
289
+ return new_module
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/model.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import re
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+
8
+ from peft.tuners.tuners_utils import BaseTuner
9
+ from peft.utils.constants import TRANSFORMERS_MODELS_TO_OSF_TARGET_MODULES_MAPPING
10
+
11
+ from .layer import OSFLayer, dispatch_default
12
+
13
+
14
+ class OSFModel(BaseTuner):
15
+ """A minimal tuner implementing Orthogonal Subspace Fine-tuning."""
16
+
17
+ prefix: str = "osf_"
18
+ tuner_layer_cls = OSFLayer
19
+ target_module_mapping = TRANSFORMERS_MODELS_TO_OSF_TARGET_MODULES_MAPPING
20
+
21
+ def __init__(
22
+ self,
23
+ model,
24
+ config,
25
+ adapter_name,
26
+ low_cpu_mem_usage: bool = False,
27
+ state_dict: dict[str, torch.Tensor] | None = None,
28
+ ):
29
+ # Pass state_dict through for compatibility with BaseTuner
30
+ super().__init__(
31
+ model,
32
+ config,
33
+ adapter_name,
34
+ low_cpu_mem_usage=low_cpu_mem_usage,
35
+ state_dict=state_dict,
36
+ )
37
+
38
+ def __getattr__(self, name: str):
39
+ """Forward missing attributes to the wrapped base model.
40
+
41
+ This mirrors the behavior of other tuners (e.g., LoRA), ensuring attributes like `device` resolve to the
42
+ underlying transformers model.
43
+ """
44
+ try:
45
+ return super().__getattr__(name) # defer to nn.Module's logic
46
+ except AttributeError:
47
+ if name == "model": # avoid infinite recursion during init
48
+ raise
49
+ return getattr(self.model, name)
50
+
51
+ def _prepare_adapter_config(self, peft_config, model_config):
52
+ # If target_modules is unspecified, try mapping; else fall back to all linear layers for custom models
53
+ if peft_config.target_modules is None:
54
+ target_modules = self.target_module_mapping.get(model_config["model_type"])
55
+ if target_modules is not None:
56
+ peft_config = super()._prepare_adapter_config(peft_config, model_config)
57
+ else:
58
+ from peft.utils.constants import INCLUDE_LINEAR_LAYERS_SHORTHAND
59
+
60
+ peft_config.target_modules = INCLUDE_LINEAR_LAYERS_SHORTHAND
61
+ return peft_config
62
+
63
+ def _create_and_replace(
64
+ self,
65
+ osf_config,
66
+ adapter_name: str,
67
+ target: nn.Module,
68
+ target_name: str,
69
+ parent: nn.Module,
70
+ current_key: str,
71
+ *,
72
+ parameter_name: str | None = None,
73
+ ) -> None:
74
+ # OSF only works on 2D weight matrices
75
+ if not hasattr(target, "weight") or len(target.weight.shape) != 2:
76
+ return None
77
+
78
+ # Determine effective rank for this target (supports int or fractional in (0,1])
79
+ def _resolve_rank(value, min_dim: int) -> int:
80
+ if value is None:
81
+ return max(min_dim // 2, 0)
82
+ # floats in (0,1] => fraction of min_dim
83
+ if isinstance(value, float) and 0 < value <= 1:
84
+ r = int(min_dim * value)
85
+ else:
86
+ r = int(value)
87
+ return max(min(min_dim, r), 0)
88
+
89
+ min_dim = min(target.weight.shape)
90
+ effective_rank = _resolve_rank(getattr(osf_config, "effective_rank", None), min_dim)
91
+
92
+ # Check for per-module rank overrides (allow int or fractional)
93
+ if hasattr(osf_config, "rank_pattern") and osf_config.rank_pattern:
94
+ for pattern, rank in osf_config.rank_pattern.items():
95
+ if re.search(pattern, current_key):
96
+ effective_rank = _resolve_rank(rank, min_dim)
97
+ break
98
+
99
+ kwargs = {
100
+ "effective_rank": effective_rank,
101
+ }
102
+
103
+ # Create a new or update an existing OSF layer in place
104
+ if isinstance(target, OSFLayer):
105
+ target.update_layer(adapter_name, **kwargs)
106
+ else:
107
+ new_module = dispatch_default(target, adapter_name, osf_config, **kwargs)
108
+ if new_module is None:
109
+ return None
110
+ # If adding an additional adapter, keep it frozen initially
111
+ if adapter_name not in self.active_adapters:
112
+ new_module.requires_grad_(False)
113
+ self._replace_module(parent, target_name, new_module, target)
114
+
115
+ def _mark_only_adapters_as_trainable(self, model: nn.Module) -> None:
116
+ for n, p in model.named_parameters():
117
+ # Only OSF adapter parameters (in osf_svd_params) should be trainable
118
+ if "osf_svd_params" not in n:
119
+ p.requires_grad = False
120
+
121
+ # Use BaseTuner's merge and merge_and_unload implementations.
122
+ # Explicitly disallow unmerging at the model level for OSF.
123
+ def unmerge_adapter(self, *args, **kwargs):
124
+ raise NotImplementedError("OSF models do not support unmerging")
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/utils.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Utilities for Orthogonal Subspace Learning with Adaptive OSF."""
15
+
16
+ from __future__ import annotations
17
+
18
+ from typing import Any
19
+
20
+ import torch
21
+ import torch.distributed as dist
22
+ from torch import nn
23
+
24
+
25
+ # Note: OSF now relies on OSFLayer + BaseTuner; no model-level helpers required here.
26
+
27
+
28
+ __all__ = [
29
+ "decompose_weight_matrix",
30
+ "project_gradient_to_orthogonal_space",
31
+ "reconstruct_weight_matrix",
32
+ ]
33
+
34
+
35
+ def _wait_if_async(tensor):
36
+ """Wait for AsyncCollectiveTensor if needed, otherwise return tensor as-is."""
37
+ if hasattr(tensor, "wait"):
38
+ return tensor.wait()
39
+ return tensor
40
+
41
+
42
+ def decompose_weight_matrix(weight: torch.Tensor, top_k: int) -> dict[str, Any]:
43
+ """Perform an SVD of ``weight`` and split it into frozen and trainable parts."""
44
+ device_local = weight.device
45
+ orig_dtype = weight.dtype
46
+ W = weight.to(torch.float32)
47
+ U, S, Vt = torch.linalg.svd(W, full_matrices=False)
48
+ k = min(top_k, S.shape[0])
49
+
50
+ svd = {
51
+ "U_high": U[:, :k].contiguous().detach().to(device=device_local, dtype=orig_dtype),
52
+ "S_high": S[:k].contiguous().detach().to(device=device_local, dtype=orig_dtype),
53
+ "V_high": Vt[:k, :].contiguous().detach().to(device=device_local, dtype=orig_dtype),
54
+ "U_low": nn.Parameter(U[:, k:].contiguous().detach().to(device=device_local, dtype=orig_dtype)),
55
+ "S_low": nn.Parameter(S[k:].contiguous().detach().to(device=device_local, dtype=orig_dtype)),
56
+ "V_low": nn.Parameter(Vt[k:, :].contiguous().detach().to(device=device_local, dtype=orig_dtype)),
57
+ "rank_high": k,
58
+ }
59
+ return svd
60
+
61
+
62
+ def reconstruct_weight_matrix(svd_dict: dict[str, torch.Tensor]) -> torch.Tensor:
63
+ """Reconstruct a weight matrix from its SVD components."""
64
+ U_high = svd_dict["U_high"]
65
+ S_high = svd_dict["S_high"]
66
+ V_high = svd_dict["V_high"]
67
+ U_low = svd_dict["U_low"]
68
+ S_low = svd_dict["S_low"]
69
+ V_low = svd_dict["V_low"]
70
+
71
+ high_part = (
72
+ torch.mm(U_high * S_high.unsqueeze(0), V_high)
73
+ if U_high.numel() > 0 and S_high.numel() > 0
74
+ else torch.zeros(U_low.size(0), V_low.size(1), device=U_high.device)
75
+ )
76
+ low_part = (
77
+ torch.mm(U_low * S_low.unsqueeze(0), V_low)
78
+ if U_low.numel() > 0 and S_low.numel() > 0
79
+ else torch.zeros(U_high.size(0), V_high.size(1), device=U_low.device)
80
+ )
81
+ return high_part + low_part
82
+
83
+
84
+ def project_gradient_to_orthogonal_space(svd_dict: dict[str, Any]) -> None:
85
+ """Project gradients of ``U_low`` and ``V_low`` to be orthogonal to the high rank space."""
86
+ if svd_dict["U_low"].grad is None and svd_dict["S_low"].grad is None and svd_dict["V_low"].grad is None:
87
+ return
88
+
89
+ U_high = svd_dict["U_high"]
90
+ V_high = svd_dict["V_high"]
91
+
92
+ # Project U_low gradients to space orthogonal to U_high
93
+ if svd_dict["U_low"].grad is not None:
94
+ dU = svd_dict["U_low"].grad
95
+ # Support distributed tensors by operating on the local shard
96
+ local_U_high = getattr(U_high, "to_local", lambda: U_high)()
97
+ local_dU = getattr(dU, "to_local", lambda: dU)()
98
+
99
+ # Perform projection computation using memory-efficient operations
100
+ # Memory-optimized projection: dU = dU - U_high @ (U_high.T @ dU)
101
+ # Use addmm_ for efficient in-place operation
102
+ # Compute local contribution to (U_high^T @ dU); all-reduce to get global projection
103
+ proj_coeff = torch.mm(local_U_high.transpose(0, 1), local_dU)
104
+ if dist.is_available() and dist.is_initialized() and dist.get_world_size() > 1:
105
+ dist.all_reduce(proj_coeff, op=dist.ReduceOp.SUM)
106
+ # Apply projection using only local rows of U_high
107
+ local_dU.addmm_(local_U_high, proj_coeff, alpha=-1.0)
108
+
109
+ if hasattr(dU, "_local_tensor"):
110
+ dU._local_tensor.copy_(local_dU)
111
+ else:
112
+ dU.copy_(local_dU)
113
+
114
+ # Repeat projection for V_low using V_high
115
+ if svd_dict["V_low"].grad is not None:
116
+ dV = svd_dict["V_low"].grad
117
+ local_V_high = getattr(V_high, "to_local", lambda: V_high)()
118
+ local_dV = getattr(dV, "to_local", lambda: dV)()
119
+
120
+ # Compute Gram matrix G = V_high^T @ V_high for global projection across row-sharded V_high
121
+ # Assumes column dimension is consistent across ranks (row sharding over singular vectors)
122
+ G_local = torch.mm(local_V_high.transpose(0, 1), local_V_high)
123
+ if dist.is_available() and dist.is_initialized() and dist.get_world_size() > 1:
124
+ dist.all_reduce(G_local, op=dist.ReduceOp.SUM)
125
+
126
+ # Apply projection: dV = dV - dV @ G (use local shard of dV)
127
+ update = torch.mm(local_dV, G_local)
128
+ local_dV.add_(update, alpha=-1.0)
129
+
130
+ if hasattr(dV, "_local_tensor"):
131
+ dV._local_tensor.copy_(local_dV)
132
+ else:
133
+ dV.copy_(local_dV)