AdithyaSK HF Staff commited on
Commit
98ec3d7
·
verified ·
1 Parent(s): e047f13

Stage Harbor release files 64501-65000

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/oft/model.py +200 -0
  2. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/osf/__init__.py +15 -0
  3. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/osf/config.py +80 -0
  4. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/osf/layer.py +289 -0
  5. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/osf/model.py +124 -0
  6. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/osf/utils.py +133 -0
  7. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/p_tuning/__init__.py +23 -0
  8. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/p_tuning/config.py +60 -0
  9. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/p_tuning/model.py +130 -0
  10. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/poly/__init__.py +24 -0
  11. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/poly/config.py +103 -0
  12. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/poly/layer.py +165 -0
  13. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/poly/model.py +104 -0
  14. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/poly/router.py +81 -0
  15. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/prefix_tuning/__init__.py +23 -0
  16. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/prefix_tuning/config.py +42 -0
  17. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/prefix_tuning/model.py +101 -0
  18. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/prompt_tuning/__init__.py +23 -0
  19. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/prompt_tuning/config.py +91 -0
  20. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/prompt_tuning/model.py +105 -0
  21. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/randlora/__init__.py +40 -0
  22. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/randlora/bnb.py +456 -0
  23. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/randlora/config.py +199 -0
  24. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/randlora/layer.py +353 -0
  25. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/randlora/model.py +356 -0
  26. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/road/__init__.py +47 -0
  27. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/road/bnb.py +407 -0
  28. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/road/config.py +126 -0
  29. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/road/layer.py +418 -0
  30. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/road/model.py +164 -0
  31. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/shira/__init__.py +27 -0
  32. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/shira/config.py +129 -0
  33. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/shira/layer.py +221 -0
  34. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/shira/mask_functions.py +72 -0
  35. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/shira/model.py +142 -0
  36. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/trainable_tokens/__init__.py +33 -0
  37. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/trainable_tokens/config.py +89 -0
  38. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/trainable_tokens/layer.py +262 -0
  39. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/trainable_tokens/model.py +153 -0
  40. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/tuners_utils.py +2071 -0
  41. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/vblora/__init__.py +24 -0
  42. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/vblora/config.py +196 -0
  43. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/vblora/layer.py +258 -0
  44. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/vblora/model.py +209 -0
  45. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/vera/__init__.py +40 -0
  46. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/vera/bnb.py +411 -0
  47. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/vera/config.py +162 -0
  48. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/vera/layer.py +294 -0
  49. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/vera/model.py +294 -0
  50. tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/waveft/__init__.py +24 -0
tasks/tasksmith-9aea936e30e4/tests/source/src/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")
tasks/tasksmith-9aea936e30e4/tests/source/src/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
+ )
tasks/tasksmith-9aea936e30e4/tests/source/src/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
tasks/tasksmith-9aea936e30e4/tests/source/src/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
tasks/tasksmith-9aea936e30e4/tests/source/src/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 getattr(peft_config, "target_modules", None) is None:
54
+ model_type = model_config.get("model_type")
55
+ if model_type in self.target_module_mapping:
56
+ peft_config.target_modules = set(self.target_module_mapping[model_type])
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")
tasks/tasksmith-9aea936e30e4/tests/source/src/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)
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/p_tuning/__init__.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 PromptEncoderConfig, PromptEncoderReparameterizationType
18
+ from .model import PromptEncoder
19
+
20
+
21
+ __all__ = ["PromptEncoder", "PromptEncoderConfig", "PromptEncoderReparameterizationType"]
22
+
23
+ register_peft_method(name="p_tuning", config_cls=PromptEncoderConfig, model_cls=PromptEncoder)
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/p_tuning/config.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 Union
18
+
19
+ from peft.config import PromptLearningConfig
20
+ from peft.utils import PeftType
21
+
22
+
23
+ class PromptEncoderReparameterizationType(str, enum.Enum):
24
+ MLP = "MLP"
25
+ LSTM = "LSTM"
26
+
27
+
28
+ @dataclass
29
+ class PromptEncoderConfig(PromptLearningConfig):
30
+ """
31
+ This is the configuration class to store the configuration of a [`PromptEncoder`].
32
+
33
+ Args:
34
+ encoder_reparameterization_type (Union[[`PromptEncoderReparameterizationType`], `str`]):
35
+ The type of reparameterization to use.
36
+ encoder_hidden_size (`int`): The hidden size of the prompt encoder.
37
+ encoder_num_layers (`int`): The number of layers of the prompt encoder.
38
+ encoder_dropout (`float`): The dropout probability of the prompt encoder.
39
+ """
40
+
41
+ encoder_reparameterization_type: Union[str, PromptEncoderReparameterizationType] = field(
42
+ default=PromptEncoderReparameterizationType.MLP,
43
+ metadata={"help": "How to reparameterize the prompt encoder"},
44
+ )
45
+ encoder_hidden_size: int = field(
46
+ default=None,
47
+ metadata={"help": "The hidden size of the prompt encoder"},
48
+ )
49
+ encoder_num_layers: int = field(
50
+ default=2,
51
+ metadata={"help": "The number of layers of the prompt encoder"},
52
+ )
53
+ encoder_dropout: float = field(
54
+ default=0.0,
55
+ metadata={"help": "The dropout of the prompt encoder"},
56
+ )
57
+
58
+ def __post_init__(self):
59
+ super().__post_init__()
60
+ self.peft_type = PeftType.P_TUNING
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/p_tuning/model.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Based on https://github.com/NVIDIA/NeMo/blob/main/nemo/collections/nlp/modules/common/prompt_encoder.py
16
+ # with some refactor
17
+ import warnings
18
+
19
+ import torch
20
+
21
+ from .config import PromptEncoderConfig, PromptEncoderReparameterizationType
22
+
23
+
24
+ class PromptEncoder(torch.nn.Module):
25
+ """
26
+ The prompt encoder network that is used to generate the virtual token embeddings for p-tuning.
27
+
28
+ Args:
29
+ config ([`PromptEncoderConfig`]): The configuration of the prompt encoder.
30
+
31
+ Example:
32
+
33
+ ```py
34
+ >>> from peft import PromptEncoder, PromptEncoderConfig
35
+
36
+ >>> config = PromptEncoderConfig(
37
+ ... peft_type="P_TUNING",
38
+ ... task_type="SEQ_2_SEQ_LM",
39
+ ... num_virtual_tokens=20,
40
+ ... token_dim=768,
41
+ ... num_transformer_submodules=1,
42
+ ... num_attention_heads=12,
43
+ ... num_layers=12,
44
+ ... encoder_reparameterization_type="MLP",
45
+ ... encoder_hidden_size=768,
46
+ ... )
47
+
48
+ >>> prompt_encoder = PromptEncoder(config)
49
+ ```
50
+
51
+ **Attributes**:
52
+ - **embedding** (`torch.nn.Embedding`) -- The embedding layer of the prompt encoder.
53
+ - **mlp_head** (`torch.nn.Sequential`) -- The MLP head of the prompt encoder if `inference_mode=False`.
54
+ - **lstm_head** (`torch.nn.LSTM`) -- The LSTM head of the prompt encoder if `inference_mode=False` and
55
+ `encoder_reparameterization_type="LSTM"`.
56
+ - **token_dim** (`int`) -- The hidden embedding dimension of the base transformer model.
57
+ - **input_size** (`int`) -- The input size of the prompt encoder.
58
+ - **output_size** (`int`) -- The output size of the prompt encoder.
59
+ - **hidden_size** (`int`) -- The hidden size of the prompt encoder.
60
+ - **total_virtual_tokens** (`int`): The total number of virtual tokens of the
61
+ prompt encoder.
62
+ - **encoder_type** (Union[[`PromptEncoderReparameterizationType`], `str`]): The encoder type of the prompt
63
+ encoder.
64
+
65
+
66
+ Input shape: (`batch_size`, `total_virtual_tokens`)
67
+
68
+ Output shape: (`batch_size`, `total_virtual_tokens`, `token_dim`)
69
+ """
70
+
71
+ def __init__(self, config):
72
+ super().__init__()
73
+ self.token_dim = config.token_dim
74
+ self.input_size = self.token_dim
75
+ self.output_size = self.token_dim
76
+ self.hidden_size = config.encoder_hidden_size
77
+ self.total_virtual_tokens = config.num_virtual_tokens * config.num_transformer_submodules
78
+ self.encoder_type = config.encoder_reparameterization_type
79
+
80
+ # embedding
81
+ self.embedding = torch.nn.Embedding(self.total_virtual_tokens, self.token_dim)
82
+ if not config.inference_mode:
83
+ if self.encoder_type == PromptEncoderReparameterizationType.LSTM:
84
+ lstm_dropout = config.encoder_dropout
85
+ num_layers = config.encoder_num_layers
86
+ # LSTM
87
+ self.lstm_head = torch.nn.LSTM(
88
+ input_size=self.input_size,
89
+ hidden_size=self.hidden_size,
90
+ num_layers=num_layers,
91
+ dropout=lstm_dropout,
92
+ bidirectional=True,
93
+ batch_first=True,
94
+ )
95
+
96
+ self.mlp_head = torch.nn.Sequential(
97
+ torch.nn.Linear(self.hidden_size * 2, self.hidden_size * 2),
98
+ torch.nn.ReLU(),
99
+ torch.nn.Linear(self.hidden_size * 2, self.output_size),
100
+ )
101
+
102
+ elif self.encoder_type == PromptEncoderReparameterizationType.MLP:
103
+ encoder_num_layers_default = PromptEncoderConfig.encoder_num_layers
104
+ if config.encoder_num_layers != encoder_num_layers_default:
105
+ warnings.warn(
106
+ f"for {self.encoder_type.value}, the argument `encoder_num_layers` is ignored. "
107
+ f"Exactly {encoder_num_layers_default} MLP layers are used."
108
+ )
109
+ layers = [
110
+ torch.nn.Linear(self.input_size, self.hidden_size),
111
+ torch.nn.ReLU(),
112
+ torch.nn.Linear(self.hidden_size, self.hidden_size),
113
+ torch.nn.ReLU(),
114
+ torch.nn.Linear(self.hidden_size, self.output_size),
115
+ ]
116
+ self.mlp_head = torch.nn.Sequential(*layers)
117
+
118
+ else:
119
+ raise ValueError("Prompt encoder type not recognized. Please use one of MLP (recommended) or LSTM.")
120
+
121
+ def forward(self, indices):
122
+ input_embeds = self.embedding(indices)
123
+ if self.encoder_type == PromptEncoderReparameterizationType.LSTM:
124
+ output_embeds = self.mlp_head(self.lstm_head(input_embeds)[0])
125
+ elif self.encoder_type == PromptEncoderReparameterizationType.MLP:
126
+ output_embeds = self.mlp_head(input_embeds)
127
+ else:
128
+ raise ValueError("Prompt encoder type not recognized. Please use one of MLP (recommended) or LSTM.")
129
+
130
+ return output_embeds
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/poly/__init__.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 PolyConfig
18
+ from .layer import Linear, PolyLayer
19
+ from .model import PolyModel
20
+
21
+
22
+ __all__ = ["Linear", "PolyConfig", "PolyLayer", "PolyModel"]
23
+
24
+ register_peft_method(name="poly", config_cls=PolyConfig, model_cls=PolyModel)
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/poly/config.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from dataclasses import dataclass, field
18
+ from typing import Literal, Optional, Union
19
+
20
+ from peft.config import PeftConfig
21
+ from peft.utils import PeftType
22
+
23
+
24
+ @dataclass
25
+ class PolyConfig(PeftConfig):
26
+ """
27
+ This is the configuration class to store the configuration of a [`PolyModel`].
28
+ - [Polytropon (Poly)](https://huggingface.co/papers/2202.13914)
29
+ - [Multi-Head Routing (MHR)](https://huggingface.co/papers/2211.03831)
30
+
31
+ Args:
32
+ r (`int`): Attention dimension of each Lora in Poly.
33
+ target_modules (`Union[List[str],str]`): The names of the modules to apply Poly to.
34
+ exclude_modules (`Optional[Union[List[str], str]]`):
35
+ The names of the modules to not apply the adapter. When passing a string, a regex match will be performed.
36
+ When passing a list of strings, either an exact match will be performed or it is checked if the name of the
37
+ module ends with any of the passed strings.
38
+ modules_to_save (`List[str]`): List of modules apart from Poly layers to be set as trainable
39
+ and saved in the final checkpoint.
40
+ init_weights (bool): Whether to perform initialization of Poly weights.
41
+ poly_type (`Literal["poly"]`): The variant of the Poly module to use. Currently, only "poly"
42
+ is supported.
43
+ n_tasks (`int`): The number of tasks in a multitasking scenario.
44
+ n_skills (`int`): The number of skills (LoRA) in each Poly layer.
45
+ n_splits (`int`): The number of splits within each LoRA of a Poly layer. A value greater
46
+ than 1 indicates the use of Multi-Head Routing (MHR).
47
+ """
48
+
49
+ r: int = field(default=8, metadata={"help": "Lora attention dimension"})
50
+ target_modules: Optional[Union[list[str], str]] = field(
51
+ default=None,
52
+ metadata={
53
+ "help": "List of module names or regex expression of the module names to replace with Poly."
54
+ "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$' "
55
+ },
56
+ )
57
+ exclude_modules: Optional[Union[list[str], str]] = field(
58
+ default=None,
59
+ metadata={"help": "List of module names or regex expression of the module names to exclude from Poly."},
60
+ )
61
+ modules_to_save: Optional[list[str]] = field(
62
+ default=None,
63
+ metadata={
64
+ "help": "List of modules apart from Poly layers to be set as trainable and saved in the final checkpoint. "
65
+ "For example, in Sequence Classification or Token Classification tasks, "
66
+ "the final layer `classifier/score` are randomly initialized and as such need to be trainable and saved."
67
+ },
68
+ )
69
+ init_weights: bool = field(
70
+ default=True,
71
+ metadata={
72
+ "help": (
73
+ "Whether to initialize the weights of the Poly layers with their default initialization. Don't change "
74
+ "this setting, except if you know exactly what you're doing."
75
+ ),
76
+ },
77
+ )
78
+ poly_type: Literal["poly"] = field(
79
+ default="poly",
80
+ metadata={"help": 'Type of Poly modules to be used. Currently only "poly" is supported.'},
81
+ )
82
+ n_tasks: int = field(
83
+ default=1,
84
+ metadata={"help": "Number of tasks in multitasking scenario."},
85
+ )
86
+ n_skills: int = field(
87
+ default=4,
88
+ metadata={"help": "Number of skills (LoRA) in each Poly layer."},
89
+ )
90
+ n_splits: int = field(
91
+ default=1,
92
+ metadata={"help": "Number of splits within each LoRA of a Poly layer."},
93
+ )
94
+
95
+ def __post_init__(self):
96
+ super().__post_init__()
97
+ self.peft_type = PeftType.POLY
98
+ self.target_modules = (
99
+ set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules
100
+ )
101
+ self.exclude_modules = (
102
+ set(self.exclude_modules) if isinstance(self.exclude_modules, list) else self.exclude_modules
103
+ )
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/poly/layer.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 math
16
+ from typing import Any
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+
21
+ from peft.tuners.tuners_utils import BaseTunerLayer
22
+
23
+ from .config import PolyConfig
24
+ from .router import get_router
25
+
26
+
27
+ class PolyLayer(BaseTunerLayer):
28
+ # All names of layers that may contain (trainable) adapter weights
29
+ adapter_layer_names = ("poly_lora_A", "poly_lora_B", "poly_router")
30
+ # All names of other parameters that may contain adapter-related parameters
31
+ other_param_names = ("r", "n_tasks", "n_skills", "n_splits")
32
+
33
+ def __init__(self, base_layer: nn.Module, **kwargs):
34
+ self.base_layer = base_layer
35
+ self.r = {}
36
+ self.n_tasks = {}
37
+ self.n_skills = {}
38
+ self.n_splits = {}
39
+ self.poly_type = {}
40
+ self.poly_router = nn.ModuleDict()
41
+ self.poly_lora_A = nn.ParameterDict()
42
+ self.poly_lora_B = nn.ParameterDict()
43
+ self.kwargs = kwargs
44
+
45
+ base_layer = self.get_base_layer()
46
+ if isinstance(base_layer, nn.Linear):
47
+ in_features, out_features = base_layer.in_features, base_layer.out_features
48
+ else:
49
+ raise ValueError(f"Unsupported layer type {type(base_layer)}")
50
+
51
+ self.in_features = in_features
52
+ self.out_features = out_features
53
+
54
+ def update_layer(self, adapter_name, poly_config, inference_mode: bool = False, **kwargs):
55
+ if poly_config.r <= 0:
56
+ raise ValueError(f"`r` should be a positive integer value but the value passed is {poly_config.r}")
57
+
58
+ self.r[adapter_name] = poly_config.r
59
+ self.n_tasks[adapter_name] = poly_config.n_tasks
60
+ self.n_skills[adapter_name] = poly_config.n_skills
61
+ self.n_splits[adapter_name] = poly_config.n_splits
62
+ self.poly_type[adapter_name] = poly_config.poly_type
63
+
64
+ self.poly_lora_A[adapter_name] = nn.Parameter(
65
+ torch.empty(
66
+ poly_config.n_splits,
67
+ poly_config.n_skills,
68
+ self.in_features // poly_config.n_splits,
69
+ poly_config.r,
70
+ )
71
+ )
72
+ self.poly_lora_B[adapter_name] = nn.Parameter(
73
+ torch.empty(
74
+ poly_config.n_splits,
75
+ poly_config.n_skills,
76
+ poly_config.r,
77
+ self.out_features // poly_config.n_splits,
78
+ )
79
+ )
80
+ self.poly_router[adapter_name] = get_router(poly_config)
81
+
82
+ self.reset_poly_parameters(adapter_name, init_weights=poly_config.init_weights)
83
+
84
+ self._move_adapter_to_device_of_base_layer(adapter_name)
85
+ self.set_adapter(self.active_adapters, inference_mode=inference_mode)
86
+
87
+ def reset_poly_parameters(self, adapter_name, init_weights):
88
+ if adapter_name in self.poly_lora_A.keys():
89
+ # initialize A the same way as the default for nn.Linear
90
+ # https://github.com/microsoft/mttl/blob/ce4ca51dbca73be656feb9b3e5233633e3c5dec7/mttl/models/poly.py#L269
91
+ n_splits, n_skills, d, r = self.poly_lora_A[adapter_name].shape
92
+ for skill in range(n_skills):
93
+ for split in range(n_splits):
94
+ param = torch.empty((r, d))
95
+ torch.nn.init.kaiming_uniform_(param, a=math.sqrt(5))
96
+ self.poly_lora_A[adapter_name].data[split, skill, :, :] = param.T
97
+
98
+ if init_weights:
99
+ # initialize B to zero
100
+ torch.nn.init.zeros_(self.poly_lora_B[adapter_name])
101
+ else:
102
+ # initialize B the same way as the default for nn.Linear
103
+ n_splits, n_skills, r, d = self.poly_lora_B[adapter_name].shape
104
+ for skill in range(n_skills):
105
+ for split in range(n_splits):
106
+ param = torch.empty((d, r))
107
+ torch.nn.init.kaiming_uniform_(param, a=math.sqrt(5))
108
+ self.poly_lora_B[adapter_name].data[split, skill, :, :] = param.T
109
+
110
+ # initialized router
111
+ self.poly_router[adapter_name].reset()
112
+
113
+
114
+ class Linear(nn.Module, PolyLayer):
115
+ # Lora implemented in a dense layer
116
+ def __init__(
117
+ self,
118
+ base_layer,
119
+ adapter_name: str,
120
+ poly_config: PolyConfig,
121
+ **kwargs,
122
+ ) -> None:
123
+ super().__init__()
124
+ PolyLayer.__init__(self, base_layer, **kwargs)
125
+
126
+ self._active_adapter = adapter_name
127
+ self.update_layer(adapter_name, poly_config)
128
+
129
+ def forward(self, x: torch.Tensor, *args: Any, task_ids: torch.Tensor = None, **kwargs: Any) -> torch.Tensor:
130
+ previous_dtype = x.dtype
131
+ if self.disable_adapters:
132
+ result = self.base_layer(x, *args, **kwargs)
133
+ else:
134
+ result = self.base_layer(x, *args, **kwargs)
135
+ for active_adapter in self.active_adapters:
136
+ if active_adapter not in self.poly_lora_A.keys():
137
+ continue
138
+
139
+ r = self.r[active_adapter]
140
+ poly_router = self.poly_router[active_adapter]
141
+ poly_lora_A = self.poly_lora_A[active_adapter]
142
+ poly_lora_B = self.poly_lora_B[active_adapter]
143
+
144
+ # Combine the output of LoRAs
145
+ # https://github.com/microsoft/mttl/blob/ce4ca51dbca73be656feb9b3e5233633e3c5dec7/mttl/models/poly.py#L293
146
+ mixing_weights = poly_router(task_ids=task_ids, input_ids=x)
147
+ bs, n_splits, n_skills = mixing_weights.size()
148
+
149
+ # A is n_splits, n_skills, D // n_splits, rank
150
+ # we want bs, n_splits, D // n_splits, rank
151
+ A = torch.einsum("bqs,qsdr->bqdr", (mixing_weights, poly_lora_A))
152
+ B = torch.einsum("bqs,qsrd->bqrd", (mixing_weights, poly_lora_B))
153
+
154
+ A = A.reshape(bs, self.in_features, r)
155
+ B = B.transpose(1, 2).reshape(bs, r, self.out_features)
156
+
157
+ x = x.to(A.dtype)
158
+ result += x.bmm(A).bmm(B) / r
159
+
160
+ result = result.to(previous_dtype)
161
+ return result
162
+
163
+ def __repr__(self) -> str:
164
+ rep = super().__repr__()
165
+ return "poly." + rep
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/poly/model.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 contextlib import contextmanager
16
+ from typing import Any
17
+
18
+ import torch
19
+ from torch import nn
20
+
21
+ from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer
22
+ from peft.utils import TRANSFORMERS_MODELS_TO_POLY_TARGET_MODULES_MAPPING
23
+
24
+ from .config import PolyConfig
25
+ from .layer import Linear, PolyLayer
26
+
27
+
28
+ class PolyModel(BaseTuner):
29
+ prefix: str = "poly_"
30
+ tuner_layer_cls = PolyLayer
31
+ target_module_mapping = TRANSFORMERS_MODELS_TO_POLY_TARGET_MODULES_MAPPING
32
+
33
+ def _create_and_replace(
34
+ self,
35
+ poly_config: PolyConfig,
36
+ adapter_name: str,
37
+ target: nn.Module,
38
+ target_name: str,
39
+ parent: nn.Module,
40
+ **optional_kwargs: Any,
41
+ ):
42
+ if isinstance(target, PolyLayer):
43
+ target.update_layer(adapter_name, poly_config)
44
+ else:
45
+ new_module = self._create_new_module(
46
+ poly_config,
47
+ adapter_name,
48
+ target,
49
+ )
50
+ if adapter_name not in self.active_adapters:
51
+ # adding an additional adapter: it is not automatically trainable
52
+ new_module.requires_grad_(False)
53
+ self._replace_module(parent, target_name, new_module, target)
54
+
55
+ @staticmethod
56
+ def _create_new_module(poly_config, adapter_name, target, **kwargs):
57
+ if isinstance(target, BaseTunerLayer):
58
+ target_base_layer = target.get_base_layer()
59
+ else:
60
+ target_base_layer = target
61
+
62
+ if isinstance(target_base_layer, torch.nn.Linear):
63
+ return Linear(target, adapter_name, poly_config, **kwargs)
64
+ else:
65
+ raise ValueError(
66
+ f"Target module {target} is not supported. Currently, only the following modules are supported: "
67
+ "`torch.nn.Linear`."
68
+ )
69
+
70
+ def _register_pre_hooks(self, task_ids):
71
+ """Helper method to register pre hooks."""
72
+ if task_ids is None:
73
+ return []
74
+
75
+ def pre_hook(_, args, kwargs):
76
+ kwargs["task_ids"] = task_ids
77
+ return args, kwargs
78
+
79
+ handles = []
80
+
81
+ for module in self.model.modules():
82
+ if isinstance(module, Linear):
83
+ handle = module.register_forward_pre_hook(pre_hook, with_kwargs=True)
84
+ handles.append(handle)
85
+
86
+ return handles
87
+
88
+ @contextmanager
89
+ def _manage_pre_hooks(self, task_ids):
90
+ """Context manager to handle the lifecycle of pre hooks."""
91
+ handles = self._register_pre_hooks(task_ids)
92
+ try:
93
+ yield
94
+ finally:
95
+ for handle in handles:
96
+ handle.remove()
97
+
98
+ def forward(self, *args, task_ids=None, **kwargs):
99
+ with self._manage_pre_hooks(task_ids):
100
+ return self.model(*args, **kwargs)
101
+
102
+ def generate(self, *args, task_ids=None, **kwargs):
103
+ with self._manage_pre_hooks(task_ids):
104
+ return self.model.generate(*args, **kwargs)
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/poly/router.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 abc import ABC, abstractmethod
16
+
17
+ import torch
18
+ from torch import nn
19
+ from torch.distributions.relaxed_bernoulli import RelaxedBernoulli
20
+
21
+ from .config import PolyConfig
22
+
23
+
24
+ EPS = 1e-12
25
+
26
+
27
+ def get_router(poly_config: PolyConfig) -> nn.Module:
28
+ if poly_config.poly_type == "poly":
29
+ return PolyRouter(poly_config)
30
+ else:
31
+ raise ValueError(
32
+ f"Unsupported poly_type: {poly_config.poly_type}. "
33
+ "Currently, only the following types are supported: "
34
+ "`poly`."
35
+ )
36
+
37
+
38
+ class Router(nn.Module, ABC):
39
+ @abstractmethod
40
+ def reset(self): ...
41
+
42
+ @abstractmethod
43
+ def forward(self, task_ids: torch.Tensor, input_ids: torch.Tensor): ...
44
+
45
+
46
+ class PolyRouter(Router):
47
+ # It's a simplified implementation of
48
+ # https://github.com/microsoft/mttl/blob/ce4ca51dbca73be656feb9b3e5233633e3c5dec7/mttl/models/poly.py#L138
49
+ def __init__(self, poly_config: PolyConfig):
50
+ super().__init__()
51
+
52
+ self.poly_type = poly_config.poly_type
53
+ self.n_tasks = poly_config.n_tasks
54
+ self.n_skills = poly_config.n_skills
55
+ self.n_splits = poly_config.n_splits
56
+
57
+ self.module_logits = nn.Parameter(torch.empty((self.n_tasks, self.n_splits * self.n_skills)))
58
+
59
+ def reset(self):
60
+ torch.nn.init.uniform_(self.module_logits, -1e-3, 1e-3)
61
+
62
+ def forward(self, task_ids: torch.Tensor, input_ids: torch.Tensor):
63
+ if task_ids is None:
64
+ raise ValueError("task_ids should not be None.")
65
+ if task_ids.max().item() >= self.n_tasks:
66
+ raise ValueError(f"Only {self.n_tasks} tasks available. Found task id = {task_ids.max().item()}")
67
+
68
+ # move task id to input's device
69
+ task_ids = task_ids.to(self.module_logits.device)
70
+
71
+ module_logits = self.module_logits[task_ids]
72
+ module_logits = module_logits.view(-1, self.n_splits, self.n_skills)
73
+
74
+ if self.training:
75
+ module_logits = RelaxedBernoulli(temperature=1.0, logits=module_logits).rsample()
76
+ else:
77
+ module_logits = torch.sigmoid(module_logits)
78
+
79
+ module_weights = module_logits / (module_logits.sum(dim=-1, keepdim=True) + EPS)
80
+
81
+ return module_weights
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/prefix_tuning/__init__.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 PrefixTuningConfig
18
+ from .model import PrefixEncoder
19
+
20
+
21
+ __all__ = ["PrefixEncoder", "PrefixTuningConfig"]
22
+
23
+ register_peft_method(name="prefix_tuning", config_cls=PrefixTuningConfig, model_cls=PrefixEncoder)
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/prefix_tuning/config.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 dataclasses import dataclass, field
16
+
17
+ from peft.config import PromptLearningConfig
18
+ from peft.utils import PeftType
19
+
20
+
21
+ @dataclass
22
+ class PrefixTuningConfig(PromptLearningConfig):
23
+ """
24
+ This is the configuration class to store the configuration of a [`PrefixEncoder`].
25
+
26
+ Args:
27
+ encoder_hidden_size (`int`): The hidden size of the prompt encoder.
28
+ prefix_projection (`bool`): Whether to project the prefix embeddings.
29
+ """
30
+
31
+ encoder_hidden_size: int = field(
32
+ default=None,
33
+ metadata={"help": "The hidden size of the encoder"},
34
+ )
35
+ prefix_projection: bool = field(
36
+ default=False,
37
+ metadata={"help": "Whether to project the prefix tokens"},
38
+ )
39
+
40
+ def __post_init__(self):
41
+ super().__post_init__()
42
+ self.peft_type = PeftType.PREFIX_TUNING
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/prefix_tuning/model.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Based on https://github.com/THUDM/P-tuning-v2/blob/main/model/prefix_encoder.py
16
+ # with some refactor
17
+ import torch
18
+
19
+
20
+ class PrefixEncoder(torch.nn.Module):
21
+ r"""
22
+ The `torch.nn` model to encode the prefix.
23
+
24
+ Args:
25
+ config ([`PrefixTuningConfig`]): The configuration of the prefix encoder.
26
+
27
+ Example:
28
+
29
+ ```py
30
+ >>> from peft import PrefixEncoder, PrefixTuningConfig
31
+
32
+ >>> config = PrefixTuningConfig(
33
+ ... peft_type="PREFIX_TUNING",
34
+ ... task_type="SEQ_2_SEQ_LM",
35
+ ... num_virtual_tokens=20,
36
+ ... token_dim=768,
37
+ ... num_transformer_submodules=1,
38
+ ... num_attention_heads=12,
39
+ ... num_layers=12,
40
+ ... encoder_hidden_size=768,
41
+ ... )
42
+ >>> prefix_encoder = PrefixEncoder(config)
43
+ ```
44
+
45
+ **Attributes**:
46
+ - **embedding** (`torch.nn.Embedding`) -- The embedding layer of the prefix encoder.
47
+ - **transform** (`torch.nn.Sequential`) -- The two-layer MLP to transform the prefix embeddings if
48
+ `prefix_projection` is `True`.
49
+ - **prefix_projection** (`bool`) -- Whether to project the prefix embeddings.
50
+
51
+ Input shape: (`batch_size`, `num_virtual_tokens`)
52
+
53
+ Output shape: (`batch_size`, `num_virtual_tokens`, `2*layers*hidden`)
54
+ """
55
+
56
+ def __init__(self, config):
57
+ super().__init__()
58
+ self.prefix_projection = config.prefix_projection
59
+ token_dim = config.token_dim
60
+ num_layers = config.num_layers
61
+ encoder_hidden_size = config.encoder_hidden_size
62
+ num_virtual_tokens = config.num_virtual_tokens
63
+ if self.prefix_projection and not config.inference_mode:
64
+ # Use a two-layer MLP to encode the prefix
65
+ self.embedding = torch.nn.Embedding(num_virtual_tokens, token_dim)
66
+ self.transform = torch.nn.Sequential(
67
+ torch.nn.Linear(token_dim, encoder_hidden_size),
68
+ torch.nn.Tanh(),
69
+ torch.nn.Linear(encoder_hidden_size, num_layers * 2 * token_dim),
70
+ )
71
+ else:
72
+ self.embedding = torch.nn.Embedding(num_virtual_tokens, num_layers * 2 * token_dim)
73
+
74
+ def forward(self, prefix: torch.Tensor):
75
+ if self.prefix_projection:
76
+ prefix_tokens = self.embedding(prefix)
77
+ past_key_values = self.transform(prefix_tokens)
78
+ else:
79
+ past_key_values = self.embedding(prefix)
80
+ return past_key_values
81
+
82
+ def load_prompt_embeddings(self, prompt_embeddings: torch.Tensor) -> None:
83
+ """
84
+ Load the flattened prompt embeddings saved by PEFT (`prompt_embeddings`).
85
+
86
+ For prefix tuning, this is only supported when `prefix_projection=False`, because in that case the learned
87
+ parameters are the KV prefix itself (`embedding.weight` has shape `[num_virtual_tokens,
88
+ num_layers*2*token_dim]`).
89
+
90
+ If `prefix_projection=True`, the parameters are (virtual token embeddings + an MLP) and there is no general way
91
+ to invert the projection to recover those parameters from a flattened KV prefix.
92
+ """
93
+ if self.prefix_projection:
94
+ raise ValueError("Cannot load flattened prompt embeddings when `prefix_projection=True`.")
95
+ if prompt_embeddings.shape != self.embedding.weight.shape:
96
+ raise ValueError(
97
+ "Invalid `prompt_embeddings` shape. Expected "
98
+ f"{tuple(self.embedding.weight.shape)}, got {tuple(prompt_embeddings.shape)}."
99
+ )
100
+ with torch.no_grad():
101
+ self.embedding.weight.copy_(prompt_embeddings.to(self.embedding.weight.device))
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/prompt_tuning/__init__.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 PromptTuningConfig, PromptTuningInit
18
+ from .model import PromptEmbedding
19
+
20
+
21
+ __all__ = ["PromptEmbedding", "PromptTuningConfig", "PromptTuningInit"]
22
+
23
+ register_peft_method(name="prompt_tuning", config_cls=PromptTuningConfig, model_cls=PromptEmbedding)
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/prompt_tuning/config.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.config import PromptLearningConfig
20
+ from peft.utils import PeftType
21
+
22
+
23
+ class PromptTuningInit(str, enum.Enum):
24
+ TEXT = "TEXT"
25
+ SAMPLE_VOCAB = "SAMPLE_VOCAB"
26
+ RANDOM = "RANDOM"
27
+
28
+
29
+ @dataclass
30
+ class PromptTuningConfig(PromptLearningConfig):
31
+ """
32
+ This is the configuration class to store the configuration of a [`PromptEmbedding`].
33
+
34
+ Args:
35
+ prompt_tuning_init (Union[[`PromptTuningInit`], `str`]):
36
+ The initialization of the prompt embedding. `TEXT` will initialize with your text. `SAMPLE_VOCAB` will
37
+ initialize with randomly sampled tokens from the model's vocabulary. `RANDOM` will initialize with randomly
38
+ sampled continuous, soft tokens (warning: sampled soft tokens may fall outside of embedding manifold)
39
+ prompt_tuning_init_text (`str`, *optional*):
40
+ The text to initialize the prompt embedding. Only used if `prompt_tuning_init` is `TEXT`.
41
+ tokenizer_name_or_path (`str`, *optional*):
42
+ The name or path of the tokenizer. Only used if `prompt_tuning_init` is `TEXT`.
43
+ tokenizer_kwargs (`dict`, *optional*):
44
+ The keyword arguments to pass to `AutoTokenizer.from_pretrained`. Only used if `prompt_tuning_init` is
45
+ `TEXT`.
46
+ """
47
+
48
+ prompt_tuning_init: Union[PromptTuningInit, str] = field(
49
+ default=PromptTuningInit.RANDOM,
50
+ metadata={"help": "How to initialize the prompt tuning parameters"},
51
+ )
52
+ prompt_tuning_init_text: Optional[str] = field(
53
+ default=None,
54
+ metadata={
55
+ "help": "The text to use for prompt tuning initialization. Only used if prompt_tuning_init is `TEXT`"
56
+ },
57
+ )
58
+ tokenizer_name_or_path: Optional[str] = field(
59
+ default=None,
60
+ metadata={
61
+ "help": "The tokenizer to use for prompt tuning initialization. Only used if prompt_tuning_init is `TEXT`"
62
+ },
63
+ )
64
+
65
+ tokenizer_kwargs: Optional[dict] = field(
66
+ default=None,
67
+ metadata={
68
+ "help": (
69
+ "The keyword arguments to pass to `AutoTokenizer.from_pretrained`. Only used if prompt_tuning_init is "
70
+ "`TEXT`"
71
+ ),
72
+ },
73
+ )
74
+
75
+ def __post_init__(self):
76
+ super().__post_init__()
77
+ self.peft_type = PeftType.PROMPT_TUNING
78
+ if (self.prompt_tuning_init == PromptTuningInit.TEXT) and not self.tokenizer_name_or_path:
79
+ raise ValueError(
80
+ f"When prompt_tuning_init='{PromptTuningInit.TEXT.value}', "
81
+ f"tokenizer_name_or_path can't be {self.tokenizer_name_or_path}."
82
+ )
83
+ if (self.prompt_tuning_init == PromptTuningInit.TEXT) and self.prompt_tuning_init_text is None:
84
+ raise ValueError(
85
+ f"When prompt_tuning_init='{PromptTuningInit.TEXT.value}', "
86
+ f"prompt_tuning_init_text can't be {self.prompt_tuning_init_text}."
87
+ )
88
+ if self.tokenizer_kwargs and (self.prompt_tuning_init != PromptTuningInit.TEXT):
89
+ raise ValueError(
90
+ f"tokenizer_kwargs only valid when using prompt_tuning_init='{PromptTuningInit.TEXT.value}'."
91
+ )
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/prompt_tuning/model.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 math
16
+
17
+ import torch
18
+
19
+ from peft.utils.integrations import gather_params_ctx
20
+
21
+ from .config import PromptTuningInit
22
+
23
+
24
+ class PromptEmbedding(torch.nn.Module):
25
+ """
26
+ The model to encode virtual tokens into prompt embeddings.
27
+
28
+ Args:
29
+ config ([`PromptTuningConfig`]): The configuration of the prompt embedding.
30
+ word_embeddings (`torch.nn.Module`): The word embeddings of the base transformer model.
31
+
32
+ **Attributes**:
33
+ - **embedding** (`torch.nn.Embedding`) -- The embedding layer of the prompt embedding.
34
+
35
+ Example:
36
+
37
+ ```py
38
+ >>> from peft import PromptEmbedding, PromptTuningConfig
39
+
40
+ >>> config = PromptTuningConfig(
41
+ ... peft_type="PROMPT_TUNING",
42
+ ... task_type="SEQ_2_SEQ_LM",
43
+ ... num_virtual_tokens=20,
44
+ ... token_dim=768,
45
+ ... num_transformer_submodules=1,
46
+ ... num_attention_heads=12,
47
+ ... num_layers=12,
48
+ ... prompt_tuning_init="TEXT",
49
+ ... prompt_tuning_init_text="Predict if sentiment of this review is positive, negative or neutral",
50
+ ... tokenizer_name_or_path="t5-base",
51
+ ... )
52
+
53
+ >>> # t5_model.shared is the word embeddings of the base model
54
+ >>> prompt_embedding = PromptEmbedding(config, t5_model.shared)
55
+ ```
56
+
57
+ Input Shape: (`batch_size`, `total_virtual_tokens`)
58
+
59
+ Output Shape: (`batch_size`, `total_virtual_tokens`, `token_dim`)
60
+ """
61
+
62
+ def __init__(self, config, word_embeddings):
63
+ super().__init__()
64
+
65
+ total_virtual_tokens = config.num_virtual_tokens * config.num_transformer_submodules
66
+ self.embedding = torch.nn.Embedding(total_virtual_tokens, config.token_dim)
67
+ if config.prompt_tuning_init == PromptTuningInit.SAMPLE_VOCAB and not config.inference_mode:
68
+ # Randomly sample tokens from the tokenizer's vocab
69
+ vocab_size = word_embeddings.num_embeddings
70
+ init_token_ids = torch.randint(0, vocab_size, (total_virtual_tokens,), dtype=torch.long).to(
71
+ word_embeddings.weight.device
72
+ )
73
+ with gather_params_ctx(word_embeddings.parameters()):
74
+ word_embedding_weights = word_embeddings(init_token_ids).detach().clone()
75
+ word_embedding_weights = word_embedding_weights.to(torch.float32)
76
+ self.embedding.weight = torch.nn.Parameter(word_embedding_weights)
77
+
78
+ elif config.prompt_tuning_init == PromptTuningInit.TEXT and not config.inference_mode:
79
+ from transformers import AutoTokenizer
80
+
81
+ tokenizer_kwargs = config.tokenizer_kwargs or {}
82
+ # security: disallow trust_remote_code, as this could allow code execution when loading a prompt tuning
83
+ # checkpoint
84
+ tokenizer_kwargs.pop("trust_remote_code", None)
85
+ tokenizer = AutoTokenizer.from_pretrained(config.tokenizer_name_or_path, **tokenizer_kwargs)
86
+ init_text = config.prompt_tuning_init_text
87
+ init_token_ids = tokenizer(init_text)["input_ids"]
88
+ # Trim or iterate until num_text_tokens matches total_virtual_tokens
89
+ num_text_tokens = len(init_token_ids)
90
+ if num_text_tokens > total_virtual_tokens:
91
+ init_token_ids = init_token_ids[:total_virtual_tokens]
92
+ elif num_text_tokens < total_virtual_tokens:
93
+ num_reps = math.ceil(total_virtual_tokens / num_text_tokens)
94
+ init_token_ids = init_token_ids * num_reps
95
+ init_token_ids = init_token_ids[:total_virtual_tokens]
96
+ init_token_ids = torch.LongTensor(init_token_ids).to(word_embeddings.weight.device)
97
+ with gather_params_ctx(word_embeddings.parameters()):
98
+ word_embedding_weights = word_embeddings(init_token_ids).detach().clone()
99
+ word_embedding_weights = word_embedding_weights.to(torch.float32)
100
+ self.embedding.weight = torch.nn.Parameter(word_embedding_weights)
101
+
102
+ def forward(self, indices):
103
+ # Just get embeddings
104
+ prompt_embeddings = self.embedding(indices)
105
+ return prompt_embeddings
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/randlora/__init__.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025-present the HuggingFace Inc. team.
2
+
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from peft.import_utils import is_bnb_4bit_available, is_bnb_available
17
+ from peft.utils import register_peft_method
18
+
19
+ from .config import RandLoraConfig
20
+ from .layer import Linear, RandLoraLayer
21
+ from .model import RandLoraModel
22
+
23
+
24
+ __all__ = ["Linear", "RandLoraConfig", "RandLoraLayer", "RandLoraModel"]
25
+
26
+ register_peft_method(name="randlora", config_cls=RandLoraConfig, model_cls=RandLoraModel, prefix="randlora_")
27
+
28
+
29
+ def __getattr__(name):
30
+ if (name == "Linear8bitLt") and is_bnb_available():
31
+ from .bnb import Linear8bitLt
32
+
33
+ return Linear8bitLt
34
+
35
+ if (name == "Linear4bit") and is_bnb_4bit_available():
36
+ from .bnb import Linear4bit
37
+
38
+ return Linear4bit
39
+
40
+ raise AttributeError(f"module {__name__} has no attribute {name}")
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/randlora/bnb.py ADDED
@@ -0,0 +1,456 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 check_adapters_to_merge
24
+ from peft.utils.integrations import dequantize_bnb_weight
25
+ from peft.utils.other import transpose
26
+
27
+ from .layer import RandLoraLayer, UniqueBaseGrad
28
+
29
+
30
+ if is_bnb_available():
31
+
32
+ class Linear8bitLt(torch.nn.Module, RandLoraLayer):
33
+ def __init__(
34
+ self,
35
+ base_layer: torch.nn.Module,
36
+ adapter_name: str,
37
+ randlora_A,
38
+ randlora_B,
39
+ r: int = 0,
40
+ randlora_alpha: int = 0,
41
+ randlora_dropout: float = 0.0,
42
+ fan_in_fan_out: bool = False,
43
+ init_weights: bool = True,
44
+ **kwargs,
45
+ ) -> None:
46
+ super().__init__()
47
+ RandLoraLayer.__init__(self, base_layer)
48
+ self.fan_in_fan_out = fan_in_fan_out
49
+
50
+ self._active_adapter = adapter_name
51
+ self.update_layer(
52
+ adapter_name,
53
+ randlora_A,
54
+ randlora_B,
55
+ r,
56
+ randlora_alpha=randlora_alpha,
57
+ randlora_dropout=randlora_dropout,
58
+ init_weights=init_weights,
59
+ )
60
+
61
+ def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None:
62
+ """
63
+ Merge the active adapter weights into the base weights
64
+
65
+ Args:
66
+ safe_merge (`bool`, *optional*):
67
+ If True, the merge operation will be performed in a copy of the original weights and check for NaNs
68
+ before merging the weights. This is useful if you want to check if the merge operation will produce
69
+ NaNs. Defaults to `False`.
70
+ adapter_names (`list[str]`, *optional*):
71
+ The list of adapter names that should be merged. If None, all active adapters will be merged.
72
+ Defaults to `None`.
73
+ """
74
+
75
+ adapter_names = check_adapters_to_merge(self, adapter_names)
76
+ if not adapter_names:
77
+ return
78
+
79
+ for active_adapter in adapter_names:
80
+ if active_adapter not in self.randlora_lambda.keys():
81
+ continue
82
+
83
+ warnings.warn(
84
+ "Merge RandLora module to 8-bit linear may get different generations due to rounding errors."
85
+ )
86
+ randlora_data = self.get_delta_weight(active_adapter)
87
+
88
+ weight = self.get_base_layer().weight
89
+ state = self.get_base_layer().state
90
+ if state.SCB is None:
91
+ state.SCB = weight.SCB
92
+
93
+ output = dequantize_bnb_weight(weight, state)
94
+ w_data = output.to(randlora_data.dtype).to(randlora_data.device) + randlora_data
95
+
96
+ if safe_merge and not torch.isfinite(w_data).all():
97
+ raise ValueError(
98
+ f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken"
99
+ )
100
+
101
+ self.get_base_layer().weight = bnb.nn.Int8Params(
102
+ w_data.to("cpu"), requires_grad=False, has_fp16_weights=weight.has_fp16_weights
103
+ ).to(weight.device)
104
+ state.reset_grads()
105
+ self.merged_adapters.append(active_adapter)
106
+
107
+ def unmerge(self) -> None:
108
+ """
109
+ This method unmerges all merged adapter layers from the base weights.
110
+ """
111
+ if not self.merged:
112
+ warnings.warn("Already unmerged. Nothing to do")
113
+ return
114
+
115
+ while len(self.merged_adapters) > 0:
116
+ active_adapter = self.merged_adapters.pop()
117
+ if active_adapter not in self.randlora_lambda.keys():
118
+ continue
119
+ warnings.warn(
120
+ "Unmerge randlora module to 8-bit linear may get different generations due to rounding errors."
121
+ )
122
+ randlora_data = self.get_delta_weight(active_adapter)
123
+
124
+ weight = self.get_base_layer().weight
125
+ state = self.get_base_layer().state
126
+ if state.SCB is None:
127
+ state.SCB = weight.SCB
128
+ output = dequantize_bnb_weight(weight, state=state)
129
+
130
+ w_data = output.to(randlora_data.dtype).to(randlora_data.device) - randlora_data
131
+
132
+ self.get_base_layer().weight = bnb.nn.Int8Params(
133
+ w_data.to("cpu"), requires_grad=False, has_fp16_weights=weight.has_fp16_weights
134
+ ).to(weight.device)
135
+ state.reset_grads()
136
+
137
+ def get_scaled_bases(self, adapter, device=None) -> list[torch.Tensor, torch.Tensor]:
138
+ """
139
+ Performs scaling on the smallest random base (randlora_A) and returns randlora_A and randlora_B in the
140
+ correct order to fit the target layers' dimensions
141
+
142
+ Args:
143
+ adapter (str):
144
+ The name of the adapter for which the delta weight should be computed.
145
+ """
146
+
147
+ randlora_A = self.randlora_A[adapter]
148
+ randlora_B = self.randlora_B[adapter]
149
+
150
+ if device is None:
151
+ device = randlora_B.device
152
+ dtype = randlora_B.dtype
153
+
154
+ # In case users wants to merge the adapter weights that are in
155
+ # (b)float16 while being on CPU, we need to cast the weights to float32, perform the merge and then cast back to
156
+ # (b)float16 because some CPUs have slow bf16/fp16 matmuls.
157
+ cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16)
158
+
159
+ randlora_lambda = self.randlora_lambda[adapter].to(device)
160
+ randlora_gamma = self.randlora_gamma[adapter].to(device)
161
+
162
+ if cast_to_fp32:
163
+ randlora_A = randlora_A.float()
164
+ randlora_B = randlora_B.float()
165
+ randlora_lambda = randlora_lambda.float()
166
+ randlora_gamma = randlora_gamma.float()
167
+
168
+ # The trainable parameters are always applied to randlora_A, the smallest basis.
169
+ min_dim, max_dim = min(self.out_features, self.in_features), max(self.out_features, self.in_features)
170
+
171
+ # As adapted layers may have different shapes and RandLora contains a single shared pair of A and B matrices,
172
+ # we initialize these matrices with the largest required size for each dimension.
173
+ # During the forward pass, required submatrices are sliced out from the shared randlora_A and randlora_B.
174
+ sliced_A = randlora_A[:, : self.num_bases, :min_dim].to(device)
175
+ sliced_B = randlora_B[:max_dim, : self.num_bases, :].to(device)
176
+
177
+ # Flattening the matrices over the rank and number of bases dimensions is more memory efficient
178
+ update_B = sliced_B.flatten(start_dim=1)
179
+ update_A = UniqueBaseGrad.apply(sliced_A, randlora_lambda, randlora_gamma).flatten(end_dim=1)
180
+ if min_dim == self.in_features:
181
+ return update_A, update_B
182
+
183
+ return update_B.T, update_A.T
184
+
185
+ def get_delta_weight(self, adapter) -> torch.Tensor:
186
+ """
187
+ Compute the delta weight for the given adapter.
188
+
189
+ Args:
190
+ adapter (str):
191
+ The name of the adapter for which the delta weight should be computed.
192
+ """
193
+
194
+ update_B, update_A = self.get_scaled_bases(adapter)
195
+
196
+ update = update_B @ update_A
197
+ output_tensor = transpose(update, self.fan_in_fan_out)
198
+
199
+ scaling = self.scaling[adapter]
200
+
201
+ return output_tensor * scaling
202
+
203
+ def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor:
204
+ """
205
+ Perform the forward pass using the RandLora adapter.
206
+
207
+ Args:
208
+ x (torch.Tensor): Input tensor.
209
+
210
+ Returns:
211
+ torch.Tensor: Output tensor after applying the RandLora adaptation.
212
+
213
+ Note:
214
+ This method implements the RandLora-specific forward pass. It applies the shared projections
215
+ (randlora_A and randlora_B) along with the per-layer trainable parameters (lambda and gamma) to compute
216
+ the adapter output.
217
+ """
218
+ if self.disable_adapters:
219
+ if self.merged:
220
+ self.unmerge()
221
+ result = self.base_layer(x, *args, **kwargs)
222
+ elif self.merged:
223
+ result = self.base_layer(x, *args, **kwargs)
224
+ else:
225
+ result = self.base_layer(x, *args, **kwargs)
226
+ for active_adapter in self.active_adapters:
227
+ if active_adapter not in self.randlora_lambda.keys():
228
+ continue
229
+
230
+ update_B, update_A = self.get_scaled_bases(active_adapter, device=x.device)
231
+
232
+ requires_conversion = not torch.is_autocast_enabled()
233
+ if requires_conversion:
234
+ expected_dtype = result.dtype
235
+ compute_dtype = update_A.dtype
236
+ if x.dtype != compute_dtype:
237
+ x = x.to(compute_dtype)
238
+
239
+ dropout = self.randlora_dropout[active_adapter]
240
+ x_temp = dropout(x.to(update_A.dtype))
241
+
242
+ adapter_output = torch.nn.functional.linear(torch.nn.functional.linear(x_temp, update_B), update_A)
243
+
244
+ if requires_conversion:
245
+ adapter_output = adapter_output.to(expected_dtype)
246
+
247
+ scaling = self.scaling[active_adapter]
248
+ result = result + adapter_output * scaling
249
+
250
+ # Ensure the output tensor has the same dtype as the input tensor
251
+ return result.to(x.dtype)
252
+
253
+ def __repr__(self) -> str:
254
+ rep = super().__repr__()
255
+ return "randlora." + rep
256
+
257
+
258
+ if is_bnb_4bit_available():
259
+
260
+ class Linear4bit(torch.nn.Module, RandLoraLayer):
261
+ def __init__(
262
+ self,
263
+ base_layer: torch.nn.Module,
264
+ adapter_name: str,
265
+ randlora_A,
266
+ randlora_B,
267
+ r: int = 0,
268
+ randlora_alpha: int = 0,
269
+ randlora_dropout: float = 0.0,
270
+ fan_in_fan_out: bool = False,
271
+ init_weights: bool = True,
272
+ **kwargs,
273
+ ) -> None:
274
+ super().__init__()
275
+ RandLoraLayer.__init__(self, base_layer)
276
+ self.fan_in_fan_out = fan_in_fan_out
277
+ self._active_adapter = adapter_name
278
+ self.update_layer(
279
+ adapter_name,
280
+ randlora_A,
281
+ randlora_B,
282
+ r,
283
+ randlora_alpha=randlora_alpha,
284
+ randlora_dropout=randlora_dropout,
285
+ init_weights=init_weights,
286
+ )
287
+
288
+ def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None:
289
+ """
290
+ Merge the active adapter weights into the base weights
291
+
292
+ Args:
293
+ safe_merge (`bool`, *optional*):
294
+ If True, the merge operation will be performed in a copy of the original weights and check for NaNs
295
+ before merging the weights. This is useful if you want to check if the merge operation will produce
296
+ NaNs. Defaults to `False`.
297
+ adapter_names (`list[str]`, *optional*):
298
+ The list of adapter names that should be merged. If None, all active adapters will be merged.
299
+ Defaults to `None`.
300
+ """
301
+
302
+ adapter_names = check_adapters_to_merge(self, adapter_names)
303
+ if not adapter_names:
304
+ return
305
+
306
+ for active_adapter in adapter_names:
307
+ if active_adapter not in self.randlora_lambda.keys():
308
+ continue
309
+
310
+ warnings.warn(
311
+ "Merge RandLora module to 4-bit linear may get different generations due to rounding errors."
312
+ )
313
+ randlora_data = self.get_delta_weight(active_adapter)
314
+
315
+ weight = self.get_base_layer().weight
316
+ kwargs = weight.__dict__
317
+ w_data = bnb.functional.dequantize_4bit(weight.data, weight.quant_state) + randlora_data
318
+
319
+ if safe_merge and not torch.isfinite(w_data).all():
320
+ raise ValueError(
321
+ f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken"
322
+ )
323
+
324
+ self.get_base_layer().weight = bnb.nn.Params4bit(w_data.to("cpu"), requires_grad=False, **kwargs).to(
325
+ weight.device
326
+ )
327
+ self.merged_adapters.append(active_adapter)
328
+
329
+ def unmerge(self) -> None:
330
+ """
331
+ This method unmerges all merged adapter layers from the base weights.
332
+ """
333
+ if not self.merged:
334
+ warnings.warn("Already unmerged. Nothing to do")
335
+ return
336
+
337
+ while len(self.merged_adapters) > 0:
338
+ active_adapter = self.merged_adapters.pop()
339
+ if active_adapter not in self.randlora_lambda.keys():
340
+ continue
341
+ warnings.warn(
342
+ "Unmerge RandLora module to 4-bit linear may get different generations due to rounding errors."
343
+ )
344
+ randlora_data = self.get_delta_weight(active_adapter)
345
+
346
+ weight = self.get_base_layer().weight
347
+ kwargs = weight.__dict__
348
+ w_data = bnb.functional.dequantize_4bit(weight.data, weight.quant_state) - randlora_data
349
+
350
+ self.get_base_layer().weight = bnb.nn.Params4bit(w_data.to("cpu"), requires_grad=False, **kwargs).to(
351
+ weight.device
352
+ )
353
+
354
+ def get_scaled_bases(self, adapter, device=None) -> list[torch.Tensor, torch.Tensor]:
355
+ """
356
+ Performs scaling on the smallest random base (randlora_A) and returns randlora_A and randlora_B in the
357
+ correct order to fit the target layers' dimensions
358
+
359
+ Args:
360
+ adapter (str):
361
+ The name of the adapter for which the delta weight should be computed.
362
+ """
363
+
364
+ randlora_A = self.randlora_A[adapter]
365
+ randlora_B = self.randlora_B[adapter]
366
+ if device is None:
367
+ device = randlora_B.device
368
+ dtype = randlora_B.dtype
369
+
370
+ # In case users wants to merge the adapter weights that are in
371
+ # (b)float16 while being on CPU, we need to cast the weights to float32, perform the merge and then cast back to
372
+ # (b)float16 because some CPUs have slow bf16/fp16 matmuls.
373
+ cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16)
374
+
375
+ randlora_lambda = self.randlora_lambda[adapter].to(device)
376
+ randlora_gamma = self.randlora_gamma[adapter].to(device)
377
+
378
+ if cast_to_fp32:
379
+ randlora_A = randlora_A.float()
380
+ randlora_B = randlora_B.float()
381
+ randlora_lambda = randlora_lambda.float()
382
+ randlora_gamma = randlora_gamma.float()
383
+
384
+ # The trainable parameters are always applied to randlora_A, the smallest basis.
385
+ min_dim, max_dim = min(self.out_features, self.in_features), max(self.out_features, self.in_features)
386
+
387
+ # As adapted layers may have different shapes and RandLora contains a single shared pair of A and B matrices,
388
+ # we initialize these matrices with the largest required size for each dimension.
389
+ # During the forward pass, required submatrices are sliced out from the shared randlora_A and randlora_B.
390
+ sliced_A = randlora_A[:, : self.num_bases, :min_dim].to(device)
391
+ sliced_B = randlora_B[:max_dim, : self.num_bases, :].to(device)
392
+ # Flattening the matrices over the rank and number of bases dimensions is more memory efficient
393
+ update_B = sliced_B.flatten(start_dim=1)
394
+ update_A = UniqueBaseGrad.apply(sliced_A, randlora_lambda, randlora_gamma).flatten(end_dim=1)
395
+ if min_dim == self.in_features:
396
+ return update_A, update_B
397
+
398
+ return update_B.T, update_A.T
399
+
400
+ def get_delta_weight(self, adapter) -> torch.Tensor:
401
+ """
402
+ Compute the delta weight for the given adapter.
403
+
404
+ Args:
405
+ adapter (str):
406
+ The name of the adapter for which the delta weight should be computed.
407
+ """
408
+ update_B, update_A = self.get_scaled_bases(adapter)
409
+
410
+ update = update_B @ update_A
411
+ output_tensor = transpose(update, self.fan_in_fan_out)
412
+
413
+ scaling = self.scaling[adapter]
414
+
415
+ return output_tensor * scaling
416
+
417
+ def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor:
418
+ if self.disable_adapters:
419
+ if self.merged:
420
+ self.unmerge()
421
+ result = self.base_layer(x, *args, **kwargs)
422
+ elif self.merged:
423
+ result = self.base_layer(x, *args, **kwargs)
424
+ else:
425
+ result = self.base_layer(x, *args, **kwargs)
426
+ result = result.clone()
427
+ for active_adapter in self.active_adapters:
428
+ if active_adapter not in self.randlora_lambda.keys():
429
+ continue
430
+
431
+ update_B, update_A = self.get_scaled_bases(active_adapter, device=x.device)
432
+
433
+ requires_conversion = not torch.is_autocast_enabled()
434
+ if requires_conversion:
435
+ expected_dtype = result.dtype
436
+ compute_dtype = update_A.dtype
437
+ if x.dtype != compute_dtype:
438
+ x = x.to(compute_dtype)
439
+
440
+ dropout = self.randlora_dropout[active_adapter]
441
+ x_temp = dropout(x.to(update_A.dtype))
442
+
443
+ adapter_output = torch.nn.functional.linear(torch.nn.functional.linear(x_temp, update_B), update_A)
444
+
445
+ if requires_conversion:
446
+ adapter_output = adapter_output.to(expected_dtype)
447
+
448
+ scaling = self.scaling[active_adapter]
449
+ result = result + adapter_output * scaling
450
+
451
+ # Ensure the output tensor has the same dtype as the input tensor
452
+ return result.to(x.dtype)
453
+
454
+ def __repr__(self) -> str:
455
+ rep = super().__repr__()
456
+ return "randlora." + rep
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/randlora/config.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 warnings
16
+ from dataclasses import dataclass, field
17
+ from typing import Optional, Union
18
+
19
+ from peft.config import PeftConfig
20
+ from peft.utils import PeftType
21
+
22
+
23
+ @dataclass
24
+ class RandLoraConfig(PeftConfig):
25
+ """
26
+ This is the configuration class to store the configuration of a [`RandLoraModel`].
27
+
28
+ Paper: https://huggingface.co/papers/2502.00987.
29
+
30
+ Args:
31
+ r (`int`, *optional*, defaults to `32`):
32
+ RandLora's random basis rank dimension. Contrary to Lora, this parameter is inversely proportional to the
33
+ amount of trainable parameters as reducing it increases trainable parameters.
34
+ target_modules (`Union[list[str], str]`):
35
+ The names of the modules to apply RandLora to. Only linear layers are supported.
36
+ projection_prng_key (`int`):
37
+ RandLora PRNG init key. Used for initialising basis_A and basis_B for new models or when loading a
38
+ checkpoint that did not include these projections. Defaults to `0`.
39
+ save_projection (`bool`):
40
+ Whether to save the global basis_A / basis_B random basis in the state dict alongside per layer lambda /
41
+ gamma diagonal matrices. This will increase the size of the checkpoint, but guarantee that we can reload
42
+ the checkpoint on all system configurations. Defaults to `True`.
43
+ sparse (`bool`):
44
+ Whether to use sparse random bases as described in the RandLora paper. The bases are ternary sparse bases
45
+ (only containing -1, 0 and 1) where the attribution probability is 1/6 for -1 and 1 and 2/3 for 0. These
46
+ sparse matrices aim to be used for matmul free computation in the future, see
47
+ https://huggingface.co/papers/2406.02528v1 The current implementation is a proof of concept however where
48
+ the sparseness is not used to improve speed or memory usage. Using sparse matrices typically does not
49
+ reduce performance and can even help reduce overfitting. Defaults to `False`.
50
+ very_sparse (`bool`):
51
+ Whether to use highly sparse random bases as described in the RandLora paper. The very sparse bases are
52
+ ternary sparse bases (only containing -1, 0 and 1) given a matrix with smallest dimension d, the
53
+ attribution probability is 1/√D for -1 and 1 and 1- 2/√D for 0. Using these sparse matrices can further
54
+ reduce overfitting over the `sparse` alternatives but will most likely decrease performance as a results.
55
+ Use carefully. Defaults to `False`.
56
+ randlora_dropout (`float`):
57
+ The dropout probability for RandLora layers.
58
+ randlora_alpha (`float`):
59
+ The scaling coefficient for RandLora layers, this would typically be 20 times the rank. Because the
60
+ `randlora_alpha` coefficient is large by default, it can lead to numerical instabilities especially when
61
+ learning rates are high. If training is unstable, consider reducing the learning rate or the
62
+ `randlora_alpha` coefficient.
63
+ fan_in_fan_out (`bool`):
64
+ Set this to True if the layer to replace stores weight like (fan_in, fan_out). For example, gpt-2 uses
65
+ `Conv1D` which stores weights like (fan_in, fan_out) and hence this should be set to `True`.
66
+ bias (`str`):
67
+ Bias type. Can be 'none', 'all' or 'randlora_only'. If 'all' or 'randlora_only', the corresponding biases
68
+ will be updated during training. Be aware that this means that, even when disabling the adapters, the model
69
+ will not produce the same output as the base model would have without adaptation.
70
+ modules_to_save (`list[str]`):
71
+ list of modules apart from RandLora layers to be set as trainable and saved in the final checkpoint.
72
+ init_weights (`bool`):
73
+ Whether to initialize the weights of the RandLora layers with their default initialization. Don't change
74
+ this setting, except if you know exactly what you're doing.
75
+ layers_to_transform (`Union[list[int],int]`):
76
+ The layer indexes to transform, if this argument is specified, it will apply the RandLora transformations
77
+ on the layer indexes that are specified in this list. If a single integer is passed, it will apply the
78
+ RandLora transformations on the layer at this index.
79
+ layers_pattern (`str`):
80
+ The layer pattern name, used only if `layers_to_transform` is different from `None` and if the layer
81
+ pattern is not in the common layers pattern.
82
+ """
83
+
84
+ r: int = field(default=32, metadata={"help": "RandLora random basis rank"})
85
+
86
+ target_modules: Optional[Union[list[str], str]] = field(
87
+ default=None,
88
+ metadata={
89
+ "help": (
90
+ "list of module names or regex expression of the module names to replace with RandLora."
91
+ "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'. "
92
+ "Only linear layers are supported."
93
+ )
94
+ },
95
+ )
96
+ projection_prng_key: int = field(
97
+ default=0,
98
+ metadata={
99
+ "help": (
100
+ "RandLora PRNG init key. Used for initialising basis_A and basis_B for new models or when loading a "
101
+ "checkpoint that did not include these projections."
102
+ )
103
+ },
104
+ )
105
+ save_projection: bool = field(
106
+ default=True,
107
+ metadata={
108
+ "help": (
109
+ "Whether to save the basis_A / basis_B projections in the state dict alongside per layer lambda / "
110
+ "gamma weights. This will increase the size of the checkpoint, but guarantee that we can reload "
111
+ "the checkpoint on all system configurations."
112
+ )
113
+ },
114
+ )
115
+ sparse: bool = field(
116
+ default=False,
117
+ metadata={
118
+ "help": (
119
+ "Whether to use sparse random bases as described in the RandLora paper."
120
+ "The current implementation is a proof of concept where the sparseness"
121
+ "is not used to improve speed or memory usage."
122
+ )
123
+ },
124
+ )
125
+ very_sparse: bool = field(
126
+ default=False,
127
+ metadata={
128
+ "help": (
129
+ "Whether to use very sparse random bases."
130
+ "The current implementation is a proof of concept where the sparseness"
131
+ "is not used to improve speed or memory usage."
132
+ )
133
+ },
134
+ )
135
+ randlora_dropout: float = field(default=0.0, metadata={"help": "Dropout in the adapter layers"})
136
+ fan_in_fan_out: bool = field(
137
+ default=False,
138
+ metadata={"help": "Set this to True if the layer to replace stores weight like (fan_in, fan_out)"},
139
+ )
140
+ randlora_alpha: int = field(
141
+ default=640,
142
+ metadata={
143
+ "help": "Scaling coefficient in the adapter layers, typically 20 times the rank of the random bases."
144
+ },
145
+ )
146
+ bias: str = field(
147
+ default="none", metadata={"help": "Bias type for RandLora. Can be 'none', 'all' or 'randlora_only'"}
148
+ )
149
+ modules_to_save: Optional[list[str]] = field(
150
+ default=None,
151
+ metadata={
152
+ "help": (
153
+ "list of modules apart from RandLora layers to be set as trainable and saved in the final checkpoint. For"
154
+ " example, in Sequence Classification or Token Classification tasks, the final layer"
155
+ " `classifier/score` are randomly initialized and as such need to be trainable and saved."
156
+ )
157
+ },
158
+ )
159
+ init_weights: bool = field(
160
+ default=True,
161
+ metadata={
162
+ "help": (
163
+ "Whether to initialize the weights of the RandLora layers with their default initialization. Don't change "
164
+ "this setting, except if you know exactly what you're doing."
165
+ ),
166
+ },
167
+ )
168
+ layers_to_transform: Optional[Union[list[int], int]] = field(
169
+ default=None,
170
+ metadata={
171
+ "help": (
172
+ "The layer indexes to transform, is this argument is specified, PEFT will transform only the layers"
173
+ " indexes that are specified inside this list. If a single integer is passed, PEFT will transform only"
174
+ " the layer at this index."
175
+ )
176
+ },
177
+ )
178
+ layers_pattern: Optional[str] = field(
179
+ default=None,
180
+ metadata={
181
+ "help": (
182
+ "The layer pattern name, used only if `layers_to_transform` is different to None and if the layer"
183
+ " pattern is not in the common layers pattern."
184
+ )
185
+ },
186
+ )
187
+
188
+ def __post_init__(self):
189
+ self.peft_type = PeftType.RANDLORA
190
+ self.target_modules = (
191
+ set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules
192
+ )
193
+
194
+ if not self.save_projection:
195
+ warnings.warn(
196
+ "Specified to not save basis_A and basis_B within the state dictionary, instead they will be restored "
197
+ "using the PRNG key store in `config.projection_prng_key`. Consider setting `config.save_projection` "
198
+ "to `True` to guarantee restoring the checkpoint correctly on all system configurations."
199
+ )
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/randlora/layer.py ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 warnings
16
+ from typing import Optional
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+ import torch.nn.functional as F
21
+ from transformers.pytorch_utils import Conv1D
22
+
23
+ from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge
24
+ from peft.utils.other import transpose
25
+
26
+ from .._buffer_dict import BufferDict
27
+
28
+
29
+ class UniqueBaseGrad(torch.autograd.Function):
30
+ # Memory efficent for a unique base
31
+ @staticmethod
32
+ def forward(ctx, randlora_A, randlora_lambda, randlora_gamma):
33
+ out = randlora_lambda[:, :, None] * randlora_A * randlora_gamma[None,]
34
+ ctx.save_for_backward(randlora_A, randlora_lambda, randlora_gamma)
35
+ return out
36
+
37
+ @staticmethod
38
+ def backward(ctx, grad_output):
39
+ randlora_A, randlora_lambda, randlora_gamma = ctx.saved_tensors
40
+ randlora_A, randlora_lambda, randlora_gamma = (
41
+ randlora_A.to(grad_output.dtype),
42
+ randlora_lambda.to(grad_output.dtype),
43
+ randlora_gamma.to(grad_output.dtype),
44
+ )
45
+ grad_randlora_lambda = torch.einsum("kbj,kvj,bj->kb", grad_output, randlora_A, randlora_gamma)
46
+ grad_randlora_gamma = torch.einsum("kbj,kvj,kb->bj", grad_output, randlora_A, randlora_lambda)
47
+ return None, grad_randlora_lambda, grad_randlora_gamma
48
+
49
+
50
+ class RandLoraLayer(BaseTunerLayer):
51
+ # List all names of layers that may contain adapter weights
52
+ adapter_layer_names = ("randlora_lambda", "randlora_gamma")
53
+ other_param_names = ("randlora_A", "randlora_B")
54
+
55
+ def __init__(self, base_layer: nn.Module, **kwargs):
56
+ self.base_layer = base_layer
57
+ self.r = {}
58
+ self.scaling = {}
59
+ self.randlora_dropout = nn.ModuleDict({})
60
+
61
+ # For storing vector scale
62
+ self.randlora_lambda = nn.ParameterDict({})
63
+ self.randlora_gamma = nn.ParameterDict({})
64
+
65
+ # Stores a reference to the randlora_A/B BufferDict.
66
+ # Set to `None` otherwise to avoid computation with random weights
67
+ self.randlora_A: Optional[BufferDict] = None
68
+ self.randlora_B: Optional[BufferDict] = None
69
+
70
+ # Mark the weight as unmerged
71
+ self._disable_adapters = False
72
+ self.merged_adapters = []
73
+
74
+ # flag to enable/disable casting of input to weight dtype during forward call
75
+ self.cast_input_dtype_enabled = True
76
+
77
+ base_layer = self.get_base_layer()
78
+ if isinstance(base_layer, nn.Linear):
79
+ in_features, out_features = base_layer.in_features, base_layer.out_features
80
+ elif isinstance(base_layer, Conv1D):
81
+ in_features, out_features = (
82
+ base_layer.weight.ds_shape if hasattr(base_layer.weight, "ds_shape") else base_layer.weight.shape
83
+ )
84
+
85
+ self.in_features = in_features
86
+ self.out_features = out_features
87
+ self.kwargs = kwargs
88
+
89
+ @property
90
+ def merged(self) -> bool:
91
+ return bool(self.merged_adapters)
92
+
93
+ def update_layer(
94
+ self,
95
+ adapter_name,
96
+ randlora_A: BufferDict,
97
+ randlora_B: BufferDict,
98
+ r,
99
+ randlora_alpha,
100
+ randlora_dropout,
101
+ init_weights,
102
+ inference_mode: bool = False,
103
+ **kwargs,
104
+ ):
105
+ if r <= 0:
106
+ raise ValueError(f"`r` should be a positive integer value but the value passed is {r}")
107
+ self.r[adapter_name] = r
108
+ if randlora_dropout > 0.0:
109
+ randlora_dropout_layer = nn.Dropout(p=randlora_dropout)
110
+ else:
111
+ randlora_dropout_layer = nn.Identity()
112
+
113
+ self.randlora_dropout.update(nn.ModuleDict({adapter_name: randlora_dropout_layer}))
114
+
115
+ # Actual trainable parameters
116
+ num_bases = min(self.in_features, self.out_features) / r
117
+ self.num_bases = int(num_bases) if num_bases.is_integer() else int(num_bases) + 1 # Full rank
118
+ self.randlora_lambda[adapter_name] = nn.Parameter(torch.randn(r, self.num_bases), requires_grad=True)
119
+ self.randlora_gamma[adapter_name] = nn.Parameter(
120
+ torch.ones(self.num_bases, min(self.out_features, self.in_features))
121
+ / max(self.out_features, self.in_features),
122
+ requires_grad=True,
123
+ )
124
+
125
+ self.scaling[adapter_name] = randlora_alpha / r
126
+
127
+ # non trainable references to randlora_A/B buffers
128
+ self.randlora_A = randlora_A
129
+ self.randlora_B = randlora_B
130
+ if adapter_name not in randlora_A:
131
+ # This means that this is not the first RandLora adapter. We have to add an entry in the dict for this adapter.
132
+ if len(self.randlora_A) < 1:
133
+ raise ValueError(
134
+ "The `randlora_A` and `randlora_B` buffers are empty. This should not happen. Please report this issue."
135
+ )
136
+ # we can take any of the existing adapter's parameters, as they should all be identical
137
+ randlora_A_param = list(self.randlora_A.values())[0]
138
+ randlora_B_param = list(self.randlora_B.values())[0]
139
+
140
+ error_tmpl = (
141
+ "{} has a size of {} but {} or greater is required; this probably happened because an additional RandLora "
142
+ "adapter was added after the first one with incompatible shapes."
143
+ )
144
+ max_dim, min_dim = max(self.in_features, self.out_features), min(self.in_features, self.out_features)
145
+ # check input size
146
+ if randlora_B_param.shape[0] < max_dim:
147
+ raise ValueError(error_tmpl.format("randlora_B", randlora_B_param.shape[0], max_dim))
148
+ # check output size
149
+ if randlora_A_param.shape[-1] < min_dim:
150
+ raise ValueError(error_tmpl.format("randlora_A", randlora_A_param.shape[1], min_dim))
151
+
152
+ # check r
153
+ error_tmpl = (
154
+ "{} has a size of {} but {} or greater is required; this probably happened because an additional RandLora "
155
+ "adapter with a lower rank was added after the first one; loading the adapters "
156
+ "in reverse order may solve this."
157
+ )
158
+ if randlora_A_param.shape[0] < self.r[adapter_name]:
159
+ raise ValueError(error_tmpl.format("randlora_A", randlora_A_param.shape[0], self.r[adapter_name]))
160
+
161
+ if randlora_B_param.shape[-1] < self.r[adapter_name]:
162
+ raise ValueError(error_tmpl.format("randlora_B", randlora_B_param.shape[-1], self.r[adapter_name]))
163
+
164
+ self.randlora_A[adapter_name] = randlora_A_param
165
+ self.randlora_B[adapter_name] = randlora_B_param
166
+
167
+ if init_weights:
168
+ self.reset_randlora_parameters(adapter_name)
169
+
170
+ self._move_adapter_to_device_of_base_layer(adapter_name)
171
+ self.set_adapter(self.active_adapters, inference_mode=inference_mode)
172
+
173
+ def reset_randlora_parameters(self, adapter_name):
174
+ if adapter_name in self.randlora_lambda.keys():
175
+ with torch.no_grad():
176
+ nn.init.zeros_(self.randlora_lambda[adapter_name])
177
+ nn.init.constant_(self.randlora_gamma[adapter_name], 1 / max(self.randlora_gamma[adapter_name].shape))
178
+
179
+
180
+ class Linear(nn.Linear, RandLoraLayer):
181
+ # RandLora implemented in a dense layer
182
+ def __init__(
183
+ self,
184
+ base_layer,
185
+ randlora_A: BufferDict,
186
+ randlora_B: BufferDict,
187
+ adapter_name: str,
188
+ r: int = 0,
189
+ randlora_alpha: int = 0,
190
+ randlora_dropout: float = 0.0,
191
+ fan_in_fan_out: bool = False, # Set this to True if the layer to replace stores weight like (fan_in, fan_out)
192
+ is_target_conv_1d_layer: bool = False,
193
+ init_weights: bool = True,
194
+ **kwargs,
195
+ ) -> None:
196
+ # this gets the init from nn.Linear's super perspective, i.e. nn.Module.__init__, which should always be called
197
+ super(nn.Linear, self).__init__()
198
+ RandLoraLayer.__init__(self, base_layer, **kwargs)
199
+ self.fan_in_fan_out = fan_in_fan_out
200
+ self._active_adapter = adapter_name
201
+ self.update_layer(adapter_name, randlora_A, randlora_B, r, randlora_alpha, randlora_dropout, init_weights)
202
+ self.is_target_conv_1d_layer = is_target_conv_1d_layer
203
+
204
+ def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None:
205
+ """
206
+ Merge the active adapter weights into the base weights
207
+
208
+ Args:
209
+ safe_merge (`bool`, *optional*):
210
+ If True, the merge operation will be performed in a copy of the original weights and check for NaNs
211
+ before merging the weights. This is useful if you want to check if the merge operation will produce
212
+ NaNs. Defaults to `False`.
213
+ adapter_names (`list[str]`, *optional*):
214
+ The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults
215
+ to `None`.
216
+ """
217
+ adapter_names = check_adapters_to_merge(self, adapter_names)
218
+ if not adapter_names:
219
+ # no adapter to merge
220
+ return
221
+
222
+ for active_adapter in adapter_names:
223
+ if active_adapter in self.randlora_lambda.keys():
224
+ base_layer = self.get_base_layer()
225
+ orig_dtype = base_layer.weight.dtype
226
+
227
+ if safe_merge:
228
+ # Note that safe_merge will be slower than the normal merge
229
+ # because of the copy operation.
230
+ orig_weights = base_layer.weight.data.clone()
231
+
232
+ orig_weights += self.get_delta_weight(active_adapter)
233
+
234
+ if not torch.isfinite(orig_weights).all():
235
+ raise ValueError(
236
+ f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken"
237
+ )
238
+
239
+ base_layer.weight.data = orig_weights.to(orig_dtype)
240
+ else:
241
+ delta_weight = self.get_delta_weight(active_adapter)
242
+ base_layer.weight.data += delta_weight.to(orig_dtype)
243
+
244
+ self.merged_adapters.append(active_adapter)
245
+
246
+ def unmerge(self) -> None:
247
+ """
248
+ This method unmerges all merged adapter layers from the base weights.
249
+ """
250
+ if not self.merged:
251
+ warnings.warn("Already unmerged. Nothing to do.")
252
+ return
253
+
254
+ while len(self.merged_adapters) > 0:
255
+ base_layer = self.get_base_layer()
256
+ orig_dtype = base_layer.weight.dtype
257
+ active_adapter = self.merged_adapters.pop()
258
+ if active_adapter in self.randlora_lambda.keys():
259
+ delta_weight = self.get_delta_weight(active_adapter)
260
+ base_layer.weight.data -= delta_weight.to(orig_dtype)
261
+
262
+ def get_scaled_bases(self, adapter, device=None) -> tuple[torch.Tensor, torch.Tensor]:
263
+ """
264
+ Performs scaling on the smallest random base (randlora_A) and returns randlora_A and randlora_B in the correct
265
+ order to fit the target layers' dimensions
266
+
267
+ Args:
268
+ adapter (str):
269
+ The name of the adapter for which the delta weight should be computed.
270
+ """
271
+
272
+ randlora_A = self.randlora_A[adapter]
273
+ randlora_B = self.randlora_B[adapter]
274
+ if device is None:
275
+ device = randlora_B.device
276
+ dtype = randlora_B.dtype
277
+
278
+ # In case users wants to merge the adapter weights that are in
279
+ # (b)float16 while being on CPU, we need to cast the weights to float32, perform the merge and then cast back to
280
+ # (b)float16 because some CPUs have slow bf16/fp16 matmuls.
281
+ cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16)
282
+
283
+ randlora_lambda = self.randlora_lambda[adapter].to(device)
284
+ randlora_gamma = self.randlora_gamma[adapter].to(device)
285
+
286
+ if cast_to_fp32:
287
+ randlora_A = randlora_A.float()
288
+ randlora_B = randlora_B.float()
289
+ randlora_lambda = randlora_lambda.float()
290
+ randlora_gamma = randlora_gamma.float()
291
+
292
+ # The trainable parameters are always applied to randlora_A, the smallest basis.
293
+ min_dim, max_dim = min(self.out_features, self.in_features), max(self.out_features, self.in_features)
294
+
295
+ # As adapted layers may have different shapes and RandLora contains a single shared pair of A and B matrices,
296
+ # we initialize these matrices with the largest required size for each dimension.
297
+ # During the forward pass, required submatrices are sliced out from the shared randlora_A and randlora_B.
298
+ sliced_A = randlora_A[:, : self.num_bases, :min_dim].to(device)
299
+ sliced_B = randlora_B[:max_dim, : self.num_bases, :].to(device)
300
+
301
+ # Flattening the matrices over the rank and number of bases dimensions is more memory efficient
302
+ update_B = sliced_B.flatten(start_dim=1)
303
+ update_A = UniqueBaseGrad.apply(sliced_A, randlora_lambda, randlora_gamma).flatten(end_dim=1)
304
+
305
+ # Since update_A is applied on the smallest dimension, test whether update_A or update_B should be applied first. This is done to reduce trainable parameters.
306
+ if min_dim == self.in_features:
307
+ return update_A, update_B
308
+ return update_B.T, update_A.T
309
+
310
+ def get_delta_weight(self, adapter) -> torch.Tensor:
311
+ """
312
+ Compute the delta weight for the given adapter.
313
+
314
+ Args:
315
+ adapter (str):
316
+ The name of the adapter for which the delta weight should be computed.
317
+ """
318
+
319
+ update_B, update_A = self.get_scaled_bases(adapter)
320
+
321
+ update = (update_B.T @ update_A.T).T
322
+ output_tensor = transpose(update, self.fan_in_fan_out)
323
+
324
+ scaling = self.scaling[adapter]
325
+ return output_tensor * scaling
326
+
327
+ def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor:
328
+ previous_dtype = x.dtype
329
+ if self.disable_adapters:
330
+ if self.merged:
331
+ self.unmerge()
332
+ result = self.base_layer(x, *args, **kwargs)
333
+ elif self.merged:
334
+ result = self.base_layer(x, *args, **kwargs)
335
+ else:
336
+ result = self.base_layer(x, *args, **kwargs)
337
+ for active_adapter in self.active_adapters:
338
+ if active_adapter not in self.randlora_lambda.keys():
339
+ continue
340
+ dropout = self.randlora_dropout[active_adapter]
341
+ update_B, update_A = self.get_scaled_bases(active_adapter, device=x.device)
342
+ x = x.to(update_A.dtype)
343
+ scaling = self.scaling[active_adapter]
344
+ result = result + F.linear(F.linear(dropout(x), update_B), update_A) * scaling
345
+ result = result.to(previous_dtype)
346
+ return result
347
+
348
+ def supports_lora_conversion(self, adapter_name: str = "default") -> bool:
349
+ return True
350
+
351
+ def __repr__(self) -> str:
352
+ rep = super().__repr__()
353
+ return "randlora." + rep
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/randlora/model.py ADDED
@@ -0,0 +1,356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 __future__ import annotations
16
+
17
+ import math
18
+ import warnings
19
+ from typing import Union
20
+
21
+ import torch
22
+ import torch.nn as nn
23
+ from accelerate.utils.imports import is_bf16_available
24
+ from transformers.pytorch_utils import Conv1D
25
+
26
+ from peft.import_utils import is_bnb_4bit_available, is_bnb_available
27
+ from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer
28
+ from peft.utils import (
29
+ TRANSFORMERS_MODELS_TO_RANDLORA_TARGET_MODULES_MAPPING,
30
+ )
31
+
32
+ from .._buffer_dict import BufferDict
33
+ from ..tuners_utils import _maybe_include_all_linear_layers
34
+ from .config import RandLoraConfig
35
+ from .layer import Linear, RandLoraLayer
36
+
37
+
38
+ def _kaiming_init(
39
+ tensor_or_shape: Union[torch.Tensor, tuple[int, ...]],
40
+ generator: torch.Generator,
41
+ ) -> torch.Tensor:
42
+ """
43
+ Kaiming Uniform Initialisation adapted to accept a `torch.Generator` object for PRNG.
44
+
45
+ Args:
46
+ tensor_or_shape (`Union[torch.Tensor, tuple[int, ...]]`):
47
+ Tensor to initialise, or shape of new tensor to create and then initialise.
48
+ generator: (`torch.Generator`):
49
+ Generator object that manages the state of the PRNG algorithm in use.
50
+
51
+ Returns:
52
+ `torch.Tensor`: The initialised tensor.
53
+ """
54
+ if isinstance(tensor_or_shape, tuple):
55
+ tensor = torch.empty(
56
+ tensor_or_shape,
57
+ dtype=torch.bfloat16 if is_bf16_available() else torch.float16,
58
+ )
59
+ else:
60
+ tensor = tensor_or_shape
61
+
62
+ with torch.no_grad():
63
+ basis = torch.nn.init.kaiming_uniform_(tensor, a=math.sqrt(5), generator=generator)
64
+ return basis
65
+
66
+
67
+ class RandLoraModel(BaseTuner):
68
+ """
69
+ Creates a RandLoRA model from a pretrained transformers model.
70
+
71
+ Args:
72
+ model ([`~transformers.PreTrainedModel`]): The model to be adapted.
73
+ config ([`RandLoraConfig`]): The configuration of the RandLora model.
74
+ adapter_name (`str`): The name of the adapter, defaults to `"default"`.
75
+ low_cpu_mem_usage (`bool`, `optional`, defaults to `False`):
76
+ Create empty adapter weights on meta device. Useful to speed up the loading process.
77
+
78
+ Returns:
79
+ `torch.nn.Module`: The RandLora model.
80
+
81
+ Example:
82
+
83
+ ```py
84
+ >>> from transformers import AutoModelForCausalLM
85
+ >>> from peft import RandLoraConfig, get_peft_model
86
+
87
+ >>> base_model = AutoModelForCausalLM.from_pretrained("facebook/opt-125m")
88
+ >>> config = RandLoraConfig(r=32)
89
+ >>> model = get_peft_model(base_model, config)
90
+ ```
91
+
92
+ **Attributes**:
93
+ - **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted.
94
+ - **peft_config** ([`RandLoraConfig`]): The configuration of the RandLora model.
95
+ """
96
+
97
+ prefix: str = "randlora_"
98
+ tuner_layer_cls = RandLoraLayer
99
+ target_module_mapping = TRANSFORMERS_MODELS_TO_RANDLORA_TARGET_MODULES_MAPPING
100
+
101
+ def _find_dim(self, config) -> tuple[int, int]:
102
+ """
103
+ Finds the largest input and output dimensions across linear layers that have been wrapped with RandLora.
104
+
105
+ This will be used for determining the size of the shared randlora_A and randlora_B matrices.
106
+ """
107
+ model_config = self.get_model_config(self.model)
108
+
109
+ peft_config = self._prepare_adapter_config(config, model_config)
110
+ peft_config = _maybe_include_all_linear_layers(peft_config, self.model)
111
+
112
+ largest_shape = None
113
+ for key, module in self.model.named_modules():
114
+ if not self._check_target_module_exists(peft_config, key):
115
+ continue
116
+
117
+ if isinstance(module, nn.Linear):
118
+ module_shape = module.out_features, module.in_features
119
+ elif isinstance(module, Conv1D):
120
+ module_shape = module.weight.ds_shape if hasattr(module.weight, "ds_shape") else module.weight.shape
121
+ module_shape = module_shape[::-1]
122
+ else:
123
+ continue
124
+
125
+ if largest_shape is None:
126
+ largest_shape = module_shape
127
+ continue
128
+
129
+ if module_shape != largest_shape:
130
+ largest_shape = tuple(max(a, b) for a, b in zip(largest_shape, module_shape))
131
+
132
+ if largest_shape is None:
133
+ msg = "No layers types compatible with RandLora were found. Please check `peft_config.target_modules`."
134
+ raise ValueError(msg)
135
+
136
+ return largest_shape
137
+
138
+ def _init_randlora_A_randlora_B_sparse(self, config: RandLoraConfig, adapter_name: str, sparsity: int = 3) -> None:
139
+ """
140
+ Sparse random projections as described in https://cs-people.bu.edu/evimaria/cs565/kdd-rp.pdf
141
+ """
142
+
143
+ linear_out_dim, linear_in_dim = self._find_dim(config)
144
+ max_dim, min_dim = max(linear_out_dim, linear_in_dim), min(linear_out_dim, linear_in_dim)
145
+
146
+ # use of persistent to exclude randlora_A and randlora_B from the state dict if we choose not to save them.
147
+ self.randlora_A = BufferDict({}, persistent=config.save_projection)
148
+ self.randlora_B = BufferDict({}, persistent=config.save_projection)
149
+
150
+ # deterministic init of randlora_A and randlora_B if we know the key
151
+ generator = torch.Generator(device="cpu").manual_seed(config.projection_prng_key)
152
+
153
+ # The gamma matrix is applied on A meaning it can be unique (shared) across the n scaling matrices.
154
+ # We also set randlora_A as the smallest matrix to reduce trainable parameters.
155
+ randlora_A = torch.rand((config.r, 1, min_dim), generator=generator)
156
+
157
+ # Number of bases to ensure full rank
158
+ num_bases = min_dim / config.r
159
+ num_bases = int(num_bases) if num_bases.is_integer() else int(num_bases) + 1 # Ensure full rank
160
+ randlora_B = torch.rand((max_dim, num_bases, config.r), generator=generator)
161
+
162
+ # The current implementation is a proof of concept and does take into consideration
163
+ # the sparsity to reduce memory usage or speed up compute
164
+ randlora_B_sparse = torch.zeros(randlora_B.shape)
165
+ randlora_A_sparse = torch.zeros(randlora_A.shape)
166
+ randlora_B_sparse[randlora_B < 1 / (2 * sparsity)] = -1
167
+ randlora_B_sparse[randlora_B > 1 - 1 / (2 * sparsity)] = 1
168
+ randlora_A_sparse[randlora_A < 1 / (2 * sparsity)] = -1
169
+ randlora_A_sparse[randlora_A > 1 - 1 / (2 * sparsity)] = 1
170
+
171
+ # Std normalization is empirically found to be the best
172
+ randlora_A, randlora_B = (
173
+ randlora_A_sparse / randlora_A_sparse.std(),
174
+ randlora_B_sparse / randlora_B_sparse.std(),
175
+ )
176
+ self.randlora_A[adapter_name] = randlora_A
177
+ self.randlora_B[adapter_name] = randlora_B
178
+
179
+ def _init_randlora_A_randlora_B(self, config: RandLoraConfig, adapter_name: str) -> None:
180
+ linear_out_dim, linear_in_dim = self._find_dim(config)
181
+ max_dim, min_dim = max(linear_out_dim, linear_in_dim), min(linear_out_dim, linear_in_dim)
182
+
183
+ # use of persistent to exclude randlora_A and randlora_B from the state dict if we choose not to save them.
184
+ self.randlora_A = BufferDict({}, persistent=config.save_projection)
185
+ self.randlora_B = BufferDict({}, persistent=config.save_projection)
186
+
187
+ # deterministic init of randlora_A and randlora_B if we know the key
188
+ generator = torch.Generator(device="cpu").manual_seed(config.projection_prng_key)
189
+
190
+ # The gamma matrix is applied on A meaning it can be unique (shared) across the n scaling matrices.
191
+ # We also set randlora_A as the smallest matrix to reduce trainable parameters.
192
+ randlora_A = _kaiming_init((config.r, 1, min_dim), generator=generator)
193
+
194
+ # Ensure full rank
195
+ num_bases = min(linear_out_dim, linear_in_dim) / config.r
196
+ num_bases = int(num_bases) if num_bases.is_integer() else int(num_bases) + 1
197
+ randlora_B = torch.cat(
198
+ [_kaiming_init((max_dim, 1, config.r), generator=generator) for _ in range(num_bases)], dim=1
199
+ )
200
+
201
+ # Std normalization is empirically found to be the best
202
+ randlora_A, randlora_B = randlora_A / randlora_A.std(), randlora_B / randlora_B.std()
203
+ self.randlora_A[adapter_name] = randlora_A
204
+ self.randlora_B[adapter_name] = randlora_B
205
+
206
+ def _pre_injection_hook(self, model: nn.Module, config: RandLoraConfig, adapter_name: str) -> None:
207
+ if config.very_sparse:
208
+ linear_out_dim, linear_in_dim = self._find_dim(config)
209
+ self._init_randlora_A_randlora_B_sparse(
210
+ config, adapter_name, sparsity=math.sqrt(min(linear_out_dim, linear_in_dim))
211
+ )
212
+ elif config.sparse:
213
+ self._init_randlora_A_randlora_B_sparse(config, adapter_name, sparsity=3)
214
+ else:
215
+ self._init_randlora_A_randlora_B(config, adapter_name)
216
+
217
+ def _check_new_adapter_config(self, config: RandLoraConfig) -> None:
218
+ """
219
+ A helper method to check the config when a new adapter is being added.
220
+
221
+ Raise a ValueError if there is something wrong with the config or if it conflicts with existing adapters.
222
+
223
+ """
224
+ super()._check_new_adapter_config(config)
225
+
226
+ for existing_config in self.peft_config.values():
227
+ if existing_config is config:
228
+ # skip the current config
229
+ continue
230
+
231
+ if existing_config.projection_prng_key != config.projection_prng_key:
232
+ raise ValueError(
233
+ f"RandLora PRNG initialisation key must be the same for all adapters. Got {config.projection_prng_key=} but "
234
+ f"previous config had {existing_config.projection_prng_key}."
235
+ )
236
+
237
+ save_project_unique_values = sorted({config.save_projection for config in self.peft_config.values()})
238
+ if len(save_project_unique_values) > 1:
239
+ raise ValueError(
240
+ "RandLora projection weights must be saved for all adapters or none, but got multiple different values: "
241
+ f"{save_project_unique_values}"
242
+ )
243
+
244
+ def _create_and_replace(
245
+ self,
246
+ randlora_config,
247
+ adapter_name,
248
+ target,
249
+ target_name,
250
+ parent,
251
+ current_key,
252
+ **optional_kwargs,
253
+ ):
254
+ if current_key is None:
255
+ raise ValueError("Current Key shouldn't be `None`")
256
+
257
+ r = randlora_config.r
258
+ bias = hasattr(target, "bias") and target.bias is not None
259
+ kwargs = {
260
+ "r": r,
261
+ "randlora_alpha": randlora_config.randlora_alpha,
262
+ "randlora_dropout": randlora_config.randlora_dropout,
263
+ "fan_in_fan_out": randlora_config.fan_in_fan_out,
264
+ "init_weights": randlora_config.init_weights,
265
+ "loaded_in_8bit": getattr(self.model, "is_loaded_in_8bit", False),
266
+ "loaded_in_4bit": getattr(self.model, "is_loaded_in_4bit", False),
267
+ }
268
+ kwargs["bias"] = bias
269
+ if isinstance(target, Linear):
270
+ target.update_layer(
271
+ adapter_name,
272
+ self.randlora_A,
273
+ self.randlora_B,
274
+ r,
275
+ randlora_config.randlora_alpha,
276
+ randlora_config.randlora_dropout,
277
+ randlora_config.init_weights,
278
+ )
279
+ else:
280
+ new_module = self._create_new_module(
281
+ randlora_config, self.randlora_A, self.randlora_B, adapter_name, target, **kwargs
282
+ )
283
+ if adapter_name not in self.active_adapter:
284
+ # adding an additional adapter: it is not automatically trainable
285
+ new_module.requires_grad_(False)
286
+ self._replace_module(parent, target_name, new_module, target)
287
+
288
+ @staticmethod
289
+ def _create_new_module(randlora_config, randlora_A, randlora_B, adapter_name, target, **kwargs):
290
+ # avoid eager bnb import
291
+ if is_bnb_available():
292
+ import bitsandbytes as bnb
293
+
294
+ from .bnb import Linear8bitLt
295
+
296
+ if is_bnb_4bit_available():
297
+ from .bnb import Linear4bit
298
+
299
+ bias = kwargs.pop("bias", False)
300
+ loaded_in_8bit = kwargs.get("loaded_in_8bit", False)
301
+ loaded_in_4bit = kwargs.get("loaded_in_4bit", False)
302
+
303
+ if isinstance(target, BaseTunerLayer):
304
+ target_base_layer = target.get_base_layer()
305
+ else:
306
+ target_base_layer = target
307
+
308
+ if loaded_in_8bit and isinstance(target_base_layer, bnb.nn.Linear8bitLt):
309
+ eightbit_kwargs = kwargs.copy()
310
+ eightbit_kwargs.update(
311
+ {
312
+ "has_fp16_weights": target_base_layer.state.has_fp16_weights,
313
+ "threshold": target_base_layer.state.threshold,
314
+ "index": target_base_layer.index,
315
+ }
316
+ )
317
+ return Linear8bitLt(target, adapter_name, randlora_A, randlora_B, **eightbit_kwargs)
318
+ elif loaded_in_4bit and isinstance(target_base_layer, bnb.nn.Linear4bit):
319
+ fourbit_kwargs = kwargs.copy()
320
+ fourbit_kwargs.update(
321
+ {
322
+ "compute_dtype": target_base_layer.compute_dtype,
323
+ "compress_statistics": target_base_layer.weight.compress_statistics,
324
+ "quant_type": target_base_layer.weight.quant_type,
325
+ }
326
+ )
327
+ return Linear4bit(target, adapter_name, randlora_A, randlora_B, **fourbit_kwargs)
328
+ elif isinstance(target_base_layer, torch.nn.Linear):
329
+ if kwargs["fan_in_fan_out"]:
330
+ warnings.warn(
331
+ "fan_in_fan_out is set to True but the target module is `torch.nn.Linear`. "
332
+ "Setting fan_in_fan_out to False."
333
+ )
334
+ kwargs["fan_in_fan_out"] = randlora_config.fan_in_fan_out = False
335
+ elif isinstance(target_base_layer, Conv1D):
336
+ kwargs["is_target_conv_1d_layer"] = True
337
+ if not kwargs["fan_in_fan_out"]:
338
+ warnings.warn(
339
+ "fan_in_fan_out is set to False but the target module is `Conv1D`. Setting fan_in_fan_out to True."
340
+ )
341
+ kwargs["fan_in_fan_out"] = randlora_config.fan_in_fan_out = True
342
+ else:
343
+ raise ValueError(
344
+ f"Target module {target} is not supported. Currently, only the following modules are supported: "
345
+ "`torch.nn.Linear`, `transformers.pytorch_utils.Conv1D`."
346
+ )
347
+ new_module = Linear(
348
+ target,
349
+ randlora_A,
350
+ randlora_B,
351
+ adapter_name,
352
+ bias=bias,
353
+ **kwargs,
354
+ )
355
+
356
+ return new_module
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/road/__init__.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
16
+ # Based on implementation made available in https://github.com/ppetrushkov/peft/tree/road (not from paper authors)
17
+
18
+ from peft.import_utils import is_bnb_4bit_available, is_bnb_available
19
+ from peft.utils import register_peft_method
20
+
21
+ from .config import RoadConfig
22
+ from .layer import Linear, RoadLayer
23
+ from .model import RoadModel
24
+
25
+
26
+ __all__ = [
27
+ "Linear",
28
+ "RoadConfig",
29
+ "RoadLayer",
30
+ "RoadModel",
31
+ ]
32
+
33
+ register_peft_method(name="road", config_cls=RoadConfig, model_cls=RoadModel, is_mixed_compatible=True)
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
+ raise AttributeError(f"module {__name__} has no attribute {name}")
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/road/bnb.py ADDED
@@ -0,0 +1,407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 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
+
26
+ from .config import RoadVariant
27
+ from .layer import RoadLayer, _apply_road, _get_delta_weight
28
+
29
+
30
+ if is_bnb_available():
31
+
32
+ class Linear8bitLt(torch.nn.Module, RoadLayer):
33
+ # Road implemented in a dense layer
34
+ def __init__(
35
+ self,
36
+ base_layer: torch.nn.Module,
37
+ adapter_name: str,
38
+ variant: RoadVariant = "road_1",
39
+ group_size: int = 64,
40
+ init_weights: bool = True,
41
+ **kwargs,
42
+ ) -> None:
43
+ super().__init__()
44
+ RoadLayer.__init__(self, base_layer)
45
+
46
+ self._active_adapter = adapter_name
47
+ self.update_layer(
48
+ adapter_name,
49
+ variant=variant,
50
+ group_size=group_size,
51
+ init_weights=init_weights,
52
+ )
53
+
54
+ def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None:
55
+ """
56
+ Merge the active adapter weights into the base weights
57
+
58
+ Args:
59
+ safe_merge (`bool`, *optional*):
60
+ If True, the merge operation will be performed in a copy of the original weights and check for NaNs
61
+ before merging the weights. This is useful if you want to check if the merge operation will produce
62
+ NaNs. Defaults to `False`.
63
+ adapter_names (`list[str]`, *optional*):
64
+ The list of adapter names that should be merged. If None, all active adapters will be merged.
65
+ Defaults to `None`.
66
+ """
67
+ adapter_names = check_adapters_to_merge(self, adapter_names)
68
+ if not adapter_names:
69
+ # no adapter to merge
70
+ return
71
+
72
+ for active_adapter in adapter_names:
73
+ if active_adapter in self._available_adapters:
74
+ warnings.warn(
75
+ "Merge road module to 8-bit linear may get different generations due to rounding errors."
76
+ )
77
+
78
+ weight = self.get_base_layer().weight
79
+ state = self.get_base_layer().state
80
+ if state.SCB is None:
81
+ state.SCB = weight.SCB
82
+
83
+ # Dequantize the result of identity matrix and int8 weight because bitsandbytes does not support int8
84
+ # dequantization directly
85
+ output = dequantize_bnb_weight(weight, state=state)
86
+ road_R = _get_delta_weight(
87
+ self.variant[active_adapter],
88
+ self.group_size[active_adapter],
89
+ self.road_theta[active_adapter].data,
90
+ self.road_alpha[active_adapter].data,
91
+ )
92
+
93
+ w_data = torch.matmul(road_R, output.to(road_R.dtype))
94
+ w_data = w_data.to(road_R.dtype).to(road_R.device).contiguous()
95
+
96
+ if safe_merge and not torch.isfinite(w_data).all():
97
+ raise ValueError(
98
+ f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken"
99
+ )
100
+
101
+ self.get_base_layer().weight = bnb.nn.Int8Params(
102
+ w_data.to("cpu"), requires_grad=False, has_fp16_weights=weight.has_fp16_weights
103
+ ).to(weight.device)
104
+
105
+ if self.get_base_layer().bias is not None:
106
+ bias = self.get_base_layer().bias
107
+ orig_dtype = bias.dtype
108
+ bias_data = bias.data
109
+ new_bias = torch.matmul(road_R, bias_data.to(road_R.dtype))
110
+ bias.data = new_bias.to(orig_dtype)
111
+
112
+ state.reset_grads()
113
+ self.merged_adapters.append(active_adapter)
114
+
115
+ def unmerge(self) -> None:
116
+ """
117
+ This method unmerges all merged adapter layers from the base weights.
118
+ """
119
+ if not self.merged:
120
+ warnings.warn("Already unmerged. Nothing to do.")
121
+ return
122
+
123
+ while len(self.merged_adapters) > 0:
124
+ active_adapter = self.merged_adapters.pop()
125
+ if active_adapter in self._available_adapters:
126
+ warnings.warn(
127
+ "Unmerge road module to 8-bit linear may get different generations due to rounding errors."
128
+ )
129
+
130
+ weight = self.get_base_layer().weight
131
+ state = self.get_base_layer().state
132
+ if state.SCB is None:
133
+ state.SCB = weight.SCB
134
+ output = dequantize_bnb_weight(weight, state=state)
135
+
136
+ road_R = _get_delta_weight(
137
+ self.variant[active_adapter],
138
+ self.group_size[active_adapter],
139
+ self.road_theta[active_adapter].data,
140
+ self.road_alpha[active_adapter].data,
141
+ )
142
+ inv_road_R = torch.linalg.inv(road_R.to(torch.float32)).to(road_R.dtype)
143
+
144
+ w_data = torch.matmul(inv_road_R, output.to(road_R.dtype))
145
+ w_data = w_data.to(road_R.dtype).to(road_R.device).contiguous()
146
+
147
+ self.get_base_layer().weight = bnb.nn.Int8Params(
148
+ w_data.to("cpu"), requires_grad=False, has_fp16_weights=weight.has_fp16_weights
149
+ ).to(weight.device)
150
+
151
+ if self.get_base_layer().bias is not None:
152
+ bias = self.get_base_layer().bias
153
+ orig_dtype = bias.dtype
154
+ bias_data = bias.data
155
+ new_bias = torch.matmul(inv_road_R, bias_data)
156
+ bias.data = new_bias.to(orig_dtype)
157
+
158
+ state.reset_grads()
159
+
160
+ def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor:
161
+ if self.disable_adapters:
162
+ if self.merged:
163
+ self.unmerge()
164
+ result = self.base_layer(x, *args, **kwargs)
165
+ elif self.merged:
166
+ result = self.base_layer(x, *args, **kwargs)
167
+ else:
168
+ result = self.base_layer(x, *args, **kwargs)
169
+
170
+ for active_adapter in self.active_adapters:
171
+ if active_adapter not in self._available_adapters:
172
+ continue
173
+
174
+ requires_conversion = not torch.is_autocast_enabled()
175
+ if requires_conversion:
176
+ expected_dtype = result.dtype
177
+ result = self._cast_input_dtype(result, self.road_theta[active_adapter].dtype)
178
+
179
+ result = _apply_road(
180
+ self.variant[active_adapter],
181
+ self.group_size[active_adapter],
182
+ self.road_theta[active_adapter],
183
+ self.road_alpha[active_adapter],
184
+ result,
185
+ )
186
+
187
+ if requires_conversion:
188
+ x = x.to(expected_dtype)
189
+
190
+ return result
191
+
192
+ def __repr__(self) -> str:
193
+ rep = super().__repr__()
194
+ return "road." + rep
195
+
196
+ def dispatch_bnb_8bit(target: torch.nn.Module, adapter_name: str, **kwargs):
197
+ new_module = None
198
+
199
+ if isinstance(target, BaseTunerLayer):
200
+ target_base_layer = target.get_base_layer()
201
+ else:
202
+ target_base_layer = target
203
+
204
+ loaded_in_8bit = kwargs.get("loaded_in_8bit", False)
205
+ if loaded_in_8bit and isinstance(target_base_layer, bnb.nn.Linear8bitLt):
206
+ eightbit_kwargs = kwargs.copy()
207
+ eightbit_kwargs.update(
208
+ {
209
+ "has_fp16_weights": target.state.has_fp16_weights,
210
+ "threshold": target.state.threshold,
211
+ "index": target.index,
212
+ }
213
+ )
214
+ new_module = Linear8bitLt(target, adapter_name, **eightbit_kwargs)
215
+
216
+ return new_module
217
+
218
+
219
+ if is_bnb_4bit_available():
220
+
221
+ class Linear4bit(torch.nn.Module, RoadLayer):
222
+ # OFT implemented in a dense layer
223
+ def __init__(
224
+ self,
225
+ base_layer: torch.nn.Module,
226
+ adapter_name: str,
227
+ variant: RoadVariant = "road_1",
228
+ group_size: int = 64,
229
+ init_weights: bool = True,
230
+ **kwargs,
231
+ ) -> None:
232
+ super().__init__()
233
+ RoadLayer.__init__(self, base_layer)
234
+
235
+ self._active_adapter = adapter_name
236
+ self.update_layer(
237
+ adapter_name,
238
+ variant=variant,
239
+ group_size=group_size,
240
+ init_weights=init_weights,
241
+ )
242
+
243
+ def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None:
244
+ """
245
+ Merge the active adapter weights into the base weights
246
+
247
+ Args:
248
+ safe_merge (`bool`, *optional*):
249
+ If True, the merge operation will be performed in a copy of the original weights and check for NaNs
250
+ before merging the weights. This is useful if you want to check if the merge operation will produce
251
+ NaNs. Defaults to `False`.
252
+ adapter_names (`list[str]`, *optional*):
253
+ The list of adapter names that should be merged. If None, all active adapters will be merged.
254
+ Defaults to `None`.
255
+ """
256
+ adapter_names = check_adapters_to_merge(self, adapter_names)
257
+ if not adapter_names:
258
+ # no adapter to merge
259
+ return
260
+
261
+ for active_adapter in adapter_names:
262
+ if active_adapter in self._available_adapters:
263
+ warnings.warn(
264
+ "Merge oft module to 4-bit linear may get different generations due to rounding errors."
265
+ )
266
+ # Refer to https://gist.github.com/ChrisHayduk/1a53463331f52dca205e55982baf9930
267
+ weight = self.get_base_layer().weight
268
+ kwargs = weight.__dict__
269
+
270
+ output = dequantize_bnb_weight(weight, state=weight.quant_state)
271
+
272
+ road_R = _get_delta_weight(
273
+ self.variant[active_adapter],
274
+ self.group_size[active_adapter],
275
+ self.road_theta[active_adapter].data,
276
+ self.road_alpha[active_adapter].data,
277
+ )
278
+ w_data = torch.matmul(road_R, output.to(road_R.dtype))
279
+ w_data = w_data.to(road_R.dtype).to(road_R.device)
280
+
281
+ if safe_merge and not torch.isfinite(w_data).all():
282
+ raise ValueError(
283
+ f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken"
284
+ )
285
+
286
+ if "bnb_quantized" in kwargs:
287
+ kwargs["bnb_quantized"] = False
288
+ kwargs["requires_grad"] = False
289
+ kwargs.pop("data", None)
290
+ # torch.compile can introduce attributes preceded by '_', remove them
291
+ kwargs = {k: v for k, v in kwargs.items() if not k.startswith("_")}
292
+ self.get_base_layer().weight = bnb.nn.Params4bit(w_data.to("cpu"), **kwargs).to(weight.device)
293
+
294
+ if self.get_base_layer().bias is not None:
295
+ bias = self.get_base_layer().bias
296
+ orig_dtype = bias.dtype
297
+ bias_data = bias.data
298
+ new_bias = torch.matmul(road_R, bias_data.to(road_R.dtype))
299
+ bias.data = new_bias.to(orig_dtype)
300
+
301
+ self.merged_adapters.append(active_adapter)
302
+
303
+ def unmerge(self) -> None:
304
+ """
305
+ This method unmerges all merged adapter layers from the base weights.
306
+ """
307
+ if not self.merged:
308
+ warnings.warn("Already unmerged. Nothing to do.")
309
+ return
310
+
311
+ while len(self.merged_adapters) > 0:
312
+ active_adapter = self.merged_adapters.pop()
313
+ if active_adapter in self._available_adapters:
314
+ warnings.warn(
315
+ "Unmerge oft module to 4-bit linear may get different generations due to rounding errors."
316
+ )
317
+
318
+ weight = self.get_base_layer().weight
319
+ kwargs = weight.__dict__
320
+ output = dequantize_bnb_weight(weight, state=weight.quant_state)
321
+
322
+ road_R = _get_delta_weight(
323
+ self.variant[active_adapter],
324
+ self.group_size[active_adapter],
325
+ self.road_theta[active_adapter].data,
326
+ self.road_alpha[active_adapter].data,
327
+ )
328
+ inv_road_R = torch.linalg.inv(road_R.to(torch.float32)).to(road_R.dtype)
329
+
330
+ w_data = torch.matmul(inv_road_R, output.to(road_R.dtype))
331
+ w_data = w_data.to(road_R.dtype).to(road_R.device)
332
+
333
+ if "bnb_quantized" in kwargs:
334
+ kwargs["bnb_quantized"] = False
335
+ kwargs["requires_grad"] = False
336
+ kwargs.pop("data", None)
337
+ self.get_base_layer().weight = bnb.nn.Params4bit(w_data.to("cpu"), **kwargs).to(weight.device)
338
+
339
+ if self.get_base_layer().bias is not None:
340
+ bias = self.get_base_layer().bias
341
+ orig_dtype = bias.dtype
342
+ bias_data = bias.data
343
+ new_bias = torch.matmul(inv_road_R, bias_data)
344
+ bias.data = new_bias.to(orig_dtype)
345
+
346
+ def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor:
347
+ if self.disable_adapters:
348
+ if self.merged:
349
+ self.unmerge()
350
+ result = self.base_layer(x, *args, **kwargs)
351
+ elif self.merged:
352
+ result = self.base_layer(x, *args, **kwargs)
353
+ else:
354
+ result = self.base_layer(x, *args, **kwargs)
355
+ # As per Tim Dettmers, for 4bit, we need to defensively clone here.
356
+ # The reason is that in some cases, an error can occur that backprop
357
+ # does not work on a manipulated view. This issue may be solved with
358
+ # newer PyTorch versions but this would need extensive testing to be
359
+ # sure.
360
+ # result = result.clone()
361
+
362
+ for active_adapter in self.active_adapters:
363
+ if active_adapter not in self._available_adapters:
364
+ continue
365
+
366
+ requires_conversion = not torch.is_autocast_enabled()
367
+ if requires_conversion:
368
+ expected_dtype = result.dtype
369
+ result = self._cast_input_dtype(result, self.road_theta[active_adapter].dtype)
370
+
371
+ result = _apply_road(
372
+ self.variant[active_adapter],
373
+ self.group_size[active_adapter],
374
+ self.road_theta[active_adapter],
375
+ self.road_alpha[active_adapter],
376
+ result,
377
+ )
378
+ if requires_conversion:
379
+ x = x.to(expected_dtype)
380
+
381
+ return result
382
+
383
+ def __repr__(self) -> str:
384
+ rep = super().__repr__()
385
+ return "oft." + rep
386
+
387
+ def dispatch_bnb_4bit(target: torch.nn.Module, adapter_name: str, **kwargs):
388
+ new_module = None
389
+
390
+ if isinstance(target, BaseTunerLayer):
391
+ target_base_layer = target.get_base_layer()
392
+ else:
393
+ target_base_layer = target
394
+
395
+ loaded_in_4bit = kwargs.get("loaded_in_4bit", False)
396
+ if loaded_in_4bit and is_bnb_4bit_available() and isinstance(target_base_layer, bnb.nn.Linear4bit):
397
+ fourbit_kwargs = kwargs.copy()
398
+ fourbit_kwargs.update(
399
+ {
400
+ "compute_dtype": target_base_layer.compute_dtype,
401
+ "compress_statistics": target_base_layer.weight.compress_statistics,
402
+ "quant_type": target_base_layer.weight.quant_type,
403
+ }
404
+ )
405
+ new_module = Linear4bit(target, adapter_name, **fourbit_kwargs)
406
+
407
+ return new_module
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/road/config.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 __future__ import annotations
16
+
17
+ from dataclasses import dataclass, field
18
+ from typing import Literal, Optional, Union
19
+
20
+ from peft.config import PeftConfig
21
+ from peft.utils import PeftType
22
+
23
+
24
+ RoadVariant = Literal["road_1", "road_2", "road_4"]
25
+
26
+
27
+ @dataclass
28
+ class RoadConfig(PeftConfig):
29
+ """
30
+ This is the configuration class to store the configuration of a [`RoadModel`]. RoAd adapter is proposed in
31
+ https://huggingface.co/papers/2409.00119.
32
+
33
+ Args:
34
+ variant (Union[`RoadVariant`, `str`]):
35
+ The variant of the Road model to use. It can be one of road_1, road_2, or road_4. Refer to the paper for
36
+ more details.
37
+ - road_1: Uses the same scale and angle for all pairs of elements.
38
+ This variant has lowest number of parameters, it stores a number equal to the output hidden size of
39
+ parameters for each layer that RoAd is applied to.
40
+ - road_2: Uses the same scale and angle for each element.
41
+ This variant has 2x the number of parameters compared to road_1.
42
+ - road_4: Uses two different scales and angles for each ellement.
43
+ This variant has 4x the number of parameters compared to road_1.
44
+ group_size (`int`):
45
+ Group size defines how elements are grouped together into 2D vectors for rotation. Within each group
46
+ element 0 is paired with element group_size/2, then element 1 is paired with element group_size/2+1 and so
47
+ on. This has no effect on the model performance, since elements are unordered, however it has some effect
48
+ on inference speed when used in e.g. VLLM. For best speed group size of at least 32 or 64 (the default) is
49
+ recommended. Note that model hidden size (or hidden size per partition when used with tensor parallelism)
50
+ must be divisible by group_size, so for very small models you might need to reduce this parameter.
51
+ init_weights (`bool`):
52
+ Whether to perform initialization of RoAd weights.
53
+ target_modules (`Optional[Union[List[str], str]]`):
54
+ The names of the modules to apply the adapter to. If this is specified, only the modules with the specified
55
+ names will be replaced. When passing a string, a regex match will be performed. When passing a list of
56
+ strings, either an exact match will be performed or it is checked if the name of the module ends with any
57
+ of the passed strings. If this is specified as 'all-linear', then all linear/Conv1D modules are chosen (if
58
+ the model is a PreTrainedModel, the output layer excluded). If this is not specified, modules will be
59
+ chosen according to the model architecture. If the architecture is not known, an error will be raised -- in
60
+ this case, you should specify the target modules manually.
61
+ modules_to_save (`List[str]`):
62
+ List of modules apart from Road layers to be set as trainable and saved in the final checkpoint.
63
+ """
64
+
65
+ variant: Union[str, RoadVariant] = field(
66
+ default="road_1",
67
+ metadata={"help": ("Variant of the Road model to use.")},
68
+ )
69
+ group_size: int = field(
70
+ default=64,
71
+ metadata={
72
+ "help": (
73
+ "Group size defines how elements are grouped together into 2D vectors for rotation. "
74
+ "Within each group element 0 is paired with element group_size/2, "
75
+ "then element 1 is paired with element group_size/2+1 and so on. "
76
+ "This has no effect on the model performance, since elements are unordered, "
77
+ "however it has some effect on inference speed when used in e.g. VLLM. "
78
+ "For best speed group size of at least 64 is recommended. "
79
+ "Note that model hidden size (or hidden size per partition when used with tensor parallelism) "
80
+ "must be divisible by group_size, so for very small models you might need to reduce this parameter."
81
+ )
82
+ },
83
+ )
84
+ init_weights: bool = field(
85
+ default=True,
86
+ metadata={
87
+ "help": (
88
+ "Whether to initialize the weights of the RoAd layers with their default initialization. Don't change "
89
+ "this setting, except if you know exactly what you're doing."
90
+ ),
91
+ },
92
+ )
93
+ target_modules: Optional[Union[list[str], str]] = field(
94
+ default=None,
95
+ metadata={
96
+ "help": (
97
+ "List of module names or regex expression of the module names to replace with Road."
98
+ "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'."
99
+ "This can also be a wildcard 'all-linear' which matches all linear/Conv1D "
100
+ "(if the model is a PreTrainedModel, the output layer excluded)."
101
+ "If not specified, modules will be chosen according to the model architecture, If the architecture is "
102
+ "not known, an error will be raised -- in this case, you should specify the target modules manually."
103
+ ),
104
+ },
105
+ )
106
+ modules_to_save: Optional[list[str]] = field(
107
+ default=None,
108
+ metadata={
109
+ "help": (
110
+ "List of modules apart from RoAd layers to be set as trainable and saved in the final checkpoint. For"
111
+ " example, in Sequence Classification or Token Classification tasks, the final layer"
112
+ " `classifier/score` are randomly initialized and as such need to be trainable and saved."
113
+ )
114
+ },
115
+ )
116
+
117
+ def __post_init__(self):
118
+ super().__post_init__()
119
+ self.peft_type = PeftType.ROAD
120
+ self.target_modules = (
121
+ set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules
122
+ )
123
+ if self.variant not in ["road_1", "road_2", "road_4"]:
124
+ raise ValueError(f"Invalid variant {self.variant} specified. Please choose from road_1, road_2 or road_4")
125
+ if self.group_size <= 0 or self.group_size % 2 != 0:
126
+ raise ValueError(f"The group_size must be divisible by 2 when using RoadLayer, but got {self.group_size}.")
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/road/layer.py ADDED
@@ -0,0 +1,418 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 warnings
16
+ from typing import Any, Optional, Union
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+
21
+ from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge
22
+
23
+ from .config import RoadConfig, RoadVariant
24
+
25
+
26
+ class RoadLayer(BaseTunerLayer):
27
+ """
28
+ Road layer.
29
+
30
+ Generally the idea of RoAD is to split the input vector into many 2D vectors and rotate each 2D vector with its own
31
+ 2D rotation matrix. For additional flexibility, each rotation matrix is multiplied by a trainable scale.
32
+
33
+ when applied to vector R @ x each pair of elements of x is transformed like this: `y₀ = x₀ * α * cosθ - xₙ * α *
34
+ sinθ` and `yₙ = x₀ * α * sinθ + xₙ * α * cosθ`
35
+
36
+ The scales α and angles θ are learned for each pair of elements and, moreover, each of the 4 instances in the
37
+ rotation matrix may actually be different (when using variant 2 or 4).
38
+
39
+ Note that instead of using two consecutive elements x₀ x₁ we first split the whole vector into groups and pair
40
+ elements from the first with the second half of the same group, which allows for more efficient inference
41
+ implementation.
42
+
43
+ The adapter needs to only store the angles θ and scales α, rather than the full matrix R and the inference
44
+ implementation only needs to do elementwise vector multiplications.
45
+
46
+ For merging the weights, we make use of the following formula: R @ (W @ x + b) = (R @ W) @ x + R @ b. The lhs part
47
+ is how it is used in unmerged state (using efficient elementwise implementation instead of matrix multiplication)
48
+ and the rhs part is how it is used in merged state where (R @ W) becomes the new weight matrix and R @ b becomes
49
+ the new bias.
50
+
51
+ """
52
+
53
+ adapter_layer_names: tuple[str, ...] = ("road_theta", "road_alpha")
54
+ other_param_names: tuple[str, ...] = ("variant", "group_size")
55
+
56
+ def __init__(self, base_layer: nn.Module, ephemeral_gpu_offload: bool = False, **kwargs) -> None:
57
+ self.base_layer = base_layer
58
+ self.variant = {}
59
+ self.group_size = {}
60
+ self.road_theta = nn.ParameterDict({})
61
+ self.road_alpha = nn.ParameterDict({})
62
+
63
+ self._disable_adapters = False
64
+ self.merged_adapters = []
65
+
66
+ base_layer = self.get_base_layer()
67
+ if isinstance(base_layer, nn.Linear):
68
+ in_features, out_features = base_layer.in_features, base_layer.out_features
69
+ else:
70
+ raise ValueError(f"Unsupported layer type '{type(base_layer)}' encountered, cannot apply RoAd adapter.")
71
+ self.in_features = in_features
72
+ self.out_features = out_features
73
+
74
+ @property
75
+ def _available_adapters(self) -> set[str]:
76
+ return {*self.road_theta}
77
+
78
+ def update_layer(
79
+ self,
80
+ adapter_name,
81
+ variant,
82
+ group_size,
83
+ init_weights,
84
+ inference_mode: bool = False,
85
+ ):
86
+ self.variant[adapter_name] = variant
87
+ self.group_size[adapter_name] = group_size
88
+
89
+ if self.out_features % group_size != 0:
90
+ raise ValueError(
91
+ f"The out_features of the base layer must be divisible by group_size ({group_size}) when using RoadLayer."
92
+ )
93
+
94
+ # Actual trainable parameters
95
+ if variant == "road_1":
96
+ size = self.out_features // 2
97
+ elif variant == "road_2":
98
+ size = self.out_features
99
+ elif variant == "road_4":
100
+ size = self.out_features * 2
101
+ else:
102
+ raise ValueError(
103
+ f"Unsupported variant {variant} for RoadLayer. Supported variants are road_1, road_2, and road_4."
104
+ )
105
+ self.road_theta[adapter_name] = nn.Parameter(torch.empty(size))
106
+ self.road_alpha[adapter_name] = nn.Parameter(torch.empty(size))
107
+
108
+ self.reset_parameters(adapter_name, init_weights)
109
+ self._move_adapter_to_device_of_base_layer(adapter_name)
110
+
111
+ self.set_adapter(self.active_adapters, inference_mode=inference_mode)
112
+
113
+ def reset_parameters(self, adapter_name, init_weights):
114
+ if init_weights is False:
115
+ nn.init.normal_(self.road_theta[adapter_name].data, mean=0.0, std=0.5)
116
+ nn.init.normal_(self.road_alpha[adapter_name].data, mean=1.0, std=0.5)
117
+ return
118
+ nn.init.zeros_(self.road_theta[adapter_name].data)
119
+ nn.init.ones_(self.road_alpha[adapter_name].data)
120
+
121
+
122
+ class Linear(nn.Module, RoadLayer):
123
+ # Road implemented in a dense layer
124
+ def __init__(
125
+ self,
126
+ base_layer,
127
+ adapter_name: str,
128
+ variant: RoadVariant = "road_1",
129
+ group_size: int = 64,
130
+ init_weights: Union[bool, str] = True,
131
+ **kwargs,
132
+ ) -> None:
133
+ super().__init__()
134
+ RoadLayer.__init__(self, base_layer, **kwargs)
135
+
136
+ self._active_adapter = adapter_name
137
+
138
+ self.update_layer(
139
+ adapter_name,
140
+ variant,
141
+ group_size,
142
+ init_weights=init_weights,
143
+ )
144
+
145
+ def _check_forward_args(self, x, *args, **kwargs):
146
+ """Check if the arguments are compatible with the configs and state of the model"""
147
+ adapter_names = kwargs.get("adapter_names", None)
148
+ if adapter_names is None:
149
+ return
150
+
151
+ if len(x) != len(adapter_names):
152
+ msg = (
153
+ "Length of `adapter_names` should be the same as the number of inputs, but got "
154
+ f"{len(adapter_names)} and {len(x)} respectively."
155
+ )
156
+ raise ValueError(msg)
157
+
158
+ if self.merged:
159
+ # It is unclear what would be the right thing to do if users pass adapter_names and there are merged
160
+ # adapters. Therefore, it is better to raise an error in this case.
161
+ msg = "Cannot pass `adapter_names` when there are merged adapters, please call `unmerge_adapter` first."
162
+ raise ValueError(msg)
163
+
164
+ def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor:
165
+ self._check_forward_args(x, *args, **kwargs)
166
+ adapter_names = kwargs.pop("adapter_names", None)
167
+
168
+ if self.disable_adapters:
169
+ if self.merged:
170
+ self.unmerge()
171
+ result = self.base_layer(x, *args, **kwargs)
172
+ elif self.merged:
173
+ result = self.base_layer(x, *args, **kwargs)
174
+ elif adapter_names is not None:
175
+ result = self._mixed_batch_forward(x, *args, adapter_names=adapter_names, **kwargs)
176
+ else:
177
+ result = self.base_layer(x, *args, **kwargs)
178
+ torch_result_dtype = result.dtype
179
+
180
+ for active_adapter in self.active_adapters:
181
+ if active_adapter not in self._available_adapters:
182
+ continue
183
+
184
+ result = self._cast_input_dtype(result, self.road_theta[active_adapter].dtype)
185
+ result = _apply_road(
186
+ self.variant[active_adapter],
187
+ self.group_size[active_adapter],
188
+ self.road_theta[active_adapter],
189
+ self.road_alpha[active_adapter],
190
+ result,
191
+ )
192
+
193
+ result = result.to(torch_result_dtype)
194
+
195
+ return result
196
+
197
+ def _mixed_batch_forward(
198
+ self, x: torch.Tensor, *args: Any, adapter_names: list[str], **kwargs: Any
199
+ ) -> torch.Tensor:
200
+ # This is a special method that handles the case when users pass the argument `adapter_names`. This is an
201
+ # extra argument that allows mixing different adapters in the same batch at inference time.
202
+ result = self.base_layer(x, *args, **kwargs)
203
+
204
+ unique_adapters = set(adapter_names)
205
+ sub_batch_indices_list = []
206
+ for adapter in unique_adapters:
207
+ sub_batch_indices_list.append([index for index, item in enumerate(adapter_names) if item == adapter])
208
+
209
+ for i, active_adapter in enumerate(unique_adapters):
210
+ if active_adapter == "__base__":
211
+ continue
212
+ if active_adapter not in self._available_adapters:
213
+ continue
214
+
215
+ dtype = self.road_theta[active_adapter].data.dtype
216
+
217
+ # getting the sub-batch, passing it to Road layers and updating the corresponding indices of the linear
218
+ # layer output
219
+ sub_batch = result[sub_batch_indices_list[i]].to(dtype)
220
+ result[sub_batch_indices_list[i]] = _apply_road(
221
+ self.variant[active_adapter],
222
+ self.group_size[active_adapter],
223
+ self.road_theta[active_adapter],
224
+ self.road_alpha[active_adapter],
225
+ sub_batch,
226
+ )
227
+
228
+ return result
229
+
230
+ def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None:
231
+ """
232
+ Merge the active adapter weights into the base weights
233
+
234
+ Args:
235
+ safe_merge (`bool`, *optional*):
236
+ If `True`, the merge operation will be performed in a copy of the original weights and check for NaNs
237
+ before merging the weights. This is useful if you want to check if the merge operation will produce
238
+ NaNs. Defaults to `False`.
239
+ adapter_names (`List[str]`, *optional*):
240
+ The list of adapter names that should be merged. If `None`, all active adapters will be merged.
241
+ Defaults to `None`.
242
+ """
243
+ adapter_names = check_adapters_to_merge(self, adapter_names)
244
+ if not adapter_names:
245
+ # no adapter to merge
246
+ return
247
+
248
+ for active_adapter in adapter_names:
249
+ if active_adapter in self._available_adapters:
250
+ base_layer = self.get_base_layer()
251
+ orig_dtype = base_layer.weight.dtype
252
+ road_R = _get_delta_weight(
253
+ self.variant[active_adapter],
254
+ self.group_size[active_adapter],
255
+ self.road_theta[active_adapter].data,
256
+ self.road_alpha[active_adapter].data,
257
+ )
258
+ if safe_merge:
259
+ # Note that safe_merge will be slower than the normal merge
260
+ # because of the copy operation.
261
+ orig_weight = base_layer.weight.data.clone()
262
+ orig_weight = torch.matmul(road_R.to(orig_dtype), orig_weight)
263
+
264
+ if not torch.isfinite(orig_weight).all():
265
+ raise ValueError(
266
+ f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken"
267
+ )
268
+
269
+ base_layer.weight.data = orig_weight.contiguous().to(orig_dtype)
270
+
271
+ if base_layer.bias is not None:
272
+ orig_bias = base_layer.bias.clone()
273
+ orig_bias = torch.matmul(road_R.to(orig_dtype), orig_bias)
274
+
275
+ if not torch.isfinite(orig_bias).all():
276
+ raise ValueError(
277
+ f"NaNs detected in the merged bias. The adapter {active_adapter} seems to be broken"
278
+ )
279
+
280
+ base_layer.bias.data = orig_bias.contiguous().to(orig_dtype)
281
+ else:
282
+ orig_weight = base_layer.weight.data
283
+ orig_weight = torch.matmul(road_R.to(orig_dtype), orig_weight)
284
+ base_layer.weight.data = orig_weight.contiguous().to(orig_dtype)
285
+
286
+ if base_layer.bias is not None:
287
+ orig_bias = base_layer.bias.data
288
+ orig_bias = torch.matmul(road_R.to(orig_dtype), orig_bias)
289
+ base_layer.bias.data = orig_bias.contiguous().to(orig_dtype)
290
+
291
+ self.merged_adapters.append(active_adapter)
292
+
293
+ def unmerge(self) -> None:
294
+ """
295
+ This method unmerges all merged adapter layers from the base weights.
296
+ """
297
+ if not self.merged:
298
+ warnings.warn("Already unmerged. Nothing to do.")
299
+ return
300
+ while len(self.merged_adapters) > 0:
301
+ # Going in reverse order
302
+ active_adapter = self.merged_adapters.pop()
303
+ if active_adapter in self._available_adapters:
304
+ weight = self.get_base_layer().weight
305
+ orig_dtype = weight.dtype
306
+ road_R = _get_delta_weight(
307
+ self.variant[active_adapter],
308
+ self.group_size[active_adapter],
309
+ self.road_theta[active_adapter].data,
310
+ self.road_alpha[active_adapter].data,
311
+ )
312
+ # Since our matrix are not necessarily orthogonal we need inverse instead of transpose.
313
+ # In practice we expect this to basically always work since we start from block diagonal rotation matrix.
314
+ inv_road_R = torch.linalg.inv(road_R.to(torch.float32)).to(orig_dtype)
315
+ orig_weight = torch.matmul(inv_road_R, weight.data)
316
+ weight.data = orig_weight.contiguous()
317
+
318
+ if self.get_base_layer().bias is not None:
319
+ orig_bias = torch.matmul(inv_road_R, self.get_base_layer().bias.data)
320
+ self.get_base_layer().bias.data = orig_bias.contiguous()
321
+
322
+ def __repr__(self) -> str:
323
+ rep = super().__repr__()
324
+ return "road." + rep
325
+
326
+
327
+ def _get_delta_weight(variant: RoadVariant, group_size: int, road_theta: torch.Tensor, road_alpha: torch.Tensor):
328
+ first_col, second_col = _prepare_cols(variant, group_size, road_theta, road_alpha)
329
+
330
+ # To help understand the logic below consider how rope embeddings work
331
+ # here it is similar, but done in groups.
332
+ # https://discuss.huggingface.co/t/is-llama-rotary-embedding-implementation-correct/44509/3
333
+
334
+ # First column is simply put on the main diagonal
335
+ output_tensor = torch.diag(first_col)
336
+ # For second column we need to swap each half groups and add minus sign
337
+ size = second_col.shape[0]
338
+ swapped_second_col = second_col.reshape(-1, 2, group_size // 2)[:, [1, 0], :].flatten()
339
+ rotated_diag_second_col = torch.diag(swapped_second_col).reshape(-1, 2, group_size // 2, size)[:, [1, 0], :, :]
340
+ rotated_diag_second_col[:, 0, :, :] *= -1
341
+ rotated_diag_second_col = rotated_diag_second_col.reshape(size, size)
342
+ output_tensor += rotated_diag_second_col
343
+
344
+ return output_tensor
345
+
346
+
347
+ def _prepare_cols(
348
+ variant: RoadVariant, group_size: int, road_theta: torch.Tensor, road_alpha: torch.Tensor
349
+ ) -> tuple[torch.Tensor, torch.Tensor]:
350
+ # In inference mode, this can be cached
351
+ if variant == "road_1":
352
+ # In each group there are only group_size // 2 parameters that are reused
353
+ road_theta = road_theta.reshape(-1, group_size // 2).repeat_interleave(2, dim=0).flatten()
354
+ road_alpha = road_alpha.reshape(-1, group_size // 2).repeat_interleave(2, dim=0).flatten()
355
+
356
+ theta_cos = road_theta.cos()
357
+ theta_sin = road_theta.sin()
358
+
359
+ first_col = road_alpha * theta_cos
360
+ second_col = road_alpha * theta_sin
361
+ elif variant == "road_2":
362
+ # Each group has exactly group_size parameters
363
+ theta_cos = road_theta.cos()
364
+ theta_sin = road_theta.sin()
365
+
366
+ first_col = road_alpha * theta_cos
367
+ second_col = road_alpha * theta_sin
368
+ elif variant == "road_4":
369
+ # Each group has 2*group_size parameters, first half used for first column, second half for second column
370
+ road_theta = road_theta.reshape(-1, 2, group_size)
371
+ theta_cos = road_theta[:, 0, :].cos().flatten()
372
+ theta_sin = road_theta[:, 1, :].sin().flatten()
373
+ road_alpha = road_alpha.reshape(-1, 2, group_size)
374
+ alpha_1 = road_alpha[:, 0, :].flatten()
375
+ alpha_2 = road_alpha[:, 1, :].flatten()
376
+
377
+ first_col = alpha_1 * theta_cos
378
+ second_col = alpha_2 * theta_sin
379
+ else:
380
+ raise ValueError(
381
+ f"Unsupported variant {variant} for RoadLayer. Supported variants are road_1, road_2, and road_4."
382
+ )
383
+
384
+ return first_col, second_col
385
+
386
+
387
+ def _apply_road(
388
+ variant: RoadVariant, group_size: int, road_theta: torch.Tensor, road_alpha: torch.Tensor, x: torch.Tensor
389
+ ):
390
+ first_col, second_col = _prepare_cols(variant, group_size, road_theta, road_alpha)
391
+
392
+ # Split in half groups and join back
393
+ # See equation 4 in the RoAD paper
394
+ x_grouped = x.reshape(-1, 2, group_size // 2)
395
+ x1 = x_grouped[:, 0, :]
396
+ x2 = x_grouped[:, 1, :]
397
+ rotate_half_x = torch.stack((-x2, x1), dim=1).reshape(x.shape)
398
+ result = x * first_col + rotate_half_x * second_col
399
+ return result
400
+
401
+
402
+ def dispatch_default(
403
+ target: torch.nn.Module,
404
+ adapter_name: str,
405
+ road_config: RoadConfig,
406
+ **kwargs,
407
+ ) -> Optional[torch.nn.Module]:
408
+ new_module = None
409
+
410
+ if isinstance(target, BaseTunerLayer):
411
+ target_base_layer = target.get_base_layer()
412
+ else:
413
+ target_base_layer = target
414
+
415
+ if isinstance(target_base_layer, torch.nn.Linear):
416
+ new_module = Linear(target, adapter_name, **kwargs)
417
+
418
+ return new_module
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/road/model.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 operator
17
+ from contextlib import contextmanager
18
+ from functools import partial
19
+
20
+ from torch import nn
21
+
22
+ from peft.import_utils import is_bnb_4bit_available, is_bnb_available
23
+ from peft.tuners.road.config import RoadConfig
24
+ from peft.tuners.tuners_utils import (
25
+ BaseTuner,
26
+ get_device_map,
27
+ )
28
+ from peft.utils import TRANSFORMERS_MODELS_TO_ROAD_TARGET_MODULES_MAPPING
29
+
30
+ from .layer import RoadLayer, dispatch_default
31
+
32
+
33
+ def _adapter_names_pre_forward_hook(target, args, kwargs, adapter_names):
34
+ # pre-forward hook to inject the adapter_names argument when using mixed adapter batches inference
35
+ kwargs["adapter_names"] = adapter_names
36
+ return args, kwargs
37
+
38
+
39
+ class RoadModel(BaseTuner):
40
+ """ """
41
+
42
+ prefix: str = "road_"
43
+ tuner_layer_cls = RoadLayer
44
+ target_module_mapping = TRANSFORMERS_MODELS_TO_ROAD_TARGET_MODULES_MAPPING
45
+
46
+ def _create_and_replace(
47
+ self,
48
+ road_config: RoadConfig,
49
+ adapter_name: str,
50
+ target: nn.Module,
51
+ target_name: str,
52
+ parent: nn.Module,
53
+ current_key,
54
+ ) -> None:
55
+ if current_key is None:
56
+ raise ValueError("Current Key shouldn't be `None`")
57
+
58
+ # Regexp matching - Find key which matches current target_name in patterns provided
59
+ variant = road_config.variant
60
+ group_size = road_config.group_size
61
+
62
+ kwargs = {
63
+ "variant": variant,
64
+ "group_size": group_size,
65
+ "init_weights": road_config.init_weights,
66
+ "loaded_in_8bit": getattr(self.model, "is_loaded_in_8bit", False),
67
+ "loaded_in_4bit": getattr(self.model, "is_loaded_in_4bit", False),
68
+ }
69
+ # for torchao merging, we need the get_apply_tensor_subclass from the quantization config
70
+ try:
71
+ kwargs["get_apply_tensor_subclass"] = operator.attrgetter(
72
+ "hf_quantizer.quantization_config.get_apply_tensor_subclass"
73
+ )(self.model)
74
+ except AttributeError:
75
+ pass
76
+
77
+ if isinstance(target, RoadLayer):
78
+ target.update_layer(
79
+ adapter_name,
80
+ variant,
81
+ group_size,
82
+ init_weights=road_config.init_weights,
83
+ )
84
+ else:
85
+ device_map = get_device_map(self.model)
86
+ new_module = self._create_new_module(road_config, adapter_name, target, device_map=device_map, **kwargs)
87
+ if adapter_name not in self.active_adapters:
88
+ # adding an additional adapter: it is not automatically trainable
89
+ new_module.requires_grad_(False)
90
+ self._replace_module(parent, target_name, new_module, target)
91
+
92
+ @staticmethod
93
+ def _create_new_module(road_config: RoadConfig, adapter_name, target, **kwargs):
94
+ dispatchers = []
95
+
96
+ # avoid eager bnb import
97
+ if is_bnb_available():
98
+ from .bnb import dispatch_bnb_8bit
99
+
100
+ dispatchers.append(dispatch_bnb_8bit)
101
+
102
+ if is_bnb_4bit_available():
103
+ from .bnb import dispatch_bnb_4bit
104
+
105
+ dispatchers.append(dispatch_bnb_4bit)
106
+
107
+ dispatchers.extend(
108
+ [
109
+ dispatch_default,
110
+ ]
111
+ )
112
+
113
+ new_module = None
114
+ for dispatcher in dispatchers:
115
+ new_module = dispatcher(target, adapter_name, road_config=road_config, **kwargs)
116
+ if new_module is not None: # first match wins
117
+ break
118
+
119
+ if new_module is None:
120
+ # no module could be matched
121
+ raise ValueError(
122
+ f"Target module {target} is not supported. Currently, only the following modules are supported: "
123
+ "`torch.nn.Linear`."
124
+ )
125
+
126
+ return new_module
127
+
128
+ @contextmanager
129
+ def _enable_peft_forward_hooks(self, *args, **kwargs):
130
+ # If adapter_names is passed as an argument, we inject it into the forward arguments.
131
+ adapter_names = kwargs.pop("adapter_names", None)
132
+ if adapter_names is None:
133
+ # nothing to do
134
+ yield
135
+ return
136
+
137
+ if self.training:
138
+ raise ValueError("Cannot pass `adapter_names` when the model is in training mode.")
139
+
140
+ # Check that users only passed actually existing adapters.
141
+ # Note: We cannot do this on the layer level, as each individual layer may not have each adapter. Still, we want
142
+ # to check that there is at least one layer with the given name, or else something like typos can easily slip.
143
+ expected_adapters = set()
144
+ for layer in self.modules():
145
+ if isinstance(layer, RoadLayer):
146
+ expected_adapters |= layer.road_theta.keys()
147
+ unique_adapters = {name for name in adapter_names if name != "__base__"}
148
+ unexpected_adapters = unique_adapters - expected_adapters
149
+ if unexpected_adapters:
150
+ raise ValueError(f"Trying to infer with non-existing adapter(s): {', '.join(sorted(unexpected_adapters))}")
151
+
152
+ hook_handles = []
153
+ for module in self.modules():
154
+ if isinstance(module, RoadLayer):
155
+ pre_forward = partial(_adapter_names_pre_forward_hook, adapter_names=adapter_names)
156
+ handle = module.register_forward_pre_hook(pre_forward, with_kwargs=True)
157
+ hook_handles.append(handle)
158
+
159
+ # TODO LoRA also has hooks for beam search, ignore this for now
160
+
161
+ yield
162
+
163
+ for handle in hook_handles:
164
+ handle.remove()
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/shira/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 peft.utils import register_peft_method
16
+
17
+ from .config import ShiraConfig
18
+ from .layer import Linear, ShiraLayer
19
+ from .model import ShiraModel
20
+
21
+
22
+ __all__ = ["Linear", "ShiraConfig", "ShiraLayer", "ShiraModel"]
23
+
24
+
25
+ register_peft_method(
26
+ name="shira", config_cls=ShiraConfig, model_cls=ShiraModel, prefix="shira_", is_mixed_compatible=True
27
+ )
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/shira/config.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 __future__ import annotations
16
+
17
+ import warnings
18
+ from dataclasses import dataclass, field
19
+ from typing import Literal, Optional, Union
20
+
21
+ from peft.config import PeftConfig
22
+ from peft.utils import PeftType
23
+
24
+ from .mask_functions import random_mask
25
+
26
+
27
+ @dataclass
28
+ class ShiraConfig(PeftConfig):
29
+ """
30
+ This is the configuration class to store the configuration of a [`ShiraModel`].
31
+
32
+ Args:
33
+ r (`int`, *optional*, defaults to `32`):
34
+ For a given target module, the number of SHiRA parameters is computed as r(m+n), where the original tensor
35
+ dimensions are m x n. This means the number of SHiRA parameters is the same as that for a LoRA adapter.
36
+ SHiRA is a high rank adapter. Setting this r parameter does not restrict the rank to this value.
37
+ mask_type (`str`, defaults to `random`):
38
+ Type of mask function. Defaults to a random sparse mask. An optional user-defined mask_fn to compute the
39
+ mask value can also be supplied by instantiating `config = ShiraConfig(...)` and then setting
40
+ `config.mask_fn = <your custom mask function>`. For a pretrained weight with shape m x n, the custom mask
41
+ function must return only one mask (shape: m x n) which must be binary 0 or 1 with num_shira_parameters =
42
+ r(m + n) for linear layers. Device and dtype of mask must be same as base layer's weight's device and
43
+ dtype. Please see mask_functions.py for more details and to see the default random sparse mask
44
+ implementation.
45
+ random_seed (`int`, *optional*, defaults to `None`):
46
+ random seed for the torch generator for random_mask.
47
+ target_modules (`Union[List[str], str]`):
48
+ List of module names or regex expression of the module names to replace with SHiRA. For example, ['q', 'v']
49
+ or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'. Only linear layers are supported.
50
+ fan_in_fan_out (`bool`):
51
+ Set this to True if the layer to replace stores weight like (fan_in, fan_out). For example, gpt-2 uses
52
+ `Conv1D` which stores weights like (fan_in, fan_out) and hence this should be set to `True`.
53
+ init_weights (`bool`, defaults to `True`):
54
+ Initialize SHiRA weight to have zero values. If set to False, SHiRA weights are initialized to randn values
55
+ instead of zeros and this is used only for testing.
56
+ modules_to_save (`List[str]`):
57
+ List of modules apart from SHiRA layers to be set as trainable and saved in the final checkpoint.
58
+ """
59
+
60
+ r: int = field(
61
+ default=32,
62
+ metadata={
63
+ "help": (
64
+ "For a given target module, the number of SHiRA parameters is computed as r(m+n), where the original "
65
+ "tensor dimensions are m x n. This means the number of SHiRA parameters is the same as that for a LoRA adapter. "
66
+ "SHiRA is a high rank adapter. Setting this r parameter does not restrict the rank to this value."
67
+ )
68
+ },
69
+ )
70
+ mask_type: Literal["random"] = field(
71
+ default="random",
72
+ metadata={
73
+ "help": (
74
+ "Type of mask function. Defaults to a random sparse mask. "
75
+ "An optional user-defined mask_fn to compute the mask value can also be supplied by instantiating `config = ShiraConfig(...)` and then setting "
76
+ "`config.mask_fn = <your custom mask function>`. For a pretrained weight with shape m x n, the custom mask function must return only one mask (shape: m x n) "
77
+ "which must be binary 0 or 1 with num_shira_parameters = r(m + n) for linear layers. Device and dtype of mask must be same as base layer's weight's device and dtype. "
78
+ "Please see mask_functions.py for more details and to see the default random sparse mask implementation."
79
+ )
80
+ },
81
+ )
82
+ random_seed: Optional[int] = field(
83
+ default=None, metadata={"help": "random seed for the torch generator for random_mask"}
84
+ )
85
+ target_modules: Optional[Union[list[str], str]] = field(
86
+ default=None,
87
+ metadata={
88
+ "help": (
89
+ "List of module names or regex expression of the module names to replace with SHiRA."
90
+ "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'. "
91
+ "Only linear layers are supported."
92
+ )
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
+ init_weights: bool = field(
100
+ default=True,
101
+ metadata={
102
+ "help": "Initialize SHiRA weight to have zero values. If set to False, SHiRA weights are initialized to randn values instead of zeros and this is used only for testing."
103
+ },
104
+ )
105
+ modules_to_save: Optional[list[str]] = field(
106
+ default=None,
107
+ metadata={
108
+ "help": (
109
+ "List of modules apart from SHiRA layers to be set as trainable and saved in the final checkpoint. For"
110
+ " example, in Sequence Classification or Token Classification tasks, the final layer"
111
+ " `classifier/score` are randomly initialized and as such need to be trainable and saved."
112
+ )
113
+ },
114
+ )
115
+
116
+ def __post_init__(self):
117
+ super().__post_init__()
118
+ self.peft_type = PeftType.SHIRA
119
+ self.target_modules = (
120
+ set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules
121
+ )
122
+ if self.mask_type == "random":
123
+ self.mask_fn = random_mask
124
+ else:
125
+ if not self.inference_mode:
126
+ warnings.warn(
127
+ f"Argument {self.mask_type=} is not recognized, please supply your own masking function by calling `config.mask_fn = my_mask_fn`."
128
+ )
129
+ self.mask_fn = None
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/shira/layer.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 copy
16
+ import warnings
17
+ from typing import Optional
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
+
26
+ class ShiraLayer(BaseTunerLayer):
27
+ # List all names of layers that may contain trainable adapter weights
28
+ adapter_layer_names = ("shira_weight",)
29
+ # All names of other adapter-related parameters
30
+ other_param_names = ("r", "scaling", "shira_indices")
31
+
32
+ def __init__(self, base_layer: nn.Module, **kwargs):
33
+ self.base_layer = base_layer
34
+ self.r = {}
35
+ self.scaling = {}
36
+ self.shira_weight = nn.ParameterDict({})
37
+ self.shira_indices = {}
38
+ self.weight_shape = base_layer.weight.shape # Assumes SHiRA is on some layer with "weight" parameter
39
+
40
+ # Mark the weight as unmerged
41
+ self._disable_adapters = False
42
+ self.merged_adapters = []
43
+
44
+ base_layer = self.get_base_layer()
45
+ if isinstance(base_layer, nn.Linear):
46
+ in_features, out_features = base_layer.in_features, base_layer.out_features
47
+ else:
48
+ raise NotImplementedError("Only nn.Linear layers supported currently")
49
+
50
+ self.in_features = in_features
51
+ self.out_features = out_features
52
+ self.kwargs = kwargs
53
+
54
+ def update_layer(
55
+ self,
56
+ adapter_name,
57
+ mask,
58
+ r,
59
+ init_weights: bool = True,
60
+ inference_mode: bool = False,
61
+ **kwargs,
62
+ ):
63
+ if r <= 0:
64
+ raise ValueError(f"`r` should be a positive integer value but the value passed is {r}")
65
+ self.r[adapter_name] = r
66
+ self.scaling[adapter_name] = (
67
+ 1.0 # Default scale during training. Can be set to any (non-negative) value during inference.
68
+ )
69
+ # The number of shira weights in this layer is determined by r such that the total number of weights is the same as a LoRA Layer (for direct comparisons)
70
+ num_shira_weight = r * (self.in_features + self.out_features)
71
+ if num_shira_weight > self.in_features * self.out_features:
72
+ raise ValueError(
73
+ f"The set rank {r} results in more shira params than the total number of params in the base layer {self.in_features * self.out_features} and this is not allowed."
74
+ )
75
+
76
+ # Actual trainable parameters
77
+ # We have used a vector parameter with fixed indices that we use inside a torch.sparse_coo_tensor in get_delta_weight function.
78
+ # Directly using a torch.sparse_coo_tensor as a parameter could have been possible but we ran into some issues similar to:
79
+ # https://github.com/pytorch/pytorch/issues/79542.
80
+ shira_init_weight = torch.zeros(num_shira_weight) if init_weights else torch.randn(num_shira_weight)
81
+ self.shira_weight[adapter_name] = nn.Parameter(
82
+ shira_init_weight.to(self.base_layer.weight.dtype).to(self.base_layer.weight.device),
83
+ requires_grad=True,
84
+ )
85
+
86
+ if mask is not None:
87
+ # Compute the shira_indices from the mask. Make sure the mask is formed using r*(self.in_features + self.out_features) and not some other K.
88
+ mask_indices = torch.where(mask == 1.0)
89
+ self.shira_indices[adapter_name] = torch.cat(
90
+ [mask_indices[0].unsqueeze(0), mask_indices[1].unsqueeze(0)], 0
91
+ ).to(torch.int)
92
+ self.shira_indices[adapter_name] = self.shira_indices[adapter_name].to(self.base_layer.weight.device)
93
+
94
+ if self.shira_indices[adapter_name].shape[1] != self.shira_weight[adapter_name].shape[0]:
95
+ raise ValueError(
96
+ f"The SHiRA indices and weights are not the same dimensions for adapter {adapter_name} in layer {self.base_layer}"
97
+ )
98
+
99
+ self._move_adapter_to_device_of_base_layer(adapter_name)
100
+ self.set_adapter(self.active_adapters, inference_mode=inference_mode)
101
+
102
+ def reset_shira_parameters(self, adapter_name):
103
+ nn.init.zeros_(self.shira_weight[adapter_name])
104
+
105
+ def set_scale(self, adapter, scale):
106
+ if adapter not in self.scaling:
107
+ # Ignore the case where the adapter is not in the layer
108
+ return
109
+ self.scaling[adapter] = scale
110
+
111
+
112
+ class Linear(nn.Module, ShiraLayer):
113
+ # SHiRA implemented in a dense layer
114
+ def __init__(
115
+ self,
116
+ base_layer,
117
+ mask,
118
+ adapter_name: str,
119
+ r: int = 0,
120
+ fan_in_fan_out: bool = False, # Set this to True if the layer to replace stored weight like (fan_in, fan_out)
121
+ init_weights: bool = True,
122
+ **kwargs,
123
+ ) -> None:
124
+ super().__init__()
125
+ ShiraLayer.__init__(self, base_layer, **kwargs)
126
+ self.fan_in_fan_out = fan_in_fan_out
127
+ if self.base_layer is not self.get_base_layer():
128
+ raise ValueError("SHiRA does not support nested base layers")
129
+
130
+ self._active_adapter = adapter_name
131
+ self.update_layer(adapter_name, mask, r, init_weights=init_weights)
132
+
133
+ def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None:
134
+ """
135
+ Merge the active adapter weights into the base weights
136
+
137
+ Args:
138
+ safe_merge (`bool`, *optional*):
139
+ If True, the merge operation will be performed in a copy of the original weights and check for NaNs
140
+ before merging the weights. This is useful if you want to check if the merge operation will produce
141
+ NaNs. Defaults to `False`.
142
+ adapter_names (`List[str]`, *optional*):
143
+ The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults
144
+ to `None`.
145
+ """
146
+
147
+ adapter_names = check_adapters_to_merge(self, adapter_names)
148
+ if not adapter_names:
149
+ # no adapter to merge
150
+ return
151
+
152
+ for active_adapter in adapter_names:
153
+ if active_adapter in self.shira_weight.keys():
154
+ base_layer = self.get_base_layer()
155
+ if safe_merge:
156
+ # Note that safe_merge will be slower than the normal merge
157
+ # because of the copy operation.
158
+ orig_weights = base_layer.weight.data.clone()
159
+
160
+ orig_weights += self.get_delta_weight(active_adapter)
161
+
162
+ if not torch.isfinite(orig_weights).all():
163
+ raise ValueError(
164
+ f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken"
165
+ )
166
+
167
+ base_layer.weight.data = orig_weights
168
+ else:
169
+ base_layer.weight.data += self.get_delta_weight(active_adapter)
170
+ self.merged_adapters.append(active_adapter)
171
+
172
+ def unmerge(self) -> None:
173
+ if not self.merged:
174
+ warnings.warn("Already unmerged. Nothing to do.")
175
+ return
176
+
177
+ while len(self.merged_adapters) > 0:
178
+ active_adapter = self.merged_adapters.pop()
179
+ if active_adapter in self.shira_weight.keys():
180
+ self.get_base_layer().weight.data -= self.get_delta_weight(active_adapter)
181
+
182
+ def get_delta_weight(self, adapter) -> torch.Tensor:
183
+ """
184
+ Compute the delta weight for the given adapter.
185
+
186
+ Args:
187
+ adapter (str):
188
+ The name of the adapter for which the delta weight should be computed.
189
+ """
190
+
191
+ # In multi-gpu environment, the indices are at the wrong gpu. This is needed to correct this.
192
+ self.shira_indices[adapter] = self.shira_indices[adapter].to(self.shira_weight[adapter].device)
193
+ return torch.sparse_coo_tensor(
194
+ self.shira_indices[adapter], self.shira_weight[adapter] * self.scaling[adapter], self.weight_shape
195
+ )
196
+
197
+ def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor:
198
+ if self.disable_adapters:
199
+ if self.merged:
200
+ self.unmerge()
201
+ result = self.base_layer(x, *args, **kwargs)
202
+ elif self.merged:
203
+ result = self.base_layer(x, *args, **kwargs)
204
+ else:
205
+ new_weight = copy.deepcopy(self.base_layer.weight.data)
206
+ for active_adapter in self.active_adapters:
207
+ if active_adapter not in self.shira_weight.keys():
208
+ continue
209
+ new_weight += self.get_delta_weight(active_adapter)
210
+
211
+ result = F.linear(x, new_weight, bias=self.base_layer.bias)
212
+
213
+ return result
214
+
215
+ def supports_lora_conversion(self, adapter_name: str = "default") -> bool:
216
+ # delta weight is sparse, which does not work with SVD
217
+ return False
218
+
219
+ def __repr__(self) -> str:
220
+ rep = super().__repr__()
221
+ return "shira." + rep
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/shira/mask_functions.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """
16
+ This module is intended to store mask functions for use inside SHiRA construction. The mask functions are required to
17
+ have a specific signature as shown below.
18
+
19
+ Required positional arguments:
20
+ base_layer - This is the linear layer where the shira adapter will be attached. r - This parameter is used to
21
+ determine the number of parameters in the
22
+ shira adapter in a way that is consistent with LoRA sizing. SHiRA is a high rank adapter. Setting this
23
+ parameter does not restrict the adapter rank.
24
+ Keyword arguments can be provided as needed by the particular mask function implementation.
25
+
26
+ Return:
27
+ mask - this is a torch.tensor of the same shape as base_layer.weight that contains 0s and 1s with the same
28
+ dtype and device as base_layer.weight
29
+
30
+ If you would like to attach SHiRA adapters to a model using PEFT methods (such as get_peft_model()), using more
31
+ arguments than the provided positional arguments, you can create the mask function reference like the following:
32
+
33
+ ```
34
+ def create_mask_function_reference(**my_kwargs):
35
+ def mask_fn(base_layer, r):
36
+ ... your implementation here that might use my_kwargs ...
37
+ return mask
38
+ return mask_fn
39
+ ```
40
+ Then, you can create your peft model with custom SHiRA mask as follows:
41
+ ```
42
+ model = ...
43
+ my_kwargs = ...
44
+ mask_fn = create_mask_function_reference(**my_kwargs)
45
+ peft_config = ShiraConfig(r=4, mask_type='my_custom_mask')
46
+ peft_config.mask_fn = mask_fn
47
+ peft_model = get_peft_model(model, peft_config)
48
+ ```
49
+
50
+ Complete training examples are provided in the examples/shira/ directory.
51
+ """
52
+
53
+ from typing import Optional
54
+
55
+ import torch
56
+ import torch.nn as nn
57
+
58
+
59
+ def random_mask(base_layer: nn.Module, r: int, random_seed: Optional[int] = None, **kwargs) -> torch.tensor:
60
+ shape = base_layer.weight.shape
61
+ num_shira_weights = r * (shape[0] + shape[1])
62
+ random_generator = torch.Generator()
63
+ if random_seed is not None:
64
+ random_generator.manual_seed(random_seed)
65
+ idx = (torch.randperm(base_layer.weight.numel(), generator=random_generator)[:num_shira_weights]).to(
66
+ base_layer.weight.device
67
+ )
68
+ val = torch.ones_like(idx.type(base_layer.weight.dtype))
69
+ mask = torch.zeros_like(base_layer.weight.view(1, -1))
70
+ mask = mask.scatter_(1, idx.unsqueeze(0), val.unsqueeze(0)).view(shape)
71
+
72
+ return mask
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/shira/model.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 __future__ import annotations
16
+
17
+ import warnings
18
+
19
+ import torch
20
+
21
+ from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer
22
+ from peft.utils import (
23
+ TRANSFORMERS_MODELS_TO_SHIRA_TARGET_MODULES_MAPPING,
24
+ )
25
+
26
+ from .layer import Linear, ShiraLayer
27
+
28
+
29
+ class ShiraModel(BaseTuner):
30
+ """
31
+ Creates a Sparse High Rank Adapter (SHiRA) Model from a pretrained model.
32
+
33
+ Args:
34
+ model ([`~transformers.PreTrainedModel`]): The model to be adapted.
35
+ config ([`ShiraConfig`]): The configuration of the SHiRA model.
36
+ adapter_name (`str`): The name of the adapter, defaults to `"default"`.
37
+
38
+ Returns:
39
+ `torch.nn.Module`: The SHiRA model.
40
+
41
+ Example:
42
+
43
+ ```py
44
+ >>> from transformers import AutoModelForCausalLM
45
+ >>> from peft import ShiraConfig, get_peft_model
46
+
47
+ >>> base_model = AutoModelForCausalLM.from_pretrained("facebook/opt-125m")
48
+ >>> config = ShiraConfig(r=32)
49
+ >>> model = get_peft_model(base_model, config)
50
+ ```
51
+
52
+ **Attributes**:
53
+ - **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted.
54
+ - **peft_config** ([`ShiraConfig`]): The configuration of the SHiRA model.
55
+ """
56
+
57
+ prefix: str = "shira_"
58
+ tuner_layer_cls = ShiraLayer
59
+ target_module_mapping = TRANSFORMERS_MODELS_TO_SHIRA_TARGET_MODULES_MAPPING
60
+
61
+ def _create_and_replace(
62
+ self,
63
+ shira_config,
64
+ adapter_name,
65
+ target,
66
+ target_name,
67
+ parent,
68
+ current_key,
69
+ **optional_kwargs,
70
+ ):
71
+ if current_key is None:
72
+ raise ValueError("Current Key shouldn't be `None`")
73
+
74
+ bias = hasattr(target, "bias") and target.bias is not None
75
+ kwargs = {}
76
+ kwargs["bias"] = bias
77
+ if shira_config.mask_type == "random":
78
+ kwargs["random_seed"] = shira_config.random_seed
79
+
80
+ for k, v in optional_kwargs.items():
81
+ kwargs[k] = v
82
+
83
+ if isinstance(target, Linear):
84
+ mask = (
85
+ shira_config.mask_fn(target.base_layer, shira_config.r, **kwargs)
86
+ if shira_config.mask_fn is not None
87
+ else None
88
+ )
89
+ target.update_layer(
90
+ adapter_name,
91
+ mask,
92
+ shira_config.r,
93
+ init_weights=shira_config.init_weights,
94
+ )
95
+ else:
96
+ new_module = self._create_new_module(shira_config, adapter_name, target, **kwargs)
97
+ if adapter_name not in self.active_adapter:
98
+ # adding an additional adapter: it is not automatically trainable
99
+ new_module.requires_grad_(False)
100
+ self._replace_module(parent, target_name, new_module, target)
101
+
102
+ @staticmethod
103
+ def _create_new_module(shira_config, adapter_name, target, **kwargs):
104
+ fan_in_fan_out = shira_config.fan_in_fan_out
105
+
106
+ _ = kwargs.pop("bias", False)
107
+
108
+ if isinstance(target, BaseTunerLayer):
109
+ target_base_layer = target.get_base_layer()
110
+ else:
111
+ target_base_layer = target
112
+
113
+ if isinstance(target_base_layer, torch.nn.Linear):
114
+ if fan_in_fan_out:
115
+ warnings.warn(
116
+ "fan_in_fan_out is set to True but the target module is `torch.nn.Linear`. "
117
+ "Setting fan_in_fan_out to False."
118
+ )
119
+ fan_in_fan_out = shira_config.fan_in_fan_out = False
120
+ else:
121
+ raise ValueError(
122
+ f"Target module {target} is not supported. Currently, only the following modules are supported: "
123
+ "`torch.nn.Linear`."
124
+ )
125
+
126
+ mask = (
127
+ shira_config.mask_fn(target_base_layer, shira_config.r, **kwargs)
128
+ if shira_config.mask_fn is not None
129
+ else None
130
+ )
131
+
132
+ new_module = Linear(
133
+ target,
134
+ mask,
135
+ adapter_name,
136
+ shira_config.r,
137
+ fan_in_fan_out,
138
+ init_weights=shira_config.init_weights,
139
+ **kwargs,
140
+ )
141
+
142
+ return new_module
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/trainable_tokens/__init__.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 peft.utils import register_peft_method
16
+
17
+ from .config import TrainableTokensConfig
18
+ from .layer import TrainableTokensLayer
19
+ from .model import TrainableTokensModel
20
+
21
+
22
+ __all__ = [
23
+ "TrainableTokensConfig",
24
+ "TrainableTokensLayer",
25
+ "TrainableTokensModel",
26
+ ]
27
+
28
+ register_peft_method(
29
+ name="trainable_tokens",
30
+ config_cls=TrainableTokensConfig,
31
+ model_cls=TrainableTokensModel,
32
+ is_mixed_compatible=False,
33
+ )
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/trainable_tokens/config.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 __future__ import annotations
16
+
17
+ from dataclasses import dataclass, field
18
+ from typing import Optional, Union
19
+
20
+ from peft.config import PeftConfig
21
+ from peft.utils import PeftType
22
+
23
+
24
+ @dataclass
25
+ class TrainableTokensConfig(PeftConfig):
26
+ """
27
+ Configuration for the `TrainableTokens` method.
28
+
29
+ Allows for training new tokens (and re-training existing ones) without training the full embedding matrix. By
30
+ marking a few select tokens (identified by their indices) trainable and leaving the rest untouched, this method can
31
+ be used to add new tokens or changing the embedding of existing tokens while saving on memory. Both storage as well
32
+ as working memory usage are reduced in contrast to training the embedding matrix fully.
33
+
34
+ Note that training with FSDP/DeepSpeed might not yet be fully supported.
35
+
36
+ Args:
37
+ token_indices (`list[int]`):
38
+ List of integers, signifying the indices of the tokens you want to be trainable. To find the index of a
39
+ token with a tokenizer, you can tokenize the string and look at the returned `input_ids`. The closer the
40
+ amount of indices is to the total amount of tokens, the less efficient this method gets.
41
+ target_modules (`Optional[Union[list[str], str]]`):
42
+ List of module names or regex expression of the module names to replace with our `TrainableTokensLayer`. If
43
+ not defined, it will attempt to get the model's input embedding layer if the model has a
44
+ `get_input_embeddings` method (transformer models usually do), if that fails the default is 'embed_tokens'.
45
+ Other example targets are `embedding`, `encoder.embeddings` or `decoder.embeddings`.
46
+ init_weights (`bool`):
47
+ By default the new token weights are initialized to be the same as the respective token embeddings. This
48
+ makes TrainableTokens a no-op when not trained. If set to `False` the weights will be random values. Do not
49
+ change this setting unless you know exactly what you're doing.
50
+ """
51
+
52
+ token_indices: list[int] = field(
53
+ default_factory=list,
54
+ metadata={
55
+ "help": (
56
+ "List of integers, signifying the indices of the tokens you want to be trainable. "
57
+ "To find the index of a token with a tokenizer, you can tokenize the string and "
58
+ "look at the returned `input_ids`. The closer the amount of indices is to the total amount of "
59
+ "tokens, the less efficient this method gets."
60
+ )
61
+ },
62
+ )
63
+ target_modules: Optional[Union[list[str], str]] = field(
64
+ default=None,
65
+ metadata={
66
+ "help": (
67
+ "List of module names or regex expression of the module names to replace with our "
68
+ "`TrainableTokensLayer`. If not defined, it will default to the model's input embedding layer if "
69
+ "the model has a `get_input_embeddings` method (transformer models usually do), if that fails the "
70
+ "default is 'embed_tokens'. Other example targets could be `embedding`, `encoder.embeddings` or "
71
+ "`decoder.embeddings`."
72
+ ),
73
+ },
74
+ )
75
+
76
+ init_weights: bool = field(
77
+ default=True,
78
+ metadata={
79
+ "help": (
80
+ "By default the new token weights are initialized to be the same as the respective token embeddings. "
81
+ "This makes TrainableTokens a no-op when not trained. If set to `False` the weights will be random "
82
+ "values. Do not change this setting unless you know exactly what you're doing. "
83
+ )
84
+ },
85
+ )
86
+
87
+ def __post_init__(self):
88
+ super().__post_init__()
89
+ self.peft_type = PeftType.TRAINABLE_TOKENS
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/trainable_tokens/layer.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 __future__ import annotations
16
+
17
+ import warnings
18
+ from typing import Optional
19
+
20
+ import torch
21
+ import torch.distributed as dist
22
+ import torch.nn as nn
23
+ import torch.nn.functional as F
24
+
25
+ from peft.tuners._buffer_dict import BufferDict
26
+ from peft.tuners.tuners_utils import BaseTunerLayer, _get_in_out_features, check_adapters_to_merge
27
+ from peft.utils.integrations import check_deepspeed_zero3_enabled, gather_params_ctx
28
+
29
+
30
+ class TrainableTokensLayer(nn.Module, BaseTunerLayer):
31
+ # All names of layers that may contain (trainable) adapter weights
32
+ adapter_layer_names = ("trainable_tokens_delta",)
33
+
34
+ # All names of other parameters that may contain adapter-related parameters
35
+ other_param_names = ("token_indices", "trainable_tokens_original")
36
+
37
+ def __init__(
38
+ self,
39
+ base_layer: nn.Module,
40
+ adapter_name: str,
41
+ token_indices: list[int],
42
+ tied_adapter: Optional[TrainableTokensLayer] = None,
43
+ **kwargs,
44
+ ) -> None:
45
+ super().__init__()
46
+
47
+ self.base_layer = base_layer
48
+ self._active_adapter = adapter_name
49
+ self.kwargs = kwargs
50
+
51
+ # wrap the tied adapter in a list so that it is excluded from .(named_)modules() and, therefore,
52
+ # not included in the state dict since it would be a copy of the tied adapter anyway.
53
+ self._tied_adapter = [tied_adapter] if tied_adapter else []
54
+
55
+ # we store the updated weights of particular tokens and their originals. we assume
56
+ # that the count of new tokens is far smaller than the number of total tokens.
57
+ #
58
+ # In case we have weight tying with another token adapter, we'll have no actual
59
+ # references on our own but use everything from the tied adapter.
60
+ if not self.tied_adapter:
61
+ self.trainable_tokens_delta = nn.ParameterDict({})
62
+ self.trainable_tokens_original = BufferDict({})
63
+ self.token_indices = {}
64
+ else:
65
+ self.trainable_tokens_delta = self.tied_adapter.trainable_tokens_delta
66
+ self.trainable_tokens_original = self.tied_adapter.trainable_tokens_original
67
+ self.token_indices = self.tied_adapter.token_indices
68
+
69
+ # Mark the weight as unmerged
70
+ self.merged_adapters = []
71
+
72
+ in_features, out_features = _get_in_out_features(self.get_base_layer())
73
+ self.in_features = in_features
74
+ self.out_features = out_features
75
+
76
+ @property
77
+ def tied_adapter(self):
78
+ if self._tied_adapter:
79
+ return self._tied_adapter[0]
80
+ return None
81
+
82
+ def _collect_token_weights(self, weight: torch.Tensor, rows: torch.Tensor, embed_dim: int) -> torch.Tensor:
83
+ """DeepSpeed zero3 specific code to initialize trainable tokens.
84
+
85
+ Ensures that only the necessary weights are collected to a single rank, initialized, and then shared with all
86
+ ranks.
87
+ """
88
+ src_rank = 0
89
+ # right now, only CUDA is implemented
90
+ device = torch.device("cuda", torch.cuda.current_device())
91
+
92
+ with gather_params_ctx([weight], modifier_rank=None):
93
+ if dist.is_available() and dist.is_initialized() and dist.get_rank() == src_rank:
94
+ token_weights = weight[rows].clone()
95
+ else:
96
+ # build an empty tensor with correct shape/type/device
97
+ token_weights = torch.empty(
98
+ (len(rows), embed_dim),
99
+ dtype=weight.dtype,
100
+ device=device,
101
+ )
102
+
103
+ # share the weights with all ranks
104
+ dist.broadcast(token_weights, src=src_rank)
105
+ return token_weights
106
+
107
+ def update_layer(self, adapter_name, **kwargs):
108
+ if kwargs.get("tied_adapter", None):
109
+ # as a tied adapter, we're just following whatever the adpater we're tied to does, we don't update anything.
110
+ return
111
+
112
+ self.token_indices[adapter_name] = kwargs["token_indices"]
113
+ init_weights = kwargs.get("init_weights", True)
114
+
115
+ # we initialize the delta embedding weights from the base embedding matrix and replace values instead of
116
+ # adding/subtracting deltas. we do it this way and use `embedding.weight.index_copy()` to write the updated
117
+ # values during `forward()` to avoid that the user resizing the embedding matrix, effectively filling the new
118
+ # token space with random values, training the model with TrainableTokensLayer, initializing the model anew -
119
+ # thus re-initializing the new embeddings again with new random variables. If we would add/subtract deltas
120
+ # onto the new values, we would get undefined behavior. By replacing the specific token values we always
121
+ # get defined behavior.
122
+ weight = self.get_base_layer().weight
123
+
124
+ if hasattr(self.get_base_layer(), "embedding_dim"):
125
+ embed_dim = self.get_base_layer().embedding_dim
126
+ else:
127
+ # lm_head doesn't have embedding_dim attribute
128
+ embed_dim = self.get_base_layer().in_features
129
+
130
+ if init_weights:
131
+ if check_deepspeed_zero3_enabled():
132
+ values = self._collect_token_weights(weight, self.token_indices[adapter_name], embed_dim)
133
+ else:
134
+ values = self.weight[self.token_indices[adapter_name]]
135
+ else:
136
+ # random init with matching dtype/device
137
+ values = torch.randn(
138
+ (len(self.token_indices[adapter_name]), embed_dim),
139
+ dtype=weight.dtype,
140
+ device=weight.device,
141
+ )
142
+
143
+ self.trainable_tokens_delta[adapter_name] = nn.Parameter(values.clone(), requires_grad=True)
144
+ self.trainable_tokens_original[adapter_name] = values.clone()
145
+
146
+ self._move_adapter_to_device_of_base_layer(adapter_name)
147
+
148
+ def _check_overlapping_tokens(self, adapter_names):
149
+ """Raises an error if the token indices of the given adapter names are overlapping.
150
+ This is currently not supported and can lead to undefined behavior of the model if no specific merging between
151
+ the overlapping indices' values is applied.
152
+ """
153
+ if len(adapter_names) <= 1:
154
+ return
155
+
156
+ indices = set()
157
+
158
+ # we take already merged adapters into account as well since they can be overridden by new adapters as well.
159
+ for adapter_name in set(adapter_names + self.merged_adapters):
160
+ index_set = set(self.token_indices[adapter_name])
161
+ if len(indices.intersection(index_set)):
162
+ raise ValueError(
163
+ f"Token indices of adapter {adapter_name} are already defined and would result in "
164
+ "undefined merging behavior. Only disjunct token indices are currently supported."
165
+ )
166
+ indices.update(index_set)
167
+
168
+ def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None:
169
+ adapter_names = check_adapters_to_merge(self, adapter_names)
170
+
171
+ if not adapter_names:
172
+ # no adapter to merge
173
+ return
174
+
175
+ self._check_overlapping_tokens(adapter_names)
176
+
177
+ merged = self.base_layer.weight.data
178
+
179
+ for adapter_name in adapter_names:
180
+ index = torch.tensor(self.token_indices[adapter_name]).to(merged.device)
181
+ deltas = self.trainable_tokens_delta[adapter_name].to(merged)
182
+ merged = merged.index_copy(dim=0, index=index, source=deltas)
183
+
184
+ if safe_merge and not torch.isfinite(merged).all():
185
+ raise ValueError(f"NaNs detected in the merged weights. The adapter {adapter_name} seems to be broken")
186
+
187
+ self.base_layer.weight.data = merged
188
+ self.merged_adapters.extend(adapter_names)
189
+
190
+ def unmerge(self) -> None:
191
+ if not self.merged:
192
+ warnings.warn("Already unmerged. Nothing to do.")
193
+ return
194
+
195
+ while len(self.merged_adapters) > 0:
196
+ adapter_name = self.merged_adapters.pop()
197
+
198
+ index = torch.tensor(self.token_indices[adapter_name]).to(self.base_layer.weight.device)
199
+ originals = self.trainable_tokens_original[adapter_name].to(self.base_layer.weight)
200
+ self.base_layer.weight.data.index_copy_(dim=0, index=index, source=originals)
201
+
202
+ def get_merged_weights(self, active_adapters) -> torch.Tensor:
203
+ W = self.base_layer.weight
204
+
205
+ for adapter_name in active_adapters:
206
+ index = torch.tensor(self.token_indices[adapter_name]).to(W.device)
207
+ deltas = self.trainable_tokens_delta[adapter_name].to(W)
208
+ W = W.index_copy(dim=0, index=index, source=deltas)
209
+
210
+ # Note: the return type is a Tensor, not an nn.Parameter. This can lead to some errors, e.g. torch's
211
+ # model.get_parameter fails as it does a type check. But we cannot return an nn.Parameter here, as it can lead
212
+ # to other failures, as this is not a true nn.Parameter of the model.
213
+ return W
214
+
215
+ def forward_adapters(self, x: torch.Tensor, active_adapters, *args, **kwargs) -> torch.Tensor:
216
+ if self.disable_adapters or not active_adapters:
217
+ if self.merged:
218
+ self.unmerge()
219
+ result = self.base_layer(x, *args, **kwargs)
220
+ elif self.merged:
221
+ result = self.base_layer(x, *args, **kwargs)
222
+ else:
223
+ self._check_overlapping_tokens(active_adapters)
224
+
225
+ W = self.get_merged_weights(active_adapters)
226
+
227
+ # Normally it should be very clear that we're wrapping Embedding layers but there are cases, such as
228
+ # tying weights with an LM head where the layer we wrap is a Linear layer. Therefore we must choose
229
+ # accordingly.
230
+ #
231
+ # TODO: the isinstance checks, especially the one for nn.Linear, may not hold for quantized layers;
232
+ # TODO: we may need to find a better way to detect quantized layers.
233
+ if isinstance(self.base_layer, torch.nn.Embedding):
234
+ result = F.embedding(
235
+ input=x,
236
+ weight=W,
237
+ padding_idx=self.base_layer.padding_idx,
238
+ max_norm=self.base_layer.max_norm,
239
+ norm_type=self.base_layer.norm_type,
240
+ scale_grad_by_freq=self.base_layer.scale_grad_by_freq,
241
+ sparse=self.base_layer.sparse,
242
+ )
243
+ # Some embedding layers (e.g., Gemma3TextScaledWordEmbedding) apply scaling in their forward method.
244
+ # Since we're using F.embedding directly, we need to apply this scaling manually.
245
+ embed_scale = self._get_embed_scale()
246
+ if embed_scale is not None:
247
+ result = result * embed_scale.to(result.dtype)
248
+ elif isinstance(self.base_layer, torch.nn.Linear):
249
+ # Probably a tied adapter that wraps an LM head.
250
+ result = F.linear(
251
+ input=x,
252
+ weight=W,
253
+ )
254
+ else:
255
+ raise ValueError(
256
+ "TrainableTokensLayer wraps an unknown layer type, maybe you are targeting the wrong layer?"
257
+ )
258
+
259
+ return result
260
+
261
+ def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor:
262
+ return self.forward_adapters(x, self.active_adapters, *args, **kwargs)
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/trainable_tokens/model.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 __future__ import annotations
16
+
17
+ import torch.nn as nn
18
+
19
+ from peft.config import PeftConfig
20
+ from peft.tuners.tuners_utils import BaseTuner
21
+ from peft.utils import _get_input_embeddings_name, _get_submodules
22
+
23
+ from .layer import TrainableTokensLayer
24
+
25
+
26
+ class TrainableTokensModel(BaseTuner):
27
+ prefix: str = "trainable_tokens_"
28
+ tuner_layer_cls = TrainableTokensLayer
29
+
30
+ def _prepare_adapter_config(self, peft_config, model_config):
31
+ # target_modules can be none which prompts us to infer the embedding layer name ourselves.
32
+ if peft_config.target_modules is None:
33
+ peft_config.target_modules = _get_input_embeddings_name(self.model, "embed_tokens")
34
+
35
+ return peft_config
36
+
37
+ def inject_adapter(
38
+ self,
39
+ model: nn.Module,
40
+ adapter_name: str,
41
+ autocast_adapter_dtype: bool = True,
42
+ low_cpu_mem_usage: bool = False,
43
+ **kwargs,
44
+ ) -> None:
45
+ super().inject_adapter(
46
+ model=model,
47
+ adapter_name=adapter_name,
48
+ autocast_adapter_dtype=autocast_adapter_dtype,
49
+ low_cpu_mem_usage=low_cpu_mem_usage,
50
+ **kwargs,
51
+ )
52
+
53
+ model_config = self.get_model_config(self)
54
+
55
+ # In case of weight-tying we need to adapt the tied weights as well and use tie the embedding adapter.
56
+ #
57
+ # The TrainableTokensLayer supports being tied to another TrainableTokensLayer meaning that the layer will
58
+ # not do any changes on its own but solely rely on the weights from the tied adapter. We will search for the
59
+ # tied weights and put tied TrainableTokensLayer adapters on them, all tied to the adapter of the embedding
60
+ # matrix.
61
+ tied_weights_module_names = self._get_module_names_tied_with_embedding()
62
+
63
+ if (
64
+ tied_weights_module_names
65
+ and model_config.get("tie_word_embeddings", False)
66
+ and isinstance(self.model.get_input_embeddings(), TrainableTokensLayer)
67
+ ):
68
+ # disable removing of duplicates since we're essentially only dealing with duplicates (i.e. tied weights)
69
+ for name, module in self.model.named_modules(remove_duplicate=False):
70
+ matched_keys = [target_key for target_key in tied_weights_module_names if name.endswith(target_key)]
71
+ if matched_keys:
72
+ parent, target, target_name = _get_submodules(model, name)
73
+
74
+ # If the module is already a TrainableTokensLayer, we need to replace it with a tied version
75
+ # instead of just updating it. This handles the case where the user explicitly targeted
76
+ # both the embedding and tied layers in target_modules.
77
+ if isinstance(target, TrainableTokensLayer):
78
+ # Replace the existing layer with a new one that's tied to the embedding
79
+ peft_config = self.peft_config[adapter_name].to_dict()
80
+ peft_config["tied_adapter"] = self.model.get_input_embeddings()
81
+
82
+ new_module = self._create_new_module(
83
+ peft_config, adapter_name, target.base_layer, **peft_config
84
+ )
85
+ self._replace_module(parent, target_name, new_module, target.base_layer)
86
+ else:
87
+ # Module hasn't been wrapped yet, create and replace normally
88
+ peft_config = self.peft_config[adapter_name].to_dict()
89
+ peft_config["tied_adapter"] = self.model.get_input_embeddings()
90
+
91
+ self._create_and_replace_dict(
92
+ peft_config,
93
+ adapter_name,
94
+ target,
95
+ target_name,
96
+ parent,
97
+ matched_keys[0],
98
+ )
99
+
100
+ def _get_tied_target_modules(self, *args, **kwargs):
101
+ # Normally this method would return the layers that target tied layers.
102
+ #
103
+ # We override this method since we explicitly support tied weights tied to the embedding layer.
104
+ # Therefore, we don't need the warning issued by returning the modules here.
105
+ return []
106
+
107
+ def _create_and_replace_dict(
108
+ self,
109
+ peft_config: dict,
110
+ adapter_name: str,
111
+ target: nn.Module,
112
+ target_name: str,
113
+ parent: nn.Module,
114
+ current_key: str,
115
+ ) -> None:
116
+ """
117
+ The same as `_create_and_replace` but takes a dictionary instead of a peft config so that we can add keys that
118
+ are not present in the config, such as `tied_adapter`.
119
+ """
120
+ kwargs = peft_config
121
+
122
+ if isinstance(target, TrainableTokensLayer):
123
+ target.update_layer(adapter_name, **kwargs)
124
+ else:
125
+ new_module = self._create_new_module(peft_config, adapter_name, target, **kwargs)
126
+ self._replace_module(parent, target_name, new_module, target)
127
+
128
+ def _create_and_replace(
129
+ self,
130
+ peft_config: PeftConfig,
131
+ adapter_name: str,
132
+ target: nn.Module,
133
+ target_name: str,
134
+ parent: nn.Module,
135
+ current_key: str,
136
+ ) -> None:
137
+ """
138
+ A private method to create and replace the target module with the adapter module.
139
+ """
140
+ kwargs = peft_config.to_dict()
141
+ self._create_and_replace_dict(kwargs, adapter_name, target, target_name, parent, current_key)
142
+
143
+ @staticmethod
144
+ def _create_new_module(peft_config, adapter_name, target, **kwargs):
145
+ new_module = TrainableTokensLayer(target, adapter_name, **kwargs)
146
+ new_module.update_layer(
147
+ adapter_name,
148
+ init_weights=kwargs["init_weights"],
149
+ token_indices=kwargs["token_indices"],
150
+ tied_adapter=kwargs.get("tied_adapter", None),
151
+ )
152
+
153
+ return new_module
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/tuners_utils.py ADDED
@@ -0,0 +1,2071 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 copy
17
+ import dataclasses
18
+ import os
19
+ import re
20
+ import textwrap
21
+ import warnings
22
+ from abc import ABC, abstractmethod
23
+ from collections.abc import Sequence
24
+ from contextlib import contextmanager, nullcontext
25
+ from typing import Any, Optional, Union, overload
26
+
27
+ import torch
28
+ from accelerate.hooks import AlignDevicesHook
29
+ from accelerate.utils import named_module_tensors, offload_state_dict
30
+ from packaging import version
31
+ from torch import nn
32
+ from tqdm import tqdm
33
+ from transformers import PreTrainedModel
34
+ from transformers.pytorch_utils import Conv1D
35
+
36
+ from peft.mapping import PEFT_TYPE_TO_PREFIX_MAPPING
37
+ from peft.utils import INCLUDE_LINEAR_LAYERS_SHORTHAND
38
+ from peft.utils.constants import (
39
+ DUMMY_MODEL_CONFIG,
40
+ DUMMY_TARGET_MODULES,
41
+ EMBEDDING_LAYER_NAMES,
42
+ MIN_TARGET_MODULES_FOR_OPTIMIZATION,
43
+ SEQ_CLS_HEAD_NAMES,
44
+ )
45
+ from peft.utils.integrations import init_empty_weights
46
+ from peft.utils.other import (
47
+ AuxiliaryTrainingWrapper,
48
+ _get_module_names_tied_with_embedding,
49
+ _set_adapter,
50
+ _set_layer_requires_grad,
51
+ match_target_against_key,
52
+ set_additional_trainable_modules,
53
+ )
54
+ from peft.utils.peft_types import PeftType, TaskType
55
+ from peft.utils.warning import PeftWarning
56
+
57
+ from ..config import PeftConfig
58
+ from ..utils import _get_submodules
59
+ from ._buffer_dict import BufferDict
60
+
61
+
62
+ _torch_supports_dtensor = version.parse(torch.__version__) >= version.parse("2.5.0")
63
+ _torch_supports_distributed = _torch_supports_dtensor and torch.distributed.is_available()
64
+
65
+
66
+ @contextmanager
67
+ def onload_layer(layer):
68
+ r"""
69
+ A utility for modifying a module containing one or more tuners and a base layer, any of which are offloaded to the
70
+ CPU or disk. Moves a module's sub-modules to the execution device before some action is performed, after that the
71
+ base layer state dictionary is re-assigned (if that layer was offloaded to the disk) and finally the parameters are
72
+ offloaded.
73
+
74
+ If the module has no offloaded sub-modules, this function does nothing.
75
+
76
+ Args:
77
+ layer ('torch.nn.Module'):
78
+ layer with tuners to be merged
79
+ """
80
+
81
+ offloaded_modules = []
82
+ for name, module in layer.named_modules():
83
+ if name in ["", "base_layer"]:
84
+ continue
85
+ if hasattr(module, "_hf_hook") and isinstance(module._hf_hook, AlignDevicesHook) and module._hf_hook.offload:
86
+ module._hf_hook.pre_forward(module)
87
+ offloaded_modules.append(module)
88
+
89
+ base_layer_offload = False
90
+ if hasattr(layer, "base_layer") and (
91
+ hasattr(layer.base_layer, "_hf_hook")
92
+ and isinstance(layer.base_layer._hf_hook, AlignDevicesHook)
93
+ and layer.base_layer._hf_hook.offload
94
+ ):
95
+ # check if the base layer is disk-offloaded (must contain a 'dataset' and an offload index)
96
+ if torch.device("meta") in layer.base_layer._hf_hook.original_devices.values() and hasattr(
97
+ layer.base_layer._hf_hook.weights_map, "dataset"
98
+ ):
99
+ # find the disk-offload index (maps modules to safetensors) from the `dataset` (OffloadedWeightsLoader object)
100
+ index = layer.base_layer._hf_hook.weights_map.dataset.index
101
+ module_name = list(dict(layer.base_layer._hf_hook.weights_map.dataset).keys())[0] # any module will do
102
+ file_name = index[module_name]["safetensors_file"]
103
+ base_name_arr = []
104
+ # get effective dir name
105
+ for i in os.path.split(file_name):
106
+ if "--" in i:
107
+ base_name_arr.append(i)
108
+ break
109
+ base_name_arr.append(i)
110
+ base_name = os.path.join(*base_name_arr)
111
+ safetensors_filename = base_name + "-merged"
112
+ layer.base_layer._hf_hook.pre_forward(layer.base_layer)
113
+ base_layer_offload = True
114
+
115
+ yield
116
+
117
+ for module in offloaded_modules:
118
+ module._hf_hook.post_forward(module, torch.tensor([]))
119
+
120
+ if base_layer_offload:
121
+ # re-make weights map (must be on cpu to send params to the disk via memmap if disk offload)
122
+ layer.base_layer._hf_hook.weights_map = {
123
+ name: param.to("cpu") for name, param in named_module_tensors(layer.base_layer)
124
+ }
125
+ # offload weights map to disk if original device is the disk
126
+ if torch.device("meta") in layer.base_layer._hf_hook.original_devices.values() and hasattr(
127
+ layer.base_layer._hf_hook.weights_map, "dataset"
128
+ ):
129
+ # rewrite directory with merged weights
130
+ offload_state_dict(safetensors_filename, layer.base_layer._hf_hook.weights_map)
131
+ layer.base_layer._hf_hook.post_forward(layer.base_layer, torch.tensor([]))
132
+
133
+
134
+ def _check_lora_target_modules_mamba(peft_config: PeftConfig, model: nn.Module, target_name: str):
135
+ """
136
+ Prevent applying LoRA to incompatible modules in specific architectures (e.g., Mamba).
137
+ """
138
+
139
+ lora_like_types = {"LORA", "ADALORA", "XLORA", "RANDLORA"}
140
+ incompatible_modules = {"out_proj", "conv1d"}
141
+ mamba_model_types = {"falcon_h1", "mamba", "mamba2", "falcon_mamba"}
142
+
143
+ if (
144
+ peft_config.peft_type in lora_like_types
145
+ and hasattr(model, "config")
146
+ and getattr(model.config, "model_type", None) in mamba_model_types
147
+ ):
148
+ if target_name in incompatible_modules:
149
+ raise ValueError(
150
+ f"[PEFT:{peft_config.peft_type}] Module '{target_name}' is incompatible with Mamba-based models "
151
+ f"(model_type='{model.config.model_type}'). Incompatible modules: {incompatible_modules}. "
152
+ "Please remove it from `target_modules` to avoid compatibility issues."
153
+ )
154
+
155
+
156
+ def _get_in_out_features(module: nn.Module) -> tuple[int, int] | tuple[None, None]:
157
+ """
158
+ Get the in_features and out_features of the layer.
159
+
160
+ Returns in_features and out_features as a tuple. If they cannot be determined, return a tuple of None and None.
161
+ This function covers a broad range of layers, some of which the caller might not support. Therefore, just because
162
+ this function returns a valid result does not imply that the layer type is supported.
163
+ """
164
+ if isinstance(module, nn.Linear):
165
+ if _torch_supports_distributed and isinstance(module.weight, torch.distributed.tensor.DTensor):
166
+ # If Tensor Parallel is used, the weight is sharded, so we need to get the local shape
167
+ out_features, in_features = module.weight.to_local().shape
168
+ else:
169
+ in_features, out_features = module.in_features, module.out_features
170
+ elif isinstance(module, nn.Conv1d):
171
+ in_features, out_features = module.in_channels, module.out_channels
172
+ elif isinstance(module, nn.Conv2d):
173
+ in_features, out_features = module.in_channels, module.out_channels
174
+ elif isinstance(module, nn.Conv3d):
175
+ in_features, out_features = module.in_channels, module.out_channels
176
+ elif isinstance(module, nn.Embedding):
177
+ in_features, out_features = module.num_embeddings, module.embedding_dim
178
+ elif isinstance(module, Conv1D):
179
+ in_features, out_features = (
180
+ module.weight.ds_shape if hasattr(module.weight, "ds_shape") else module.weight.shape
181
+ )
182
+ elif isinstance(module, nn.MultiheadAttention):
183
+ if not module._qkv_same_embed_dim:
184
+ raise ValueError("Only same dim for query/key/value is supported as of now for MultiheadAttention.")
185
+ in_features, out_features = module.embed_dim, 3 * module.embed_dim
186
+ elif hasattr(module, "infeatures") and hasattr(module, "outfeatures"):
187
+ # QuantLinear
188
+ in_features, out_features = module.infeatures, module.outfeatures
189
+ elif hasattr(module, "input_size") and hasattr(module, "output_size"):
190
+ # Megatron ColumnParallelLinear,RowParallelLinear
191
+ in_features, out_features = module.input_size, module.output_size
192
+ elif hasattr(module, "codebooks") and module.__class__.__name__ == "QuantizedLinear":
193
+ # AQLM QuantLinear
194
+ in_features, out_features = module.in_features, module.out_features
195
+ elif hasattr(module, "bits") and module.__class__.__name__ == "AwqGEMMQuantLinear":
196
+ # Awq layers
197
+ in_features, out_features = module.in_features, module.out_features
198
+ elif module.__class__.__name__ == "EetqLinear":
199
+ # Eetq layers
200
+ in_features, out_features = module.in_features, module.out_features
201
+ elif hasattr(module, "W_q") and module.__class__.__name__ == "HQQLinear":
202
+ # HQQ layers
203
+ in_features, out_features = module.in_features, module.out_features
204
+ elif module.__class__.__name__ == "PatchedLinear":
205
+ # INC layers
206
+ in_features, out_features = module.in_features, module.out_features
207
+ else:
208
+ # possibly support user provided custom layer types using dynamic dispatch
209
+ if hasattr(module, "in_features") and hasattr(module, "out_features"):
210
+ in_features, out_features = module.in_features, module.out_features
211
+ else:
212
+ in_features, out_features = None, None
213
+ warnings.warn(f"Unsupported layer type '{type(module)}' encountered, proceed at your own risk.", UserWarning)
214
+ return in_features, out_features
215
+
216
+
217
+ class BaseTuner(nn.Module, ABC):
218
+ r"""
219
+ A base tuner model that provides the common methods and attributes for all tuners that are injectable into a
220
+ torch.nn.Module
221
+
222
+ For adding a new Tuner class, one needs to overwrite the following methods:
223
+
224
+ - **_prepare_adapter_config**:
225
+ A private method to eventually prepare the adapter config, for example in case the field `target_modules` is
226
+ missing.
227
+ - **_create_and_replace**:
228
+ A private method to create and replace the target module with the adapter module.
229
+ - **_check_target_module_exists**:
230
+ A private helper method to check if the passed module's key name matches any of the target modules in the
231
+ adapter_config.
232
+
233
+ The easiest is to check what is done in the `peft.tuners.lora.LoraModel` class.
234
+
235
+ Attributes:
236
+ model (`torch.nn.Module`):
237
+ The model to which the adapter tuner layers will be attached.
238
+ forward (`Callable`):
239
+ The forward method of the model.
240
+ peft_config (`Union[`PeftConfig`, dict[str, PeftConfig]]`):
241
+ The adapter configuration object, it should be a dictionary of `str` to `PeftConfig` objects. One can also
242
+ pass a PeftConfig object and a new adapter will be created with the default name `adapter` or create a new
243
+ dictionary with a key `adapter_name` and a value of that peft config.
244
+ config (`dict[str, Any]`):
245
+ The model configuration object, it should be a dictionary of `str` to `Any` objects.
246
+ targeted_module_names (`list[str]`):
247
+ The list of module names that were actually adapted. Can be useful to inspect if you want to quickly
248
+ double-check that the `config.target_modules` were specified correctly.
249
+ targeted_parameter_names (`list[str]`):
250
+ The list of parameter names that were actually adapted. Can be useful to inspect if you want to quickly
251
+ double-check that the `config.target_parameters` were specified correctly.
252
+ prefix (`str`)
253
+ The PEFT-method specific unique prefix. E.g. `"lora_"` for LoRA.
254
+ """
255
+
256
+ # Required attributes for child classes:
257
+
258
+ # The unique prefix for this PEFT method, e.g. 'lora_' for LoRA.
259
+ prefix: str
260
+ # The class of the tuner layer, e.g. `LoraLayer` for LoRA.
261
+ tuner_layer_cls: type[BaseTunerLayer]
262
+ # The default target modules for various transformers model architectures, like Llama. This is useful to allow users
263
+ # to skip specifying the `target_modules` in the config of the PEFT method. The default is often something like
264
+ # `{'llama': ['q_proj', 'v_proj'], ...}`.
265
+ target_module_mapping: dict[str, list[str]]
266
+
267
+ def __init__(
268
+ self,
269
+ model,
270
+ peft_config: Union[PeftConfig, dict[str, PeftConfig]],
271
+ adapter_name: str,
272
+ low_cpu_mem_usage: bool = False,
273
+ state_dict: Optional[dict[str, torch.Tensor]] = None,
274
+ ) -> None:
275
+ super().__init__()
276
+
277
+ self.model = model
278
+ self.targeted_module_names: list[str] = []
279
+ self.targeted_parameter_names: list[str] = []
280
+
281
+ # For advanced developers, if you want to attach multiple adapters to your
282
+ # model, just add a `peft_config` dict attribute to your model.
283
+ if not hasattr(self, "peft_config"):
284
+ self.peft_config = {adapter_name: peft_config} if isinstance(peft_config, PeftConfig) else peft_config
285
+ else:
286
+ warnings.warn(
287
+ "Already found a `peft_config` attribute in the model. This will lead to having multiple adapters"
288
+ " in the model. Make sure to know what you are doing!"
289
+ )
290
+ if isinstance(peft_config, PeftConfig):
291
+ self.peft_config[adapter_name] = peft_config
292
+ else:
293
+ # user is adding a dict of PeftConfigs
294
+ self.peft_config.update(peft_config)
295
+
296
+ self.active_adapter: str | list[str] = adapter_name
297
+ self._pre_injection_hook(self.model, self.peft_config[adapter_name], adapter_name)
298
+ if peft_config != PeftType.XLORA or peft_config[adapter_name] != PeftType.XLORA:
299
+ self.inject_adapter(self.model, adapter_name, low_cpu_mem_usage=low_cpu_mem_usage, state_dict=state_dict)
300
+
301
+ # Copy the peft_config in the injected model.
302
+ self.model.peft_config = self.peft_config
303
+
304
+ @property
305
+ def active_adapters(self) -> list[str]:
306
+ if isinstance(self.active_adapter, str):
307
+ return [self.active_adapter]
308
+ # is already a list of str
309
+ return self.active_adapter
310
+
311
+ def forward(self, *args: Any, **kwargs: Any):
312
+ return self.model.forward(*args, **kwargs)
313
+
314
+ def _pre_injection_hook(self, model: nn.Module, config: PeftConfig, adapter_name: str) -> None:
315
+ r"""
316
+ A hook to be called before the adapter is injected into the model. This method can be overridden by child
317
+ classes to perform any pre-injection operations.
318
+
319
+ Args:
320
+ model (`nn.Module`):
321
+ The model to be adapted.
322
+ config (`PeftConfig`):
323
+ The adapter config.
324
+ adapter_name (`str`):
325
+ The adapter name.
326
+ """
327
+ pass
328
+
329
+ def _prepare_adapter_config(self, peft_config: PeftConfig, model_config: dict) -> PeftConfig:
330
+ r"""
331
+ A private method to prepare the adapter config.
332
+
333
+ For transformers based models, if `peft_config.target_modules` is None, for some model architectures, we can
334
+ automatically infer the target modules from the `TRANSFORMERS_MODELS_TO_XXX_TARGET_MODULES_MAPPING`.
335
+
336
+ Args:
337
+ peft_config (`PeftConfig`):
338
+ The adapter config.
339
+ model_config (`dict`):
340
+ The transformers model config, that config should contain the `model_type` key.
341
+
342
+ Returns:
343
+ peft_config (`PeftConfig`):
344
+ The PEFT config with updated `target_modules`.
345
+
346
+ Raises:
347
+ ValueError:
348
+ Raises an error if the model type was not recognized.
349
+ """
350
+ if peft_config.target_modules is None:
351
+ target_modules = self.target_module_mapping.get(model_config["model_type"])
352
+ if target_modules is None:
353
+ raise ValueError("Please specify `target_modules` in `peft_config`")
354
+ peft_config.target_modules = set(target_modules)
355
+ return peft_config
356
+
357
+ def _prepare_model(self, peft_config: PeftConfig, model: nn.Module):
358
+ r"""
359
+ A private method to modify the model structure before adapter is applied.
360
+
361
+ See `peft.tuner.lora.LoraModel._prepare_model` for an example.
362
+
363
+ Args:
364
+ peft_config (`PeftConfig`):
365
+ The prepared adapter config.
366
+ model (`nn.Module`):
367
+ The model that is going to be adapted.
368
+ """
369
+ pass
370
+
371
+ @staticmethod
372
+ def _check_target_module_exists(peft_config: PeftConfig, key: str) -> bool | re.Match[str] | None:
373
+ """
374
+ A helper method to check if the passed module's key name matches any of the target modules in the
375
+ adapter_config.
376
+
377
+ Args:
378
+ config (`PeftConfig`):
379
+ A config to match target modules from.
380
+ key (`str`):
381
+ A key to search any matches in config.
382
+
383
+ Returns:
384
+ `bool` | `re.Match[str]` | `None`:
385
+ True or re.Match object if key matches any target modules from config, False or None if no match found.
386
+ """
387
+ return check_target_module_exists(peft_config, key)
388
+
389
+ @abstractmethod
390
+ def _create_and_replace(
391
+ self,
392
+ peft_config: PeftConfig,
393
+ adapter_name: str,
394
+ target: nn.Module,
395
+ target_name: str,
396
+ parent: nn.Module,
397
+ current_key: str,
398
+ parameter_name: Optional[str] = None,
399
+ ) -> None:
400
+ r"""
401
+ Inplace replacement of the target module with the adapter layer. This method needs to be overridden by all the
402
+ tuner classes.
403
+
404
+ Check `peft.tuners.lora.LoraModel._create_and_replace` for an example.
405
+
406
+ Args:
407
+ peft_config (`PeftConfig`):
408
+ The adapter config.
409
+ adapter_name (`str`):
410
+ The adapter name.
411
+ target (`nn.Module`):
412
+ The target module.
413
+ target_name (`str`):
414
+ The target module's name.
415
+ parent (`nn.Module`):
416
+ The parent module.
417
+ current_key (`str`):
418
+ The key of the current target being adapted.
419
+ parameter_name (`str`, *optional*)
420
+ If, and only if, an `nn.Parameter` is being targeted, this is the name of the parameter.
421
+ """
422
+ ...
423
+
424
+ def _mark_only_adapters_as_trainable(self, model: nn.Module) -> None:
425
+ """
426
+ A helper method to mark only the adapter layers as trainable (i.e. module.requires_grad = False).
427
+ """
428
+ for n, p in model.named_parameters():
429
+ if self.prefix not in n:
430
+ p.requires_grad = False
431
+
432
+ for active_adapter in self.active_adapters:
433
+ bias = getattr(self.peft_config[active_adapter], "bias", "none")
434
+ if bias == "none":
435
+ continue
436
+
437
+ if bias == "all":
438
+ for n, p in model.named_parameters():
439
+ if "bias" in n:
440
+ p.requires_grad = True
441
+ elif bias.endswith("_only"): # e.g. "lora_only" or "boft_only"
442
+ for m in model.modules():
443
+ if isinstance(m, self.tuner_layer_cls) and hasattr(m, "bias") and m.bias is not None:
444
+ m.bias.requires_grad = True
445
+ else:
446
+ raise NotImplementedError(f"Requested bias: {bias}, is not implemented.")
447
+
448
+ def _enable_adapter_layers(self, enabled: bool = True) -> None:
449
+ for module in self.model.modules():
450
+ if isinstance(module, (BaseTunerLayer, AuxiliaryTrainingWrapper)):
451
+ module.enable_adapters(enabled)
452
+
453
+ def disable_adapter_layers(self) -> None:
454
+ """
455
+ Disable all adapters in-place.
456
+
457
+ When disabling all adapters, the model output corresponds to the output of the base model.
458
+ """
459
+ # TODO: deprecate in favor of enable_adapters
460
+ for active_adapter in self.active_adapters:
461
+ bias_val = getattr(self.peft_config[active_adapter], "bias", "none")
462
+ if bias_val != "none":
463
+ msg = (
464
+ f"Careful, disabling adapter layers with bias configured to be '{bias_val}' does not produce the "
465
+ "same output as the base model would without adaption."
466
+ )
467
+ warnings.warn(msg)
468
+ self._enable_adapter_layers(enabled=False)
469
+
470
+ def enable_adapter_layers(self) -> None:
471
+ """
472
+ Enable all adapters in-place
473
+ """
474
+ # TODO: deprecate in favor of enable_adapters
475
+ self._enable_adapter_layers(enabled=True)
476
+
477
+ def delete_adapter(self, adapter_name: str) -> None:
478
+ """
479
+ Deletes an existing adapter.
480
+
481
+ Args:
482
+ adapter_name (str): Name of the adapter to be deleted.
483
+ """
484
+ if adapter_name not in list(self.peft_config.keys()):
485
+ raise ValueError(f"Adapter {adapter_name} does not exist")
486
+ del self.peft_config[adapter_name]
487
+
488
+ new_adapter = delete_adapter(
489
+ model=self.model, adapter_name=adapter_name, prefix=self.prefix, layer_cls=self.tuner_layer_cls
490
+ )
491
+ self.active_adapter = new_adapter or []
492
+
493
+ def set_requires_grad(self, adapter_names: str | Sequence[str], requires_grad: bool = True) -> None:
494
+ """
495
+ Enable or disable gradients on the given adapter(s).
496
+
497
+ Args:
498
+ adapter_name (`str` or `Sequence[str]`):
499
+ The name of the adapter(s) whose gradients should be enabled/disabled.
500
+ requires_grad (`bool`, *optional*)
501
+ Whether to enable (`True`, default) or disable (`False`).
502
+ """
503
+ set_requires_grad(self.model, adapter_names=adapter_names, requires_grad=requires_grad)
504
+
505
+ def _check_new_adapter_config(self, config: PeftConfig) -> None:
506
+ """
507
+ A helper method to check the config of a new adapter being added.
508
+
509
+ Raise a ValueError if there is something wrong with the config or if it conflicts with existing adapters.
510
+
511
+ """
512
+ if len(self.peft_config) <= 1:
513
+ return
514
+
515
+ # It is assumed that the config was added to self.peft_config *before* calling this check. We should thus never
516
+ # encounter the error below. Still, it is better to verify this, or else subsequent checks could be incorrect.
517
+ if not any(conf is config for conf in self.peft_config.values()):
518
+ raise ValueError(
519
+ "_check_new_peft_config was called incorrectly, this should not happen. Please open an issue and "
520
+ "report the error: https://github.com/huggingface/peft/issues"
521
+ )
522
+
523
+ bias_values = [getattr(conf, "bias", "none") for conf in self.peft_config.values()]
524
+ if sum(bias_value != "none" for bias_value in bias_values) > 1:
525
+ raise ValueError(
526
+ f"{self.__class__.__name__} supports only 1 adapter with bias. When using multiple adapters, "
527
+ "set bias to 'none' for all adapters."
528
+ )
529
+
530
+ def _cast_adapter_dtype(self, adapter_name: str, autocast_adapter_dtype: bool = True) -> None:
531
+ """
532
+ A helper method to cast the adapter weights to the correct dtype.
533
+
534
+ Currently, this only upcasts float16 and bfloat16 to float32.
535
+
536
+ Args:
537
+ adapter_name (`str`):
538
+ The adapter name.
539
+ autocast_adapter_dtype (`bool`, *optional*):
540
+ Whether to autocast the adapter dtype. Defaults to `True`.
541
+
542
+ """
543
+ cast_adapter_dtype(self.model, adapter_name=adapter_name, autocast_adapter_dtype=autocast_adapter_dtype)
544
+
545
+ def _check_merge_allowed(self):
546
+ """Helper method to check whether the adapter can be merged.
547
+
548
+ Raise a ValueError if it is not possible to merge the adapter with the given configuration.
549
+ """
550
+ example_code = textwrap.dedent(
551
+ """
552
+ ```python
553
+ from transformers import AutoModelForCausalLM
554
+
555
+ # Load original tied model
556
+ model = AutoModelForCausalLM.from_pretrained("google/gemma-2-2b-it", tie_word_embeddings=False)
557
+
558
+ # Set the randomly initialized lm_head to the previously tied embeddings
559
+ model.lm_head.weight.data = model.model.embed_tokens.weight.data.clone()
560
+
561
+ # Save the untied model
562
+ untied_model_dir = "dir/for/untied/model"
563
+ model.save_pretrained(untied_model_dir)
564
+ model.config.save_pretrained(untied_model_dir)
565
+
566
+ # Now use the original model but in untied format
567
+ model = AutoModelForCausalLM.from_pretrained(untied_model_dir)
568
+ ```
569
+ """
570
+ )
571
+ tied_target_modules = self._get_tied_target_modules(self.model)
572
+ if tied_target_modules:
573
+ warnings.warn(
574
+ f"Model with `tie_word_embeddings=True` and the {tied_target_modules=} are part of the adapter. "
575
+ "This can lead to complications. "
576
+ "You can opt to merge the adapter after cloning the weights (to untie the embeddings). "
577
+ "You can untie the embeddings by loading the model with `tie_word_embeddings=False`. For example:"
578
+ + example_code
579
+ )
580
+
581
+ def _unload_and_optionally_merge(
582
+ self,
583
+ merge: bool = True,
584
+ progressbar: bool = False,
585
+ safe_merge: bool = False,
586
+ adapter_names: Optional[list[str]] = None,
587
+ ) -> None:
588
+ if merge:
589
+ self._check_merge_allowed()
590
+
591
+ key_list = [key for key, _ in self.model.named_modules() if self.prefix not in key]
592
+ desc = "Unloading " + ("and merging " if merge else "") + "model"
593
+ for key in tqdm(key_list, disable=not progressbar, desc=desc):
594
+ try:
595
+ parent, target, target_name = _get_submodules(self.model, key)
596
+ except AttributeError:
597
+ continue
598
+ with onload_layer(target):
599
+ if hasattr(target, "unload_and_optionally_merge_module"):
600
+ # if layers have special unloading method, like MultiheadAttention, use that
601
+ unloaded_module = target.unload_and_optionally_merge_module(
602
+ merge=merge, safe_merge=safe_merge, adapter_names=adapter_names
603
+ )
604
+ self._replace_module(parent, target_name, unloaded_module, target)
605
+ elif hasattr(target, "base_layer"):
606
+ if merge:
607
+ target.merge(safe_merge=safe_merge, adapter_names=adapter_names)
608
+ self._replace_module(parent, target_name, target.get_base_layer(), target)
609
+
610
+ return self.model
611
+
612
+ def merge_and_unload(
613
+ self, progressbar: bool = False, safe_merge: bool = False, adapter_names: Optional[list[str]] = None
614
+ ) -> torch.nn.Module:
615
+ r"""
616
+ This method merges the adapter layers into the base model.
617
+
618
+ This is needed if someone wants to use the base model as a standalone model. The returned model has the same
619
+ architecture as the original base model.
620
+
621
+ It is important to assign the returned model to a variable and use it, this is not an in-place operation!
622
+
623
+ Args:
624
+ progressbar (`bool`):
625
+ whether to show a progressbar indicating the unload and merge process (default: False).
626
+ safe_merge (`bool`):
627
+ whether to activate the safe merging check to check if there is any potential Nan in the adapter
628
+ weights.
629
+ adapter_names (`List[str]`, *optional*):
630
+ The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults
631
+ to `None`.
632
+
633
+ Example:
634
+
635
+ ```py
636
+ >>> from transformers import AutoModelForCausalLM
637
+ >>> from peft import PeftModel
638
+
639
+ >>> model_id = ...
640
+ >>> base_model = AutoModelForCausalLM.from_pretrained(model_id)
641
+ >>> peft_model_id = ...
642
+ >>> model = PeftModel.from_pretrained(base_model, peft_model_id)
643
+ >>> merged_model = model.merge_and_unload()
644
+ ```
645
+ """
646
+ return self._unload_and_optionally_merge(
647
+ progressbar=progressbar, safe_merge=safe_merge, adapter_names=adapter_names
648
+ )
649
+
650
+ def unload(self) -> torch.nn.Module:
651
+ """
652
+ Return the base model by removing all the PEFT modules.
653
+
654
+ It is important to assign the returned model to a variable and use it, this is not an in-place operation!
655
+ """
656
+ return self._unload_and_optionally_merge(merge=False)
657
+
658
+ def _check_target_module_compatiblity(self, peft_config: PeftConfig, model: nn.Module, target_name: str):
659
+ """
660
+ Prevent applying LoRA to incompatible modules in specific architectures (e.g., Mamba).
661
+ """
662
+ _check_lora_target_modules_mamba(peft_config, model, target_name)
663
+
664
+ def _create_and_replace_parameter(
665
+ self, peft_config, adapter_name, target, target_name, parent, current_key
666
+ ) -> None:
667
+ raise NotImplementedError(f"{self.__class__.__name__} does not support targeting nn.Parameter.")
668
+
669
+ def inject_adapter(
670
+ self,
671
+ model: nn.Module,
672
+ adapter_name: str,
673
+ autocast_adapter_dtype: bool = True,
674
+ low_cpu_mem_usage: bool = False,
675
+ state_dict: Optional[dict[str, torch.Tensor]] = None,
676
+ ) -> None:
677
+ r"""
678
+ Creates adapter layers and replaces the target modules with the adapter layers. This method is called under the
679
+ hood by `peft.mapping.get_peft_model` if a non-prompt tuning adapter class is passed.
680
+
681
+ The corresponding PEFT config is directly retrieved from the `peft_config` attribute of the BaseTuner class.
682
+
683
+ Args:
684
+ model (`nn.Module`):
685
+ The model to be tuned.
686
+ adapter_name (`str`):
687
+ The adapter name.
688
+ autocast_adapter_dtype (`bool`, *optional*):
689
+ Whether to autocast the adapter dtype. Defaults to `True`.
690
+ low_cpu_mem_usage (`bool`, `optional`, defaults to `False`):
691
+ Create empty adapter weights on meta device. Useful to speed up the loading process.
692
+ state_dict (`dict`, *optional*, defaults to `None`)
693
+ If a state_dict is passed here, the adapters will be injected based on the entries of the state_dict.
694
+ This can be useful when the exact `target_modules` of the PEFT method is unknown, for instance because
695
+ the checkpoint was created without meta data. Note that the values from the state_dict are not used,
696
+ only the keys are used to determine the correct layers that should be adapted.
697
+
698
+ """
699
+ ###################################
700
+ # PREPARATION OF MODEL AND CONFIG #
701
+ ###################################
702
+
703
+ peft_config = self.peft_config[adapter_name]
704
+ excluded_modules = []
705
+ unmatched_modules = []
706
+ targeted_modules_from_peft_config: list[str] = [] # only relevant if state_dict is passed
707
+ # Note: If possible, all checks should be performed *at the start of this method*.
708
+ # This way, we can raise early if something goes wrong, without leaving the model
709
+ # in a bad (half-initialized) state.
710
+ self._check_new_adapter_config(peft_config)
711
+
712
+ self._check_tied_modules(model, peft_config)
713
+
714
+ model_config = self.get_model_config(model)
715
+
716
+ peft_config = self._prepare_adapter_config(peft_config, model_config)
717
+
718
+ self._prepare_model(peft_config, model)
719
+
720
+ if getattr(peft_config, "target_parameters", []) and state_dict:
721
+ raise ValueError(
722
+ "Trying to inject a PEFT adapter from a state_dict but the PEFT config uses `target_parameters`. This "
723
+ "is not supported -- when using `target_parameters`, please inject the adapter without the state_dict."
724
+ )
725
+
726
+ named_modules = list(model.named_modules())
727
+ key_list = [key for key, _ in named_modules]
728
+
729
+ uses_dummy_target_modules = getattr(peft_config, "target_modules", None) == DUMMY_TARGET_MODULES
730
+ if uses_dummy_target_modules:
731
+ # dummy adapter, we allow not matching any module
732
+ named_modules = []
733
+ key_list = []
734
+
735
+ # update peft_config.target_modules if required
736
+ peft_config = _maybe_include_all_linear_layers(peft_config, model)
737
+
738
+ # This is an optimization to reduce the number of entries in the target_modules list. The reason is that in some
739
+ # circumstances, target_modules can contain hundreds of entries. Since each target module is checked against
740
+ # each module of the net (which can be thousands), this can become quite expensive when many adapters are being
741
+ # added. Often, the target_modules can be condensed in such a case, which speeds up the process.
742
+ # A context in which this can happen is when diffusers loads non-PEFT LoRAs. As there is no meta info on
743
+ # target_modules in that case, they are just inferred by listing all keys from the state_dict, which can be
744
+ # quite a lot. See: https://github.com/huggingface/diffusers/issues/9297
745
+ # As there is a small chance for undiscovered bugs, we apply this optimization only if the list of
746
+ # target_modules is sufficiently big.
747
+ # We also exclude IA³ from this optimization. This is because IA³ has both target_modules and
748
+ # feedforward_modules, which are coupled (the latter must be a subset). It would be possible to change the logic
749
+ # to keep both in sync, but it's not quite trivial and probably not worth the effort. See #2429.
750
+ if (
751
+ isinstance(peft_config.target_modules, (list, set))
752
+ and (len(peft_config.target_modules) >= MIN_TARGET_MODULES_FOR_OPTIMIZATION)
753
+ and (peft_config.peft_type != PeftType.IA3)
754
+ ):
755
+ suffixes = tuple("." + suffix for suffix in peft_config.target_modules)
756
+ names_no_target = [
757
+ name for name in key_list if (name not in peft_config.target_modules) and not name.endswith(suffixes)
758
+ ]
759
+ new_target_modules = _find_minimal_target_modules(peft_config.target_modules, names_no_target)
760
+ if len(new_target_modules) < len(peft_config.target_modules):
761
+ peft_config.target_modules = new_target_modules
762
+
763
+ ###############################
764
+ # MATCHING & CREATING MODULES #
765
+ ###############################
766
+
767
+ existing_adapter_prefixes = []
768
+ for key, module in named_modules:
769
+ if isinstance(module, BaseTunerLayer):
770
+ existing_adapter_prefixes.append(key + ".")
771
+
772
+ # TODO: check if this the most robust way
773
+ module_names: set[str] = set()
774
+ if state_dict is not None:
775
+ prefix = PEFT_TYPE_TO_PREFIX_MAPPING[peft_config.peft_type]
776
+ # Find the module name from the state_dict. Also defensively remove '_orig_mod.', which might be inserted if
777
+ # the model was torch.compiled beforehand
778
+ module_names = {k.rsplit("." + prefix, 1)[0].removeprefix("_orig_mod.") for k in state_dict}
779
+
780
+ for key, module in named_modules:
781
+ if not key:
782
+ continue
783
+
784
+ # It is possible that we're adding an additional adapter, so if we encounter a key that clearly belongs to a
785
+ # previous adapter we can skip here since we don't want to interfere with adapter internals.
786
+ for adapter_key in existing_adapter_prefixes:
787
+ if key.startswith(adapter_key):
788
+ excluded_modules.append(key)
789
+ break
790
+
791
+ if excluded_modules and excluded_modules[-1] == key:
792
+ continue
793
+
794
+ if state_dict is None:
795
+ # normal mechanism: match the modules using the peft_config
796
+ result = self._check_target_module_exists(peft_config, key)
797
+ if isinstance(result, _ExcludedModule):
798
+ excluded_modules.append(key)
799
+ elif not result:
800
+ unmatched_modules.append(key)
801
+ else:
802
+ self.targeted_module_names.append(key)
803
+ parent, target, target_name = _get_submodules(model, key)
804
+ self._check_target_module_compatiblity(peft_config, model, target_name)
805
+ ctx = init_empty_weights if low_cpu_mem_usage else nullcontext
806
+ with ctx():
807
+ self._create_and_replace(
808
+ peft_config, adapter_name, target, target_name, parent, current_key=key
809
+ )
810
+ else:
811
+ # defensively remove _orig_mod prefix in case the model is compiled
812
+ key = key.removeprefix("_orig_mod.")
813
+ # use the state_dict to match modules instead
814
+ if key not in module_names:
815
+ unmatched_modules.append(key)
816
+ else:
817
+ self.targeted_module_names.append(key)
818
+ parent, target, target_name = _get_submodules(model, key)
819
+ self._check_target_module_compatiblity(peft_config, model, target_name)
820
+ ctx = init_empty_weights if low_cpu_mem_usage else nullcontext
821
+ with ctx():
822
+ self._create_and_replace(
823
+ peft_config, adapter_name, target, target_name, parent, current_key=key
824
+ )
825
+
826
+ # still record what would have been matched via the config so that the two results can be compared
827
+ if self._check_target_module_exists(peft_config, key):
828
+ targeted_modules_from_peft_config.append(key)
829
+
830
+ if getattr(peft_config, "target_parameters", []):
831
+ # Note: We don't need to check for no state_dict being passed, since we already checked this earlier.
832
+ self._inject_parameters(
833
+ peft_config=peft_config, model=model, adapter_name=adapter_name, low_cpu_mem_usage=low_cpu_mem_usage
834
+ )
835
+
836
+ ####################
837
+ # CHECK FOR ERRORS #
838
+ ####################
839
+
840
+ if state_dict is not None:
841
+ # in case that the state_dict was used as source of truth and it resulted in different outcomes than what
842
+ # would have been matched with the PEFT config, warn the user about that.
843
+ targeted_set_from_peft_config = set(targeted_modules_from_peft_config)
844
+ targeted_set_from_state_dict = set(self.targeted_module_names)
845
+ diff_peft_config = targeted_set_from_peft_config - targeted_set_from_state_dict
846
+ diff_state_dict = targeted_set_from_state_dict - targeted_set_from_peft_config
847
+ warning_msg = ""
848
+ if diff_peft_config or diff_state_dict:
849
+ warning_msg = (
850
+ "While injecting the PEFT adapters, an inconsistency was discovered between the PEFT config and "
851
+ "the provided state_dict. This is not necessarily an issue and can be ignored if this was the "
852
+ "intent. "
853
+ )
854
+ if diff_peft_config:
855
+ warning_msg += (
856
+ f"The PEFT config contained these additional target modules: {sorted(diff_peft_config)}. "
857
+ )
858
+ if diff_state_dict:
859
+ warning_msg += f"The state_dict contained these additional target modules: {sorted(diff_state_dict)}. "
860
+ if warning_msg:
861
+ warnings.warn(warning_msg, RuntimeWarning)
862
+
863
+ if not self.targeted_module_names and not self.targeted_parameter_names and not uses_dummy_target_modules:
864
+ if excluded_modules and not unmatched_modules:
865
+ # All targeted modules were excluded
866
+ raise ValueError(
867
+ "All modules were excluded. This is likely unintended. "
868
+ "Check your `target_modules`, `exclude_modules` and `modules_to_save` configuration."
869
+ )
870
+ elif not excluded_modules and unmatched_modules and not peft_config.target_modules:
871
+ raise ValueError(
872
+ "No `target_modules` passed but also no `target_parameters` found. Please check the values for "
873
+ "these arguments."
874
+ )
875
+ elif not excluded_modules and unmatched_modules:
876
+ # None of the targeted modules matched
877
+ error_msg = (
878
+ f"Target modules {peft_config.target_modules} not found in the base model. "
879
+ f"Please check the target modules and try again."
880
+ )
881
+ if getattr(peft_config, "layers_to_transform", None) is not None:
882
+ error_msg += f" Note: You specified 'layers_to_transform': {peft_config.layers_to_transform}."
883
+ if getattr(peft_config, "layers_pattern", None) is not None:
884
+ error_msg += f" You also specified 'layers_pattern': {peft_config.layers_pattern}."
885
+ raise ValueError(error_msg)
886
+ else:
887
+ # Some modules did not match and some matched but were excluded
888
+ error_msg = (
889
+ "No modules were targeted for adaptation. "
890
+ "This might be caused by a combination of mismatched target modules and excluded modules. "
891
+ "Please check your `target_modules` and `exclude_modules` configuration. You may also have "
892
+ "only targeted modules that are marked to be saved (`modules_to_save`)."
893
+ )
894
+ if getattr(peft_config, "layers_to_transform", None) is not None:
895
+ error_msg += f" Note: You specified 'layers_to_transform': {peft_config.layers_to_transform}."
896
+ if getattr(peft_config, "layers_pattern", None) is not None:
897
+ error_msg += f" You also specified 'layers_pattern': {peft_config.layers_pattern}."
898
+ raise ValueError(error_msg)
899
+
900
+ elif hasattr(peft_config, "exclude_modules") and peft_config.exclude_modules and not excluded_modules:
901
+ # exclude_modules was passed but was not used
902
+ warnings.warn(
903
+ f"You have passed exclude_modules={peft_config.exclude_modules} but no modules were excluded. "
904
+ "Please check that exclude_modules was set correctly."
905
+ )
906
+
907
+ elif not uses_dummy_target_modules:
908
+ # If we landed here, it means that at least one module or parameter was adapted, so let's not raise an
909
+ # error. However, let's warn the user if it seems like
910
+ # - they wanted to match a module but there was no match
911
+ # - they wanted to match a parameter but there was no match
912
+ if peft_config.target_modules and not self.targeted_module_names:
913
+ warnings.warn(
914
+ f"target_modules={peft_config.target_modules} were set but no module was matched.", RuntimeWarning
915
+ )
916
+ elif getattr(peft_config, "target_parameters", []) and not self.targeted_parameter_names:
917
+ warnings.warn(
918
+ f"target_parameters={peft_config.target_parameters} were set but no parameter was matched.",
919
+ RuntimeWarning,
920
+ )
921
+
922
+ tied_target_modules = self._get_tied_target_modules(model=model)
923
+ if tied_target_modules:
924
+ warnings.warn(
925
+ f"Model with `tie_word_embeddings=True` and the {tied_target_modules=} are part of the adapter. "
926
+ "This can lead to complications, for example when merging the adapter "
927
+ "or converting your model to formats other than safetensors. "
928
+ "See for example https://github.com/huggingface/peft/issues/2018."
929
+ )
930
+
931
+ ################
932
+ # HOUSEKEEPING #
933
+ ################
934
+
935
+ # It's important to set the adapter here (again), because otherwise it can happen that if a 2nd adapter is
936
+ # added, and it targets different layer(s) than the first adapter (which is active), then those different
937
+ # layers will be activated, which we don't want.
938
+ self.set_adapter(self.active_adapters, inference_mode=peft_config.inference_mode)
939
+ self._mark_only_adapters_as_trainable(model)
940
+
941
+ if self.peft_config[adapter_name].inference_mode:
942
+ for n, p in model.named_parameters():
943
+ if adapter_name in n:
944
+ p.requires_grad = False
945
+
946
+ set_additional_trainable_modules(
947
+ model=model,
948
+ peft_config=peft_config,
949
+ model_config=BaseTuner.get_model_config(self),
950
+ adapter_name=adapter_name,
951
+ activate_adapter=adapter_name in self.active_adapters,
952
+ )
953
+
954
+ def _inject_parameters(
955
+ self, peft_config: PeftConfig, model: nn.Module, adapter_name: str, low_cpu_mem_usage: bool
956
+ ) -> None:
957
+ """Inject layers based on peft_config.target_modules"""
958
+
959
+ def strip_base_layer_from_name(module_name):
960
+ # It is possible that the layer is already a PEFT layer and needs updating with a new adapter. In this case,
961
+ # the name of parameter would be something like `model.layers.0.experts.base_layer.weight`, i.e. there is a
962
+ # "base_layer" inserted in the name. We need to remove that, otherwise we won't be able to match correctly
963
+ # (in this case, "experts.weight" would not match).
964
+ name = ".base_layer"
965
+ while name in module_name:
966
+ prefix, _, suffix = module_name.rpartition(name)
967
+ module_name = prefix + suffix
968
+ return module_name
969
+
970
+ def create_and_replace_param(module_name, key, param_name):
971
+ # helper function to avoid duplication
972
+ parent, target, target_name = _get_submodules(model, module_name)
973
+ unwrapped_module_name = strip_base_layer_from_name(module_name)
974
+ unwrapped_module = model.get_submodule(unwrapped_module_name)
975
+ # use the class name for checking to avoid circular import
976
+ if isinstance(unwrapped_module, BaseTunerLayer) and unwrapped_module.__class__.__name__ != "ParamWrapper":
977
+ raise ValueError(
978
+ f"Trying to wrap an `nn.Parameter` of layer '{unwrapped_module_name}' of type "
979
+ f"{type(target).__name__}, which is not a valid target. Make sure that this layer is not "
980
+ "also targeted with `target_modules`. For some models, PEFT will do this automatically, "
981
+ "try setting `target_modules=[]` to prevent it."
982
+ )
983
+
984
+ self._check_target_module_compatiblity(peft_config, model, target_name)
985
+ ctx = init_empty_weights if low_cpu_mem_usage else nullcontext
986
+ with ctx():
987
+ self._create_and_replace(
988
+ peft_config,
989
+ adapter_name,
990
+ target,
991
+ target_name,
992
+ parent,
993
+ current_key=key,
994
+ parameter_name=param_name.rpartition(".")[-1],
995
+ )
996
+
997
+ # TODO very simple matching, might not cover all use cases
998
+ unsorted_target_names = set(peft_config.target_parameters)
999
+ # As the order of matching can influence the nesting of multiple params on the same module, ensure determinism
1000
+ # by sorting.
1001
+ target_names = sorted(unsorted_target_names)
1002
+ for module_name, module in model.named_modules():
1003
+ if hasattr(module, "parametrizations"):
1004
+ # Deal with the case that the parameter is already parametrized. The issue is that we would not be able
1005
+ # to match `f"{module_name}.{param_name}"`, as the parameter is now something like
1006
+ # `module.parametrization.weight`.
1007
+ for key in target_names:
1008
+ target_module_name, _, param_name = key.rpartition(".")
1009
+ if target_module_name != module_name:
1010
+ continue
1011
+ if getattr(module, param_name, None) is None:
1012
+ continue
1013
+ create_and_replace_param(module_name, key, param_name)
1014
+ self.targeted_parameter_names.append(key)
1015
+ else:
1016
+ # Standard case: the parameter is not already parametrized. Note, however, that the model could already
1017
+ # be nested with lora.ParamWrapper, as this is how we allow targeting multiple Parameters on the same
1018
+ # module.
1019
+ unwrapped_module_name = strip_base_layer_from_name(module_name)
1020
+ # we're interested in finding the "lowest" module that contains the parameter, hence recurse=False
1021
+ for param_name, param in module.named_parameters(recurse=False):
1022
+ key = f"{unwrapped_module_name}.{param_name}"
1023
+ if (key in target_names) or any(key.endswith(f".{target_key}") for target_key in target_names):
1024
+ # Note: We use the unwrapped_module_name to check if the key matches, but we use the module_name for
1025
+ # replacement, since we want to replace the wrapped module.
1026
+ create_and_replace_param(module_name, key, param_name)
1027
+ self.targeted_parameter_names.append(key)
1028
+
1029
+ def _replace_module(self, parent, child_name, new_module, child) -> None:
1030
+ """
1031
+ Replace the sub-module of a given moduel with a new PEFT module.
1032
+
1033
+ This also deals with device placement of the new module to be in line with the child module.
1034
+
1035
+ Args:
1036
+ parent (`nn.Module`):
1037
+ The parent module on which the replacement should take place.
1038
+ child_name (`str`):
1039
+ The name of the child module to be replaced.
1040
+ new_module (`nn.Module`):
1041
+ The new PEFT module.
1042
+ child (`nn.Module`):
1043
+ The original child module that is being replaced.
1044
+
1045
+ """
1046
+ setattr(parent, child_name, new_module)
1047
+ # It's not necessary to set requires_grad here, as that is handled by
1048
+ # _mark_only_adapters_as_trainable
1049
+
1050
+ # child layer wraps the original module, unpack it
1051
+ if hasattr(child, "base_layer"):
1052
+ child = child.base_layer
1053
+
1054
+ if not hasattr(new_module, "base_layer"):
1055
+ new_module.weight = child.weight
1056
+ if hasattr(child, "bias"):
1057
+ new_module.bias = child.bias
1058
+
1059
+ if getattr(child, "state", None) is not None:
1060
+ if hasattr(new_module, "base_layer"):
1061
+ new_module.base_layer.state = child.state
1062
+ else:
1063
+ new_module.state = child.state
1064
+ new_module.to(child.weight.device)
1065
+
1066
+ meta = torch.device("meta")
1067
+ # dispatch to correct device
1068
+ for name, module in new_module.named_modules():
1069
+ if self.prefix in name:
1070
+ if hasattr(child, "qweight"):
1071
+ weight = child.qweight
1072
+ elif hasattr(child, "W_q"):
1073
+ weight = child.W_q
1074
+ elif hasattr(child, "weight"):
1075
+ weight = child.weight
1076
+ elif getattr(child, "in_proj_weight", None) is not None: # MHA
1077
+ weight = child.in_proj_weight
1078
+ else:
1079
+ weight = next(child.parameters())
1080
+
1081
+ if not any(p.device == meta for p in module.parameters()):
1082
+ module.to(weight.device)
1083
+
1084
+ def merge_adapter(self, adapter_names: Optional[list[str]] = None, safe_merge: bool = False) -> None:
1085
+ """
1086
+ This method merges the adapter layers into the base model.
1087
+
1088
+ Merging adapters can lead to a speed up of the forward pass. A copy of the adapter weights is still kept in
1089
+ memory, which is required to unmerge the adapters. In order to merge the adapter weights without keeping them
1090
+ in memory, please call `merge_and_unload`.
1091
+
1092
+ Args:
1093
+ adapter_names (`list[str]`, *optional*):
1094
+ The list of adapter names that should be merged. If `None`, all active adapters will be merged.
1095
+ Defaults to `None`.
1096
+ safe_merge (`bool`, *optional*):
1097
+ If `True`, the merge operation will be performed in a copy of the original weights and check for NaNs
1098
+ before merging the weights. This is useful if you want to check if the merge operation will produce
1099
+ NaNs. Defaults to `False`.
1100
+ """
1101
+ # Note: The order of arguments here is:
1102
+ # adapter_names, safe_merge
1103
+ # For layer.merge, the order is:
1104
+ # safe_merge, adapter_names
1105
+ # This is not so nice but this method here started with only adapter_names, thus putting safe_merge first would
1106
+ # be a backwards incompatible change.
1107
+ self._check_merge_allowed()
1108
+ for module in self.model.modules():
1109
+ if isinstance(module, BaseTunerLayer):
1110
+ with onload_layer(module):
1111
+ module.merge(adapter_names=adapter_names, safe_merge=safe_merge)
1112
+
1113
+ def unmerge_adapter(self):
1114
+ """
1115
+ This method unmerges all merged adapter layers from the base model.
1116
+ """
1117
+ for module in self.model.modules():
1118
+ if isinstance(module, BaseTunerLayer):
1119
+ with onload_layer(module):
1120
+ module.unmerge()
1121
+
1122
+ def set_adapter(self, adapter_name: str | list[str], inference_mode: bool = False) -> None:
1123
+ """Set the active adapter(s).
1124
+
1125
+ Args:
1126
+ adapter_name (str, list[str]):
1127
+ The name(s) of the adapter(s) to set as active
1128
+ inference_mode (bool, optional):
1129
+ Whether the activated adapter should be frozen (i.e. `requires_grad=False`). Default is False.
1130
+ """
1131
+ set_adapter(
1132
+ self.model, adapter_name=adapter_name, inference_mode=inference_mode, layer_cls=self.tuner_layer_cls
1133
+ )
1134
+ self.active_adapter = adapter_name
1135
+
1136
+ @staticmethod
1137
+ def get_model_config(model: nn.Module) -> dict:
1138
+ """
1139
+ This method gets the config from a model in dictionary form. If model has not attribute config, then this
1140
+ method returns a default config.
1141
+
1142
+ Args:
1143
+ model (`nn.Module`):
1144
+ Model to get the config from.
1145
+ default (`dict|None`, *optional*)::
1146
+ What to return if model does not have a config attribute.
1147
+ """
1148
+ model_config = getattr(model, "config", DUMMY_MODEL_CONFIG)
1149
+ if hasattr(model_config, "to_dict"):
1150
+ model_config = model_config.to_dict()
1151
+ elif dataclasses.is_dataclass(model_config):
1152
+ model_config = dataclasses.asdict(model_config)
1153
+ return model_config
1154
+
1155
+ def _get_tied_target_modules(self, model: nn.Module) -> list[str]:
1156
+ tied_target_modules = []
1157
+ model_config = self.get_model_config(model)
1158
+ if model_config.get("tie_word_embeddings"):
1159
+ for target_module in self.targeted_module_names:
1160
+ # This potentially yields false positives since we're just looking at the layer names. So if we use a
1161
+ # model that uses weight-tying of lm_head and embed_tokens, a third, unrelated, layer which is
1162
+ # unfortunately named so that it is in EMBEDDING_LAYER_NAMES will be falsely reported here as well.
1163
+ if target_module.split(".")[-1] in EMBEDDING_LAYER_NAMES:
1164
+ tied_target_modules.append(target_module)
1165
+ return tied_target_modules
1166
+
1167
+ def _get_module_names_tied_with_embedding(self) -> list[str]:
1168
+ return _get_module_names_tied_with_embedding(self)
1169
+
1170
+ def _add_modules_to_tie(self, peft_config, tied_weight_keys):
1171
+ """
1172
+ This method adds modules to tie to `peft_config` so that those modules can be tied downstream. By default this
1173
+ method raises a warning, and each tuner class extending `BaseTuner` can choose to implement this.
1174
+ """
1175
+ msg = (
1176
+ "Model has `tie_word_embeddings=True` and a tied layer is part of the adapter, "
1177
+ "but no implementation exists to tie the adapters. "
1178
+ "This can lead to complications, for example when merging the adapter "
1179
+ "or converting your model to formats other than safetensors. "
1180
+ "Check the discussion here: https://github.com/huggingface/peft/issues/2777"
1181
+ )
1182
+ warnings.warn(msg)
1183
+
1184
+ def _check_tied_modules(self, model: nn.Module, peft_config):
1185
+ """
1186
+ Checks if any of the tied layers are targetted via `modules_to_save`. Updates the `peft_config.modules_to_tie`
1187
+ with any layers that needs to be tied
1188
+ """
1189
+ modules_to_save = set(getattr(peft_config, "modules_to_save", []) or [])
1190
+ is_embedding_to_save = any(m in EMBEDDING_LAYER_NAMES for m in modules_to_save)
1191
+
1192
+ tied_weight_keys = self._get_module_names_tied_with_embedding()
1193
+
1194
+ if getattr(peft_config, "ensure_weight_tying", False):
1195
+ if is_embedding_to_save and tied_weight_keys:
1196
+ self._add_modules_to_tie(peft_config, tied_weight_keys)
1197
+
1198
+ elif not is_embedding_to_save and tied_weight_keys:
1199
+ warnings.warn(
1200
+ "You have requested `ensure_weight_tying`, but no tied modules are added in `modules_to_save`"
1201
+ )
1202
+
1203
+ elif not tied_weight_keys:
1204
+ warnings.warn("You have requested `ensure_weight_tying`, but no tied modules were found in the model")
1205
+
1206
+ elif is_embedding_to_save and tied_weight_keys:
1207
+ if hasattr(peft_config, "ensure_weight_tying"):
1208
+ msg = (
1209
+ "Model has `tie_word_embeddings=True` and a tied layer is part of the adapter, "
1210
+ "but `ensure_weight_tying` is not set to True. "
1211
+ "This can lead to complications, for example when merging the adapter "
1212
+ "or converting your model to formats other than safetensors. "
1213
+ "Check the discussion here: https://github.com/huggingface/peft/issues/2777"
1214
+ )
1215
+ warnings.warn(msg)
1216
+ else:
1217
+ msg = (
1218
+ "Model has `tie_word_embeddings=True` and a tied layer is part of the adapter, "
1219
+ "but no implementation exists to tie the adapters. "
1220
+ "This can lead to complications, for example when merging the adapter "
1221
+ "or converting your model to formats other than safetensors. "
1222
+ "Check the discussion here: https://github.com/huggingface/peft/issues/2777"
1223
+ )
1224
+ warnings.warn(msg)
1225
+
1226
+ def supports_lora_conversion(self, adapter_name: str = "default") -> bool:
1227
+ """
1228
+ Whether it is possible for the adapter of this model to be converted to LoRA.
1229
+
1230
+ Normally, this works if the PEFT method is additive, i.e. W' = W_base + delta_weight.
1231
+ """
1232
+ return all(
1233
+ module.supports_lora_conversion() for module in self.modules() if isinstance(module, BaseTunerLayer)
1234
+ )
1235
+
1236
+ def __getattr__(self, name: str):
1237
+ """Forward missing attributes to the wrapped module."""
1238
+ try:
1239
+ return super().__getattr__(name) # defer to nn.Module's logic
1240
+ except AttributeError:
1241
+ if name == "model": # see #1892: prevent infinite recursion if class is not initialized
1242
+ raise
1243
+ return getattr(self.model, name)
1244
+
1245
+
1246
+ class BaseTunerLayer(ABC):
1247
+ r"""
1248
+ A tuner layer mixin that provides the common methods and attributes for all tuners.
1249
+
1250
+ Args:
1251
+ is_pluggable (`bool`, *optional*):
1252
+ Whether the adapter layer can be plugged to any pytorch module
1253
+ active_adapters (Union[List[`str`], `str`], *optional*):
1254
+ The name of the active adapter.
1255
+ """
1256
+
1257
+ # All names of layers that may contain adapter (trainable) weights
1258
+ adapter_layer_names: tuple[str, ...] = ()
1259
+ # All names of other parameters that may contain adapter-related parameters
1260
+ other_param_names: tuple[str, ...] = ()
1261
+
1262
+ # indicates whether all adapters should be disabled
1263
+ _disable_adapters: bool = False
1264
+
1265
+ # the currently active adapter(s)
1266
+ _active_adapter: str | list[str] = "default"
1267
+
1268
+ # List all merged adapters
1269
+ merged_adapters: list[str] = []
1270
+
1271
+ def get_base_layer(self) -> nn.Module:
1272
+ """
1273
+ (Recursively) get the base_layer.
1274
+
1275
+ This is necessary for the case that the tuner layer wraps another tuner layer.
1276
+
1277
+ """
1278
+ base_layer = self
1279
+ while hasattr(base_layer, "base_layer"):
1280
+ base_layer = base_layer.base_layer
1281
+ return base_layer
1282
+
1283
+ def _get_embed_scale(self):
1284
+ """
1285
+ Extract embed_scale from base layer if present and valid.
1286
+
1287
+ Some embedding layers (e.g., Gemma3TextScaledWordEmbedding) apply scaling to embeddings in their forward
1288
+ method. This method checks for the presence of an `embed_scale` attribute. If it exists, it is assumed to be a
1289
+ scalar. Its shape is validated accordingly.
1290
+
1291
+ Returns:
1292
+ torch.Tensor or None: The embed_scale tensor if found and valid, None otherwise.
1293
+ """
1294
+ base_layer = self.get_base_layer()
1295
+ if not hasattr(base_layer, "embed_scale"):
1296
+ return None
1297
+
1298
+ embed_scale = base_layer.embed_scale
1299
+
1300
+ # Convert scalar values to tensors
1301
+ if isinstance(embed_scale, (int, float)):
1302
+ return torch.tensor(embed_scale, device=base_layer.weight.device, dtype=base_layer.weight.dtype)
1303
+
1304
+ # Validate tensor shape - must be scalar (0-d) or 1-element tensor for proper broadcasting
1305
+ if isinstance(embed_scale, torch.Tensor):
1306
+ if embed_scale.numel() == 1:
1307
+ return embed_scale
1308
+ else:
1309
+ # Log warning but don't fail - this maintains backward compatibility
1310
+ warnings.warn(
1311
+ f"Found embed_scale attribute with shape {embed_scale.shape}, expected scalar. "
1312
+ "Embedding scaling will not be applied. If this is unexpected, please open an issue at "
1313
+ "https://github.com/huggingface/peft/issues",
1314
+ PeftWarning,
1315
+ )
1316
+ return None
1317
+
1318
+ return None
1319
+
1320
+ @property
1321
+ def weight(self) -> torch.Tensor:
1322
+ # This is required for some transformers code, e.g. for T5, weight is accessed as:
1323
+ # self.wo.weight
1324
+ # where "wo" is the adapter layer.
1325
+ # https://github.com/huggingface/transformers/blob/78f6ed6c70b29c1560780e3869a7ad4c6b3d2710/src/transformers
1326
+ # /models/t5/modeling_t5.py#L292
1327
+ base_layer = self.get_base_layer()
1328
+ if hasattr(base_layer, "qweight"):
1329
+ # QuantLinear
1330
+ weight = base_layer.qweight
1331
+ else:
1332
+ # Other layers
1333
+ weight = base_layer.weight
1334
+ return weight
1335
+
1336
+ @property
1337
+ def bias(self) -> torch.Tensor:
1338
+ base_layer = self.get_base_layer()
1339
+ return base_layer.bias
1340
+
1341
+ def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None:
1342
+ raise NotImplementedError
1343
+
1344
+ def unmerge(self) -> None:
1345
+ raise NotImplementedError
1346
+
1347
+ @property
1348
+ def merged(self) -> bool:
1349
+ return bool(self.merged_adapters)
1350
+
1351
+ @property
1352
+ def disable_adapters(self) -> bool:
1353
+ # use a property to ensure that disable_adapters is not set directly, instead use the enable_adapters method
1354
+ return self._disable_adapters
1355
+
1356
+ @property
1357
+ def active_adapter(self) -> str | list[str]:
1358
+ # use a property to ensure that active_adapter is not set directly, instead use the set_adapter method
1359
+ return self._active_adapter
1360
+
1361
+ def _get_available_adapters(self) -> set[str]:
1362
+ """Return all adapter names that can be found on this module."""
1363
+ adapters = set()
1364
+ for layer_name in self.adapter_layer_names:
1365
+ module = getattr(self, layer_name)
1366
+ if not isinstance(module, (nn.ModuleDict, nn.ParameterDict)):
1367
+ continue
1368
+ adapters.update(set(module.keys()))
1369
+ return adapters
1370
+
1371
+ @property
1372
+ def active_adapters(self):
1373
+ if isinstance(self.active_adapter, str):
1374
+ return [self.active_adapter]
1375
+ # is already a list of str
1376
+ return self.active_adapter
1377
+
1378
+ def enable_adapters(self, enabled: bool) -> None:
1379
+ """Toggle the enabling and disabling of adapters
1380
+
1381
+ Takes care of setting the requires_grad flag for the adapter weights.
1382
+
1383
+ Args:
1384
+ enabled (bool): True to enable adapters, False to disable adapters
1385
+ """
1386
+ if enabled:
1387
+ self.set_adapter(self.active_adapters)
1388
+ self._disable_adapters = False
1389
+ else:
1390
+ # disable grads on all adapter layers
1391
+ for layer_name in self.adapter_layer_names:
1392
+ module_dict = getattr(self, layer_name)
1393
+ for layer in module_dict.values():
1394
+ _set_layer_requires_grad(layer, False)
1395
+ self._disable_adapters = True
1396
+
1397
+ def set_adapter(self, adapter_names: str | list[str], inference_mode: bool = False) -> None:
1398
+ """Set the active adapter(s).
1399
+
1400
+ Additionally, this function will set the specified adapter to trainable (i.e., requires_grad=True) unless
1401
+ inference_mode is True.
1402
+
1403
+ Args:
1404
+ adapter_name (`str` or `list[str]`):
1405
+ The name(s) of the adapter(s) to set as active.
1406
+ inference_mode (bool, optional):
1407
+ Whether the activated adapter should be frozen (i.e. `requires_grad=False`). Default is False.
1408
+ """
1409
+ if isinstance(adapter_names, str):
1410
+ adapter_names = [adapter_names]
1411
+
1412
+ # Deactivate grads on the inactive adapter and activate grads on the active adapter (if not in inference mode)
1413
+ for layer_name in self.adapter_layer_names:
1414
+ module_dict = getattr(self, layer_name)
1415
+ for key, layer in module_dict.items():
1416
+ should_require_grad = (key in adapter_names) and (not inference_mode)
1417
+ _set_layer_requires_grad(layer, should_require_grad)
1418
+
1419
+ self._active_adapter = adapter_names
1420
+
1421
+ def _all_available_adapter_names(self) -> list[str]:
1422
+ """Return a sorted list of all available adapter names"""
1423
+ adapter_names = set()
1424
+ for name in self.adapter_layer_names + self.other_param_names:
1425
+ # we check each possible attribute and if it's a dict or ModuleDict, we assume that the keys are the adapter
1426
+ # names
1427
+ attr = getattr(self, name)
1428
+ if hasattr(attr, "keys"):
1429
+ adapter_names.update(attr.keys())
1430
+ return sorted(adapter_names)
1431
+
1432
+ def delete_adapter(self, adapter_name: str) -> None:
1433
+ """
1434
+ Delete an adapter from the layer
1435
+
1436
+ This should be called on all adapter layers, or else we will get an inconsistent state.
1437
+
1438
+ This method will also set a new active adapter if the deleted adapter was an active adapter. It is important
1439
+ that the new adapter is chosen in a deterministic way, so that the same adapter is chosen on all layers.
1440
+
1441
+ Args:
1442
+ adapter_name (`str`): The name of the adapter to delete
1443
+
1444
+ """
1445
+ for attr in self.adapter_layer_names + self.other_param_names:
1446
+ if adapter_name in getattr(self, attr):
1447
+ del getattr(self, attr)[adapter_name]
1448
+
1449
+ if adapter_name in self.active_adapters:
1450
+ # choose a new active adapter
1451
+ active_adapters = self.active_adapters[:]
1452
+ active_adapters.remove(adapter_name)
1453
+ if active_adapters:
1454
+ self.set_adapter(active_adapters)
1455
+ else:
1456
+ # no active adapters left, set a new default adapter
1457
+ # here we get the list of all adapters existing adapter names and choose the first one
1458
+ remaining_adapters = self._all_available_adapter_names()
1459
+ if not remaining_adapters:
1460
+ self.set_adapter([])
1461
+ else:
1462
+ new_active_adapter = remaining_adapters[0]
1463
+ warnings.warn(
1464
+ f"Adapter {adapter_name} was active which is now deleted. Setting active adapter to "
1465
+ f"{new_active_adapter}."
1466
+ )
1467
+ self.set_adapter(remaining_adapters[0])
1468
+
1469
+ def set_requires_grad(self, adapter_names: str | Sequence[str], requires_grad: bool = True) -> None:
1470
+ """
1471
+ Enable or disable gradients on the given adapter(s).
1472
+
1473
+ Args:
1474
+ adapter_name (`str` or `Sequence[str]`):
1475
+ The name of the adapter(s) whose gradients should be enabled/disabled.
1476
+ requires_grad (`bool`, *optional*)
1477
+ Whether to enable (`True`, default) or disable (`False`).
1478
+ """
1479
+ if isinstance(adapter_names, str):
1480
+ adapter_names_set = {adapter_names}
1481
+ else:
1482
+ adapter_names_set = set(adapter_names)
1483
+
1484
+ for layer_name in self.adapter_layer_names:
1485
+ module_dict = getattr(self, layer_name)
1486
+ for key, layer in module_dict.items():
1487
+ if key in adapter_names_set:
1488
+ _set_layer_requires_grad(layer, requires_grad)
1489
+
1490
+ def _get_base_layer_device_and_dtype(self, base_layer):
1491
+ """
1492
+ Helper function to determine the device and dtype of the base layer. If not possible to determine, return None.
1493
+ """
1494
+ device, dtype = None, None
1495
+
1496
+ # check weight and qweight (for GPTQ)
1497
+ for weight_name in ("weight", "qweight"):
1498
+ weight = getattr(base_layer, weight_name, None)
1499
+ if weight is not None:
1500
+ device = weight.device
1501
+ dtype = weight.dtype
1502
+ break
1503
+
1504
+ if hasattr(base_layer, "compute_dtype"): # bnb Linear4bitLt
1505
+ dtype = base_layer.compute_dtype
1506
+
1507
+ return device, dtype
1508
+
1509
+ def _move_adapter_to_device_of_base_layer(self, adapter_name: str, device: Optional[torch.device] = None) -> None:
1510
+ """
1511
+ Move the adapter of the given name to the device, and possibly dtype, of the base layer.
1512
+ """
1513
+ base_layer = self.get_base_layer()
1514
+ if isinstance(base_layer, nn.MultiheadAttention):
1515
+ base_layer = base_layer.out_proj
1516
+ base_layer_device, base_layer_dtype = self._get_base_layer_device_and_dtype(base_layer)
1517
+
1518
+ target_device = device if device is not None else base_layer_device
1519
+ if target_device is None:
1520
+ # could not determine device
1521
+ return
1522
+
1523
+ target_dtype = None
1524
+ if base_layer_dtype is not None:
1525
+ # don't cast to int dtype
1526
+ if base_layer_dtype.is_floating_point or base_layer_dtype.is_complex:
1527
+ target_dtype = base_layer_dtype
1528
+
1529
+ meta = torch.device("meta")
1530
+
1531
+ # loop through all potential adapter layers and move them to the device of the base layer; be careful to only
1532
+ # move this specific adapter to the device, as the other adapters could be on different devices
1533
+ # see #1639
1534
+ for adapter_layer_name in self.adapter_layer_names + self.other_param_names:
1535
+ adapter_layer = getattr(self, adapter_layer_name, None)
1536
+ if not isinstance(adapter_layer, (nn.ModuleDict, nn.ParameterDict, BufferDict)):
1537
+ continue
1538
+ if adapter_name not in adapter_layer:
1539
+ continue
1540
+ if any(p.device == meta for p in adapter_layer.parameters()):
1541
+ continue
1542
+
1543
+ if target_dtype is not None:
1544
+ adapter_layer[adapter_name] = adapter_layer[adapter_name].to(target_device, dtype=target_dtype)
1545
+ else:
1546
+ adapter_layer[adapter_name] = adapter_layer[adapter_name].to(target_device)
1547
+
1548
+ @overload
1549
+ def _cast_input_dtype(self, x: None, dtype: torch.dtype) -> None: ...
1550
+
1551
+ @overload
1552
+ def _cast_input_dtype(self, x: torch.Tensor, dtype: torch.dtype) -> torch.Tensor: ...
1553
+
1554
+ def _cast_input_dtype(self, x, dtype: torch.dtype):
1555
+ """
1556
+ Whether to cast the dtype of the input of the forward method.
1557
+
1558
+ Usually, we want to enable this to align the input dtype with the dtype of the weight, but by setting
1559
+ layer.cast_input_dtype=False, this can be disabled if necessary.
1560
+
1561
+ Enabling or disabling can be managed via the peft.helpers.disable_lora_input_dtype_casting context manager.
1562
+ """
1563
+ if x is None: # useful e.g. if x is the bias, which can be None
1564
+ return None
1565
+
1566
+ cast_input_dtype_enabled = getattr(self, "cast_input_dtype_enabled", True)
1567
+ if (not cast_input_dtype_enabled) or (x.dtype == dtype):
1568
+ return x
1569
+ return x.to(dtype=dtype)
1570
+
1571
+ def supports_lora_conversion(self, adapter_name: str = "default") -> bool:
1572
+ """
1573
+ Whether it is possible for this layer type to be converted to LoRA.
1574
+
1575
+ Normally, this works if the PEFT method is additive, i.e. W' = W_base + delta_weight.
1576
+ """
1577
+ return False
1578
+
1579
+
1580
+ def _find_minimal_target_modules(
1581
+ target_modules: list[str] | set[str], other_module_names: list[str] | set[str]
1582
+ ) -> set[str]:
1583
+ """Find the minimal set of target modules that is sufficient to separate them from the other modules.
1584
+
1585
+ Sometimes, a very large list of target_modules could be passed, which can slow down loading of adapters (e.g. when
1586
+ loaded from diffusers). It may be possible to condense this list from hundreds of items to just a handful of
1587
+ suffixes that are sufficient to distinguish the target modules from the other modules.
1588
+
1589
+ Example:
1590
+ ```py
1591
+ >>> from peft.tuners.tuners_utils import _find_minimal_target_modules
1592
+
1593
+ >>> target_modules = [f"model.decoder.layers.{i}.self_attn.q_proj" for i in range(100)]
1594
+ >>> target_modules += [f"model.decoder.layers.{i}.self_attn.v_proj" for i in range(100)]
1595
+ >>> other_module_names = [f"model.encoder.layers.{i}.self_attn.k_proj" for i in range(100)]
1596
+ >>> _find_minimal_target_modules(target_modules, other_module_names)
1597
+ {"q_proj", "v_proj"}
1598
+ ```
1599
+
1600
+ Args:
1601
+ target_modules (`list[str]` | `set[str]`):
1602
+ The list of target modules.
1603
+ other_module_names (`list[str]` | `set[str]`):
1604
+ The list of other module names. They must not overlap with the target modules.
1605
+
1606
+ Returns:
1607
+ `set[str]`:
1608
+ The minimal set of target modules that is sufficient to separate them from the other modules.
1609
+
1610
+ Raises:
1611
+ ValueError:
1612
+ If `target_modules` is not a list or set of strings or if it contains an empty string. Also raises an error
1613
+ if `target_modules` and `other_module_names` contain common elements.
1614
+ """
1615
+ if isinstance(target_modules, str) or not target_modules:
1616
+ raise ValueError("target_modules should be a list or set of strings.")
1617
+
1618
+ target_modules = set(target_modules)
1619
+ if "" in target_modules:
1620
+ raise ValueError("target_modules should not contain an empty string.")
1621
+
1622
+ other_module_names = set(other_module_names)
1623
+ if not target_modules.isdisjoint(other_module_names):
1624
+ msg = (
1625
+ "target_modules and other_module_names contain common elements, this should not happen, please "
1626
+ "open a GitHub issue at https://github.com/huggingface/peft/issues with the code to reproduce this issue"
1627
+ )
1628
+ raise ValueError(msg)
1629
+
1630
+ # it is assumed that module name parts are separated by a "."
1631
+ def generate_suffixes(s):
1632
+ parts = s.split(".")
1633
+ return [".".join(parts[i:]) for i in range(len(parts))][::-1]
1634
+
1635
+ # Create a reverse lookup for other_module_names to quickly check suffix matches
1636
+ other_module_suffixes = {suffix for item in other_module_names for suffix in generate_suffixes(item)}
1637
+
1638
+ # Find all potential suffixes from target_modules
1639
+ target_modules_suffix_map = {item: generate_suffixes(item) for item in target_modules}
1640
+
1641
+ # Initialize a set for required suffixes
1642
+ required_suffixes = set()
1643
+
1644
+ # We sort the target_modules_suffix_map simply to get deterministic behavior, since sets have no order. In theory
1645
+ # the order should not matter but in case there is a bug, it's better for the bug to be deterministic.
1646
+ for item, suffixes in sorted(target_modules_suffix_map.items(), key=lambda tup: tup[1]):
1647
+ # Go through target_modules items, shortest suffixes first
1648
+ for suffix in suffixes:
1649
+ # If the suffix is already in required_suffixes or matches other_module_names, skip it
1650
+ if suffix in required_suffixes or suffix in other_module_suffixes:
1651
+ continue
1652
+ # Check if adding this suffix covers the item
1653
+ if not any(item.endswith("." + req_suffix) for req_suffix in required_suffixes):
1654
+ required_suffixes.add(suffix)
1655
+ break
1656
+
1657
+ if not required_suffixes:
1658
+ return set(target_modules)
1659
+ return required_suffixes
1660
+
1661
+
1662
+ class _ExcludedModule:
1663
+ """
1664
+ A private helper method used to represent excluded modules in the check_target_module_exists function.
1665
+ """
1666
+
1667
+ def __bool__(self):
1668
+ return False
1669
+
1670
+
1671
+ def check_target_module_exists(config, key: str) -> bool | re.Match[str] | None:
1672
+ """A helper method to check if the passed module's key name matches any of the target modules in the adapter_config.
1673
+
1674
+ Args:
1675
+ config (`PeftConfig`):
1676
+ A config to match target modules from.
1677
+ key (`str`):
1678
+ A key to search any matches in config
1679
+
1680
+ Returns:
1681
+ `bool` | `re.Match[str]` | `None`:
1682
+ True or re.Match object if key matches any target modules from config, False or None if no match found.
1683
+ """
1684
+ if hasattr(config, "exclude_modules") and config.exclude_modules:
1685
+ if isinstance(config.exclude_modules, str):
1686
+ if re.fullmatch(config.exclude_modules, key):
1687
+ return _ExcludedModule()
1688
+ elif key in config.exclude_modules:
1689
+ return _ExcludedModule()
1690
+ elif any(key.endswith(f".{exclude_key}") for exclude_key in config.exclude_modules):
1691
+ return _ExcludedModule()
1692
+
1693
+ # Adapters should never match on modules to save modules as it is a guarantee for conflicts of behavior
1694
+ # between `ModulesToSaveWrapper` internals and the potential adapter.
1695
+ modules_to_save = getattr(config, "modules_to_save", None)
1696
+ if modules_to_save:
1697
+ if any(re.match(rf"(^|.*\.){m}($|\..*)", key) for m in modules_to_save):
1698
+ return _ExcludedModule()
1699
+
1700
+ if (config.target_modules is None) and (config.target_parameters is not None):
1701
+ # this is allowed if config.target_parameters are specified
1702
+ return False
1703
+
1704
+ if isinstance(config.target_modules, str):
1705
+ target_module_found = match_target_against_key(config.target_modules, key)
1706
+ elif key in config.target_modules:
1707
+ # this module is specified directly in target_modules
1708
+ target_module_found = True
1709
+ else:
1710
+ target_module_found = any(key.endswith(f".{target_key}") for target_key in config.target_modules)
1711
+
1712
+ layer_indexes = getattr(config, "layers_to_transform", None)
1713
+ layers_pattern = getattr(config, "layers_pattern", None)
1714
+
1715
+ is_using_layer_indexes = layer_indexes is not None and (
1716
+ len(layer_indexes) != 0 if isinstance(layer_indexes, list) else True
1717
+ )
1718
+ if is_using_layer_indexes and target_module_found:
1719
+ layer_index = None
1720
+ # TODO: It's still unclear how empty layers_pattern (None, [], or "") should behave
1721
+ # For now, empty layers_pattern means any layer pattern is ok
1722
+ if layers_pattern is None or len(layers_pattern) == 0:
1723
+ layer_index = re.match(r".*\.[^.]*\.(\d+)\.", key)
1724
+ else:
1725
+ layers_pattern = [layers_pattern] if isinstance(layers_pattern, str) else layers_pattern
1726
+ for pattern in layers_pattern:
1727
+ layer_index = re.match(rf".*\.{pattern}\.(\d+)\.", key)
1728
+ if layer_index is not None:
1729
+ break
1730
+
1731
+ if layer_index is None:
1732
+ target_module_found = False
1733
+ else:
1734
+ layer_index = int(layer_index.group(1))
1735
+ if isinstance(layer_indexes, int):
1736
+ target_module_found = layer_index == layer_indexes
1737
+ else:
1738
+ target_module_found = layer_index in layer_indexes
1739
+
1740
+ return target_module_found
1741
+
1742
+
1743
+ def inspect_matched_modules(tuner: BaseTuner, adapter_name: str = "default") -> dict:
1744
+ """
1745
+ A helper function to inspect the set of matched and unmatched modules for a PEFT model and the given adapter.
1746
+ """
1747
+ config = tuner.peft_config[adapter_name]
1748
+ key_list = [key for key, _ in tuner.model.named_modules()]
1749
+ module_dict = {"matched": [], "unmatched": []}
1750
+ for key in key_list:
1751
+ if tuner._check_target_module_exists(config, key):
1752
+ module_dict["matched"].append(key)
1753
+ else:
1754
+ module_dict["unmatched"].append(key)
1755
+ return module_dict
1756
+
1757
+
1758
+ def _maybe_include_all_linear_layers(peft_config: PeftConfig, model: nn.Module) -> PeftConfig:
1759
+ """
1760
+ Helper function to update `target_modules` to all linear/Conv1D layers if provided as 'all-linear'. Adapted from
1761
+ the QLoRA repository: https://github.com/artidoro/qlora/blob/main/qlora.py
1762
+ """
1763
+ if not hasattr(peft_config, "target_modules"):
1764
+ return peft_config
1765
+
1766
+ # if `target_modules` is a string, convert to lower case and check if it matches "all-linear"
1767
+ if not (
1768
+ isinstance(peft_config.target_modules, str)
1769
+ and peft_config.target_modules.lower() == INCLUDE_LINEAR_LAYERS_SHORTHAND
1770
+ ):
1771
+ return peft_config
1772
+
1773
+ linear_classes = (torch.nn.Linear, Conv1D)
1774
+ linear_names = ("Linear",)
1775
+ linear_module_names = set()
1776
+ for name, module in model.named_modules():
1777
+ # match with all linear classes.
1778
+ if isinstance(module, linear_classes):
1779
+ linear_module_names.add(name)
1780
+ elif isinstance(module, BaseTunerLayer) and any(n in type(module).__name__ for n in linear_names):
1781
+ # If the model already has adapter layers applied, then the "linear" layer is actually an adapter layer,
1782
+ # e.g. lora.Linear, and not nn.Linear. To target this layer, we don't want to check the layer type, as there
1783
+ # are many possible layer types (one for each PEFT method) and the list would quickly get out of date. Thus
1784
+ # we rely on the name of the layer class, which by convention is something like "Linear", "Linear4bit",
1785
+ # "HqqLoraLinear", ... in PEFT. It's not pretty but should generally work.
1786
+ # See 2390
1787
+ linear_module_names.add(name)
1788
+
1789
+ # Try to remove linear layers that should not be targeted as best as possible. We have to rely on convention as
1790
+ # there are no hard rules to detect these modules.
1791
+ module_names_to_exclude = set()
1792
+ if isinstance(model, PreTrainedModel):
1793
+ output_emb = model.get_output_embeddings()
1794
+ if output_emb is not None:
1795
+ # ignore the last classification head for text generation models
1796
+ last_module_name = [name for name, module in model.named_modules() if module is output_emb][0]
1797
+ module_names_to_exclude.add(last_module_name)
1798
+ elif peft_config.task_type == TaskType.SEQ_CLS:
1799
+ # ignore classifier head for classification models (issue 2027)
1800
+ # there is no fix name for the classifier head, so check the common ones
1801
+ for name in SEQ_CLS_HEAD_NAMES:
1802
+ cls_head = getattr(model, name, None)
1803
+ if cls_head is not None:
1804
+ last_module_name = [name for name, module in model.named_modules() if module is cls_head][0]
1805
+ module_names_to_exclude.add(last_module_name)
1806
+ break
1807
+
1808
+ # we don't want nested LoRA layers, i.e. LoRA being applied to possibly existing lora_A, lora_B, etc.
1809
+ # see 2390
1810
+ for prefix, module in model.named_modules():
1811
+ if isinstance(module, BaseTunerLayer):
1812
+ for suffix, child in module.named_modules():
1813
+ if suffix:
1814
+ module_names_to_exclude.add(f"{prefix}.{suffix}")
1815
+
1816
+ linear_module_names -= module_names_to_exclude
1817
+ peft_config.target_modules = linear_module_names
1818
+ return peft_config
1819
+
1820
+
1821
+ def check_adapters_to_merge(module: BaseTunerLayer, adapter_names: Optional[list[str]] = None) -> list[str]:
1822
+ """
1823
+ Helper function to check which adapters should be merged.
1824
+
1825
+ Only return those adapters that are not already merged. Give a warning if some or all of the adapters are already
1826
+ merged.
1827
+
1828
+ """
1829
+ if adapter_names is None:
1830
+ adapter_names = module.active_adapters
1831
+ if isinstance(adapter_names, str):
1832
+ raise ValueError(f"adapter_names should be a list of strings, got {adapter_names!r}.")
1833
+
1834
+ if module.merged:
1835
+ merged_adapters = set(module.merged_adapters)
1836
+ adapter_names = [name for name in adapter_names if name not in merged_adapters]
1837
+
1838
+ if adapter_names:
1839
+ warnings.warn(
1840
+ f"Already following adapters were merged {','.join(module.merged_adapters)}. "
1841
+ f"You are now additionally merging {','.join(adapter_names)}."
1842
+ )
1843
+ else:
1844
+ warnings.warn("All adapters are already merged, nothing to do.")
1845
+
1846
+ return adapter_names
1847
+
1848
+
1849
+ def clone_module(module: nn.Module, share_weights=False):
1850
+ """Clone a module in a pytorch model.
1851
+
1852
+ Clones a module of a model, optionally sharing all the parameters between the original and the clone. Simplifies
1853
+ reusing a module when manipulating the architecture of a model.
1854
+ """
1855
+ clone = copy.deepcopy(module)
1856
+
1857
+ def _share_weights(src: nn.Module, dst: nn.Module):
1858
+ for name, param in src.named_parameters(recurse=False):
1859
+ dst.register_parameter(name, param)
1860
+
1861
+ if share_weights:
1862
+ for name, submodule in module.named_modules():
1863
+ _share_weights(submodule, clone.get_submodule(name))
1864
+
1865
+ return clone
1866
+
1867
+
1868
+ def replicate_layers(model: nn.Module, layer_map: list[tuple[int, int]]):
1869
+ """Replicate layers in a transfomer model with weight sharing.
1870
+
1871
+ This function looks for a module list attribute at model[(.model)*].layers and replicates the layers in the module
1872
+ list according to the layer map. For example the map `[[0, 4], [2, 5]]` will take the set of layers `[0, 1, 2, 3,
1873
+ 4]` and replace them with a module list containing `[0, 1, 2, 3, 2, 3, 4]`.
1874
+ """
1875
+ while hasattr(model, "model"):
1876
+ model = model.model
1877
+ # Some variants of the bert model nest the main model under the bert attribute.
1878
+ if hasattr(model, "bert"):
1879
+ model = model.bert
1880
+
1881
+ model_type = None
1882
+ layers: nn.ModuleList = None
1883
+ if hasattr(model, "layers"):
1884
+ model_type = "llama"
1885
+ layers = model.layers
1886
+ elif hasattr(model, "encoder") and hasattr(model.encoder, "layer"):
1887
+ model_type = "bert"
1888
+ layers = model.encoder.layer
1889
+ elif hasattr(model, "h"):
1890
+ model_type = "falcon"
1891
+ layers = model.h
1892
+ if not model_type or not isinstance(layers, nn.ModuleList):
1893
+ raise ValueError(
1894
+ "Could not locate the layers attribute in the model. "
1895
+ "Expected Llama, Bert or Falcon compatible architectures."
1896
+ )
1897
+
1898
+ new_layers = []
1899
+ for start, end in layer_map:
1900
+ for i in range(start, end):
1901
+ current_idx = len(new_layers)
1902
+ new_layers.append(clone_module(layers[i], share_weights=True))
1903
+ # This is a hack needed to work around the layer_idx introduced in HF transformers.
1904
+ for submodule in new_layers[-1].modules():
1905
+ if hasattr(submodule, "layer_idx"):
1906
+ submodule.layer_idx = current_idx
1907
+ layers = nn.ModuleList(new_layers)
1908
+ if model_type == "llama":
1909
+ model.layers = layers
1910
+ elif model_type == "bert":
1911
+ model.encoder.layer = layers
1912
+ elif model_type == "falcon":
1913
+ model.h = layers
1914
+ else:
1915
+ raise ValueError("Unexpected model type, need to handle post-processing of layers.")
1916
+ if hasattr(model.config, "num_hidden_layers"): # Common to Llama, Bert, Falcon.
1917
+ model.config.num_hidden_layers = len(new_layers)
1918
+
1919
+
1920
+ ###############################
1921
+ # FUNCTIONS FOR functional.py #
1922
+ ###############################
1923
+
1924
+
1925
+ def set_adapter(
1926
+ model,
1927
+ adapter_name: str | list[str],
1928
+ inference_mode: bool = False,
1929
+ layer_cls: type[BaseTunerLayer] = BaseTunerLayer,
1930
+ ) -> None:
1931
+ """Set the active PEFT adapter(s) of the model.
1932
+
1933
+ Active adapters are those adapters that participate in the forward pass. Use this function if you want to switch
1934
+ between multiple PEFT adapters.
1935
+
1936
+ Args:
1937
+ model (`nn.Module`):
1938
+ The model on which the adapter(s) should be set.
1939
+ adapter_name (str, list[str]):
1940
+ The name(s) of the adapter(s) to set as active
1941
+ inference_mode (bool, optional):
1942
+ Whether the activated adapter should be frozen (i.e. `requires_grad=False`). Default is False.
1943
+ layer_cls (type, optional):
1944
+ The class of the adapter layer. Defaults to `BaseTunerLayer`.
1945
+ """
1946
+ _set_adapter(model, adapter_name, inference_mode=inference_mode) # auxiliary modules
1947
+ for module in model.modules():
1948
+ if isinstance(module, layer_cls):
1949
+ if module.merged:
1950
+ warnings.warn("Adapter cannot be set when the model is merged. Unmerging the model first.")
1951
+ module.unmerge()
1952
+ module.set_adapter(adapter_name, inference_mode=inference_mode)
1953
+
1954
+
1955
+ def _delete_auxiliary_adapter(model, adapter_name: str, new_active_adapters: Optional[list[str]]) -> None:
1956
+ for module in model.modules():
1957
+ if isinstance(module, AuxiliaryTrainingWrapper):
1958
+ module.delete_adapter(adapter_name, new_active_adapters=new_active_adapters)
1959
+
1960
+
1961
+ def delete_adapter(
1962
+ model: nn.Module, adapter_name: str, prefix: str, layer_cls: type[BaseTunerLayer] = BaseTunerLayer
1963
+ ) -> list[str] | None:
1964
+ """
1965
+ Delete an existing PEFT adapter.
1966
+
1967
+ Note: This function does not delete the PEFT config on the model, if there is one. It will also not completely
1968
+ purge the PEFT layers if the last PEFT adapter is deleted. For this, consider using `model.unload()` if using a
1969
+ PEFT model instance, or just reloading the base model.
1970
+
1971
+ Args:
1972
+ model (`nn.Module`):
1973
+ The model from which the adapter should be deleted.
1974
+ adapter_name (str):
1975
+ The name of the adapter to be deleted.
1976
+ prefix (str):
1977
+ The prefix of the PEFT method, e.g. "lora_" for LoRA.
1978
+ layer_cls (type, optional):
1979
+ The class of the adapter layer. Defaults to `BaseTunerLayer`.
1980
+
1981
+ Returns:
1982
+ new_adapter (list[str] | None):
1983
+ The name of remaining adapter(s) after deletion, or `None` if there are no active adapters left. Use this
1984
+ to set the new active adapter of the model if necessary.
1985
+ """
1986
+ key_list = [key for key, _ in model.named_modules() if prefix not in key]
1987
+ new_adapter = None
1988
+
1989
+ for key in key_list:
1990
+ _, target, _ = _get_submodules(model, key)
1991
+ if isinstance(target, layer_cls):
1992
+ target.delete_adapter(adapter_name)
1993
+ if new_adapter is None:
1994
+ new_adapter = target.active_adapters[:]
1995
+
1996
+ _delete_auxiliary_adapter(model, adapter_name=adapter_name, new_active_adapters=new_adapter)
1997
+ return new_adapter
1998
+
1999
+
2000
+ def cast_adapter_dtype(model: nn.Module, adapter_name: str, autocast_adapter_dtype: bool = True) -> None:
2001
+ """
2002
+ A helper method to cast the adapter weights to the correct dtype.
2003
+
2004
+ Currently, this only upcasts float16 and bfloat16 to float32.
2005
+
2006
+ Args:
2007
+ adapter_name (`str`):
2008
+ The adapter name.
2009
+ autocast_adapter_dtype (`bool`, *optional*):
2010
+ Whether to autocast the adapter dtype. Defaults to `True`.
2011
+ """
2012
+ if not autocast_adapter_dtype:
2013
+ return
2014
+
2015
+ dtypes_to_convert_to_fp32 = {torch.float16, torch.bfloat16}
2016
+
2017
+ for module in model.modules():
2018
+ if not isinstance(module, BaseTunerLayer):
2019
+ continue
2020
+
2021
+ for submodule in module.modules():
2022
+ if not isinstance(submodule, (nn.ModuleDict, nn.ParameterDict, BufferDict)):
2023
+ continue
2024
+
2025
+ if adapter_name not in submodule:
2026
+ continue
2027
+
2028
+ if isinstance(submodule[adapter_name], nn.Parameter):
2029
+ if submodule[adapter_name].dtype in dtypes_to_convert_to_fp32:
2030
+ submodule[adapter_name].data = submodule[adapter_name].data.to(torch.float32)
2031
+ continue
2032
+
2033
+ if isinstance(submodule[adapter_name], torch.Tensor): # e.g. from a BufferDict
2034
+ if submodule[adapter_name].dtype in dtypes_to_convert_to_fp32:
2035
+ submodule[adapter_name] = submodule[adapter_name].to(torch.float32)
2036
+ continue
2037
+
2038
+ for param in submodule[adapter_name].parameters():
2039
+ if param.dtype in dtypes_to_convert_to_fp32:
2040
+ param.data = param.data.to(torch.float32)
2041
+
2042
+
2043
+ def set_requires_grad(model, adapter_names: str | Sequence[str], requires_grad: bool = True) -> None:
2044
+ """
2045
+ Enable or disable gradients on the given adapter(s).
2046
+
2047
+ Args:
2048
+ model (`nn.Module`):
2049
+ The model from which the adapter should be deleted.
2050
+ adapter_name (`str` or `Sequence[str]`):
2051
+ The name of the adapter(s) whose gradients should be enabled/disabled.
2052
+ requires_grad (`bool`, *optional*)
2053
+ Whether to enable (`True`, default) or disable (`False`).
2054
+ """
2055
+ for module in model.modules():
2056
+ if isinstance(module, (BaseTunerLayer, AuxiliaryTrainingWrapper)):
2057
+ module.set_requires_grad(adapter_names=adapter_names, requires_grad=requires_grad)
2058
+
2059
+
2060
+ def get_device_map(model) -> dict:
2061
+ if hasattr(model, "hf_device_map"):
2062
+ # Multi-device case: accelerate dispatch is active and exposes hf_device_map
2063
+ device_map = model.hf_device_map
2064
+ else:
2065
+ # Single-device case:
2066
+ # Recent Transformers versions intentionally skip accelerate hooks when the
2067
+ # device_map resolves to a single device (e.g. "cpu" or one GPU), so
2068
+ # hf_device_map is not set. All parameters are guaranteed to be on the
2069
+ # same device, which can be inferred from the first parameter.
2070
+ device_map = {"": next(model.parameters()).device}
2071
+ return device_map
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/vblora/__init__.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 peft.utils import register_peft_method
16
+
17
+ from .config import VBLoRAConfig
18
+ from .layer import Linear, VBLoRALayer
19
+ from .model import VBLoRAModel
20
+
21
+
22
+ __all__ = ["Linear", "VBLoRAConfig", "VBLoRALayer", "VBLoRAModel"]
23
+
24
+ register_peft_method(name="vblora", config_cls=VBLoRAConfig, model_cls=VBLoRAModel)
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/vblora/config.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 __future__ import annotations
16
+
17
+ from dataclasses import dataclass, field
18
+ from typing import Optional, Union
19
+
20
+ from peft.config import PeftConfig
21
+ from peft.utils import PeftType
22
+
23
+
24
+ @dataclass
25
+ class VBLoRAConfig(PeftConfig):
26
+ """
27
+ This is the configuration class to store the configuration of a [`VBLoRAConfig`].
28
+
29
+ Paper: https://huggingface.co/papers/2405.15179
30
+
31
+ Args:
32
+ r (`int`):
33
+ The rank of incremental matrices.
34
+ num_vectors (`int`):
35
+ Number of vectors in the vector bank. Use higher values when the model size increases.
36
+ vector_length (`int`):
37
+ The length of the vectors in the vector bank. The length of the vectors should be divisible by the hidden
38
+ dimension of the model.
39
+ topk (`int`):
40
+ The K value for top-K selection. A larger value of K increases the size of the saved model. In practice,
41
+ setting K=2 typically provides the best performance and parameter efficiency. For more details, refer to
42
+ the discussion in the paper.
43
+ target_modules (`Union[List[str], str]`):
44
+ The names of the modules to apply the adapter to. If this is specified, only the modules with the specified
45
+ names will be replaced. When passing a string, a regex match will be performed. When passing a list of
46
+ strings, either an exact match will be performed or it is checked if the name of the module ends with any
47
+ of the passed strings. If this is specified as 'all-linear', then all linear/Conv1D modules are chosen,
48
+ excluding the output layer. If this is not specified, modules will be chosen according to the model
49
+ architecture. If the architecture is not known, an error will be raised -- in this case, you should specify
50
+ the target modules manually.
51
+ exclude_modules (`Optional[Union[List[str], str]]`):
52
+ The names of the modules to not apply the adapter. When passing a string, a regex match will be performed.
53
+ When passing a list of strings, either an exact match will be performed or it is checked if the name of the
54
+ module ends with any of the passed strings.
55
+ save_only_topk_weights (`bool`):
56
+ Whether to only save the topk weights. Setting `save_only_topk_weights = True` significantly reduces
57
+ storage space. However, models saved in this mode can be used for merging or inference only, not for
58
+ resuming training.
59
+ vblora_dropout (`float`):
60
+ The dropout probability for VBLoRA layers.
61
+ fan_in_fan_out (`bool`):
62
+ Set this to True if the layer to replace stores weight like (fan_in, fan_out). For example, gpt-2 uses
63
+ `Conv1D` which stores weights like (fan_in, fan_out) and hence this should be set to `True`.
64
+ bias (`str`):
65
+ Bias type for VBLoRA. Can be 'none', 'all' or 'vblora_only'. If 'all' or 'vblora_only', the corresponding
66
+ biases will be updated during training. Be aware that this means that, even when disabling the adapters,
67
+ the model will not produce the same output as the base model would have without adaptation.
68
+ modules_to_save (`List[str]`):
69
+ List of modules apart from VBLoRA layers to be set as trainable and saved in the final checkpoint.
70
+ init_vector_bank_bound (`float`):
71
+ The vector bank is initialized with a uniform distribution between -init_vector_bank_bound and
72
+ init_vector_bank_bound. Avoid initializing the vector bank with all zeros to prevent zero gradients. A
73
+ small value, such as 0.02, is typically effective. Initializing with a large value may cause training
74
+ instability.
75
+ init_logits_std (`float`):
76
+ The logits are initialized with a normal distribution with a standard deviation of init_logits_std. Default
77
+ is 0.1.
78
+ layers_to_transform (`Union[List[int],int]`):
79
+ The layer indices to transform. If a list of ints is passed, it will apply the adapter to the layer indices
80
+ that are specified in this list. If a single integer is passed, it will apply the transformations on the
81
+ layer at this index.
82
+ layers_pattern (`Optional[Union[List[str], str]]`):
83
+ The layer pattern name, used only if `layers_to_transform` is different from `None`. This should target the
84
+ `nn.ModuleList` of the model, which is often called `'layers'` or `'h'`.
85
+ """
86
+
87
+ r: int = field(default=4, metadata={"help": "The rank of incremental matrices."})
88
+ num_vectors: int = field(
89
+ default=256,
90
+ metadata={"help": "Number of vectors in the vector bank. Use higher values when the model size increases."},
91
+ )
92
+ vector_length: int = field(
93
+ default=256,
94
+ metadata={
95
+ "help": "The length of the vectors in the vector bank. The length of the vectors should be divisible by "
96
+ "the hidden dimension of the model."
97
+ },
98
+ )
99
+ topk: int = field(
100
+ default=2,
101
+ metadata={
102
+ "help": "The K value for top-K selection. A larger value of K increases the size of the saved model. "
103
+ "In practice, setting K=2 typically provides the best performance and parameter efficiency. "
104
+ "For more details, refer to the discussion in the paper."
105
+ },
106
+ )
107
+ target_modules: Optional[Union[list[str], str]] = field(
108
+ default=None,
109
+ metadata={
110
+ "help": (
111
+ "List of module names or regex expression of the module names to replace with LoRA."
112
+ "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'."
113
+ "This can also be a wildcard 'all-linear' which matches all linear/Conv1D layers except the output layer."
114
+ "If not specified, modules will be chosen according to the model architecture, If the architecture is "
115
+ "not known, an error will be raised -- in this case, you should specify the target modules manually."
116
+ )
117
+ },
118
+ )
119
+ exclude_modules: Optional[Union[list[str], str]] = field(
120
+ default=None,
121
+ metadata={"help": "List of module names or regex expression of the module names to exclude from VBLoRA."},
122
+ )
123
+ save_only_topk_weights: bool = field(
124
+ default=False,
125
+ metadata={
126
+ "help": (
127
+ "Whether to only save the topk weights. Setting `save_only_topk_weights = True` significantly reduces "
128
+ "storage space. However, models saved in this mode can be used for merging or inference only, not for "
129
+ "resuming training."
130
+ )
131
+ },
132
+ )
133
+ vblora_dropout: float = field(default=0.0, metadata={"help": "VBLoRA dropout"})
134
+ fan_in_fan_out: bool = field(
135
+ default=False,
136
+ metadata={"help": "Set this to True if the layer to replace stores weight like (fan_in, fan_out)"},
137
+ )
138
+ bias: str = field(default="none", metadata={"help": "Bias type for VBLoRA. Can be 'none', 'all' or 'vblora_only'"})
139
+ modules_to_save: Optional[list[str]] = field(
140
+ default=None,
141
+ metadata={
142
+ "help": (
143
+ "List of modules apart from VBLoRA layers to be set as trainable and saved in the final checkpoint. For"
144
+ " example, in Sequence Classification or Token Classification tasks, the final layer"
145
+ " `classifier/score` are randomly initialized and as such need to be trainable and saved."
146
+ )
147
+ },
148
+ )
149
+ init_vector_bank_bound: float = field(
150
+ default=0.02,
151
+ metadata={
152
+ "help": (
153
+ "The vector bank is initialized with a uniform distribution between -init_vector_bank_bound and"
154
+ " init_vector_bank_bound. Avoid initializing the vector bank with all zeros to prevent zero gradients."
155
+ " A small value, such as 0.02, is typically effective. Initializing with a large value may cause"
156
+ " training instability."
157
+ ),
158
+ },
159
+ )
160
+ init_logits_std: float = field(
161
+ default=0.1,
162
+ metadata={
163
+ "help": (
164
+ "The logits are initialized with a normal distribution with a standard deviation of init_logits_std. "
165
+ "Default value 0.1 typically works well."
166
+ ),
167
+ },
168
+ )
169
+ layers_to_transform: Optional[Union[list[int], int]] = field(
170
+ default=None,
171
+ metadata={
172
+ "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. "
173
+ "This only works when target_modules is a list of str. This should target the `nn.ModuleList` of the "
174
+ "model, which is often called `'layers'` or `'h'`."
175
+ },
176
+ )
177
+ layers_pattern: Optional[Union[list[str], str]] = field(
178
+ default=None,
179
+ metadata={
180
+ "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."
181
+ "This only works when target_modules is a list of str."
182
+ },
183
+ )
184
+
185
+ def __post_init__(self):
186
+ super().__post_init__()
187
+ self.peft_type = PeftType.VBLORA
188
+ self.target_modules = (
189
+ set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules
190
+ )
191
+ self.exclude_modules = (
192
+ set(self.exclude_modules) if isinstance(self.exclude_modules, list) else self.exclude_modules
193
+ )
194
+ # check for layers_to_transform and layers_pattern
195
+ if self.layers_pattern and not self.layers_to_transform:
196
+ raise ValueError("When `layers_pattern` is specified, `layers_to_transform` must also be specified. ")
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/vblora/layer.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing import Optional
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+ import torch.nn.functional as F
21
+ from transformers.pytorch_utils import Conv1D
22
+
23
+ from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge
24
+ from peft.utils.other import transpose
25
+
26
+
27
+ class VBLoRALayer(BaseTunerLayer):
28
+ # List all names of layers that may contain adapter weights
29
+ adapter_layer_names = ("vblora_logits_A", "vblora_logits_B", "vblora_vector_bank")
30
+
31
+ def __init__(self, base_layer: nn.Module, **kwargs):
32
+ self.base_layer = base_layer
33
+ self.r = {}
34
+ self.topk = {}
35
+ self.vblora_dropout = nn.ModuleDict({})
36
+
37
+ # For storing vector scale
38
+ self.vblora_logits_A = nn.ParameterDict({})
39
+ self.vblora_logits_B = nn.ParameterDict({})
40
+
41
+ # Mark the weight as unmerged
42
+ self._disable_adapters = False
43
+ self.merged_adapters = []
44
+
45
+ base_layer = self.get_base_layer()
46
+ if isinstance(base_layer, nn.Linear):
47
+ in_features, out_features = base_layer.in_features, base_layer.out_features
48
+ elif isinstance(base_layer, Conv1D):
49
+ in_features, out_features = (
50
+ base_layer.weight.ds_shape if hasattr(base_layer.weight, "ds_shape") else base_layer.weight.shape
51
+ )
52
+
53
+ self.in_features = in_features
54
+ self.out_features = out_features
55
+ self.kwargs = kwargs
56
+
57
+ @property
58
+ def merged(self) -> bool:
59
+ return bool(self.merged_adapters)
60
+
61
+ def update_layer(
62
+ self,
63
+ adapter_name: str,
64
+ vblora_vector_bank,
65
+ r: int,
66
+ topk: int,
67
+ num_vectors: int,
68
+ vector_length: float,
69
+ vblora_dropout: float = 0.0,
70
+ init_logits_std: float = 0.01,
71
+ inference_mode: bool = False,
72
+ **kwargs,
73
+ ):
74
+ if r <= 0:
75
+ raise ValueError(f"`r` {r} should be a positive integer value")
76
+ if topk <= 0:
77
+ raise ValueError(f"`topk` {topk} should be a positive integer value")
78
+
79
+ if self.in_features % vector_length != 0:
80
+ raise ValueError(f"`in_features` {self.in_features} must be divisible by `vector_length` {vector_length}")
81
+ if self.out_features % vector_length != 0:
82
+ raise ValueError(
83
+ f"`out_features` {self.out_features} must be divisible by `vector_length` {vector_length}"
84
+ )
85
+
86
+ self.r[adapter_name] = r
87
+ self.topk[adapter_name] = topk
88
+ if vblora_dropout > 0.0:
89
+ vblora_dropout_layer = nn.Dropout(p=vblora_dropout)
90
+ else:
91
+ vblora_dropout_layer = nn.Identity()
92
+ self.vblora_dropout.update(nn.ModuleDict({adapter_name: vblora_dropout_layer}))
93
+ self.vblora_logits_A[adapter_name] = nn.Parameter(
94
+ torch.zeros(r, self.in_features // vector_length, num_vectors), requires_grad=True
95
+ )
96
+ self.vblora_logits_B[adapter_name] = nn.Parameter(
97
+ torch.zeros(self.out_features // vector_length, r, num_vectors), requires_grad=True
98
+ )
99
+ self.vblora_vector_bank = vblora_vector_bank
100
+ self.reset_vblora_logits(adapter_name, init_logits_std)
101
+ self._move_adapter_to_device_of_base_layer(adapter_name)
102
+ self.set_adapter(self.active_adapters, inference_mode=inference_mode)
103
+
104
+ def reset_vblora_logits(self, adapter_name, init_logits_std):
105
+ if adapter_name in self.vblora_logits_A.keys():
106
+ with torch.no_grad():
107
+ nn.init.normal_(self.vblora_logits_A[adapter_name], 0, init_logits_std)
108
+ nn.init.normal_(self.vblora_logits_B[adapter_name], 0, init_logits_std)
109
+
110
+
111
+ class Linear(nn.Linear, VBLoRALayer):
112
+ # VBLoRA implemented in a dense layer
113
+ def __init__(
114
+ self,
115
+ base_layer,
116
+ vblora_vector_bank,
117
+ adapter_name: str,
118
+ r: int,
119
+ num_vectors: int,
120
+ vector_length: int,
121
+ topk: int = 2,
122
+ vblora_dropout: float = 0.0,
123
+ init_logits_std: float = 0.01,
124
+ fan_in_fan_out: bool = False, # Set this to True if the layer to replace stores weight like (fan_in, fan_out)
125
+ is_target_conv_1d_layer: bool = False,
126
+ **kwargs,
127
+ ) -> None:
128
+ # this gets the init from nn.Linear's super perspective, i.e. nn.Module.__init__, which should always be called
129
+ super(nn.Linear, self).__init__()
130
+ VBLoRALayer.__init__(self, base_layer, **kwargs)
131
+ self.fan_in_fan_out = fan_in_fan_out
132
+ self._active_adapter = adapter_name
133
+ self.update_layer(
134
+ adapter_name, vblora_vector_bank, r, topk, num_vectors, vector_length, vblora_dropout, init_logits_std
135
+ )
136
+ self.is_target_conv_1d_layer = is_target_conv_1d_layer
137
+
138
+ def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None:
139
+ """
140
+ Merge the active adapter weights into the base weights
141
+
142
+ Args:
143
+ safe_merge (`bool`, *optional*):
144
+ If True, the merge operation will be performed in a copy of the original weights and check for NaNs
145
+ before merging the weights. This is useful if you want to check if the merge operation will produce
146
+ NaNs. Defaults to `False`.
147
+ adapter_names (`List[str]`, *optional*):
148
+ The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults
149
+ to `None`.
150
+ """
151
+ adapter_names = check_adapters_to_merge(self, adapter_names)
152
+ if not adapter_names:
153
+ # no adapter to merge
154
+ return
155
+
156
+ for active_adapter in adapter_names:
157
+ if active_adapter in self.vblora_logits_A.keys():
158
+ base_layer = self.get_base_layer()
159
+ if safe_merge:
160
+ # Note that safe_merge will be slower than the normal merge
161
+ # because of the copy operation.
162
+ orig_weights = base_layer.weight.data.clone()
163
+ orig_weights += self.get_delta_weight(active_adapter)
164
+ if not torch.isfinite(orig_weights).all():
165
+ raise ValueError(
166
+ f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken"
167
+ )
168
+ base_layer.weight.data = orig_weights
169
+ else:
170
+ base_layer.weight.data += self.get_delta_weight(active_adapter)
171
+ self.merged_adapters.append(active_adapter)
172
+
173
+ def unmerge(self) -> None:
174
+ if not self.merged:
175
+ warnings.warn("Already unmerged. Nothing to do.")
176
+ return
177
+
178
+ while len(self.merged_adapters) > 0:
179
+ active_adapter = self.merged_adapters.pop()
180
+ if active_adapter in self.vblora_logits_A.keys():
181
+ self.get_base_layer().weight.data -= self.get_delta_weight(active_adapter)
182
+
183
+ def _get_low_rank_matrix(self, logits: torch.tensor, vblora_vector_bank, topk) -> torch.Tensor:
184
+ top_k_logits, indices = logits.topk(topk, dim=-1)
185
+ topk_weights = F.softmax(top_k_logits, dim=-1)
186
+ return (topk_weights.unsqueeze(-1) * vblora_vector_bank[indices]).sum(-2)
187
+
188
+ def _get_lora_matrices(self, adapter, cast_to_fp32=False) -> tuple[torch.Tensor, torch.Tensor]:
189
+ vblora_logits_A = self.vblora_logits_A[adapter]
190
+ vblora_logits_B = self.vblora_logits_B[adapter]
191
+
192
+ # Check for infinity values when training. If found, training was likely resumed from a `save_only_topk_weights` model.
193
+ if self.training and vblora_logits_A[0, 0].isinf().any():
194
+ raise RuntimeError(
195
+ "Found infinity values in VB-LoRA logits. Ensure training was not resumed from a `save_only_topk_weights` model."
196
+ )
197
+
198
+ vblora_vector_bank = self.vblora_vector_bank[adapter].to(vblora_logits_A.device)
199
+ topk = self.topk[adapter]
200
+ # In case users wants to merge the adapter weights that are in
201
+ # float16 while being on CPU, we need to cast the weights to float32, perform the merge and then cast back to
202
+ # float16 because the `@` and matmul operation in general is not supported in torch + cpu + fp16.
203
+ if cast_to_fp32:
204
+ vblora_logits_A = vblora_logits_A.float()
205
+ vblora_logits_B = vblora_logits_B.float()
206
+ vblora_vector_bank = vblora_vector_bank.float()
207
+
208
+ # A: (rank, in_tile, vector_length) -> (rank, in_tile x vector_length)
209
+ A = self._get_low_rank_matrix(vblora_logits_A, vblora_vector_bank, topk).reshape(vblora_logits_A.shape[0], -1)
210
+ # B: (out_tile, rank, vector_length) -> (out_tile, vector_length, rank) -> (out_tile x vector_length, rank)
211
+ B = (
212
+ self._get_low_rank_matrix(vblora_logits_B, vblora_vector_bank, topk)
213
+ .transpose(1, 2)
214
+ .reshape(-1, vblora_logits_B.shape[1])
215
+ )
216
+ return A, B
217
+
218
+ def get_delta_weight(self, adapter) -> torch.Tensor:
219
+ """
220
+ Compute the delta weight for the given adapter.
221
+
222
+ Args:
223
+ adapter (str):
224
+ The name of the adapter for which the delta weight should be computed.
225
+ """
226
+ device = self.vblora_logits_A[adapter].device
227
+ dtype = self.vblora_logits_A[adapter].dtype
228
+ cast_to_fp32 = device.type == "cpu" and dtype == torch.float16
229
+ A, B = self._get_lora_matrices(adapter, cast_to_fp32)
230
+ output_tensor = transpose(B @ A, self.fan_in_fan_out)
231
+ return output_tensor
232
+
233
+ def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor:
234
+ previous_dtype = x.dtype
235
+ if self.disable_adapters:
236
+ if self.merged:
237
+ self.unmerge()
238
+ result = self.base_layer(x, *args, **kwargs)
239
+ elif self.merged:
240
+ result = self.base_layer(x, *args, **kwargs)
241
+ else:
242
+ result = self.base_layer(x, *args, **kwargs)
243
+ for active_adapter in self.active_adapters:
244
+ if active_adapter not in self.vblora_logits_A.keys():
245
+ continue
246
+ A, B = self._get_lora_matrices(active_adapter)
247
+ x = x.to(self.vblora_vector_bank[active_adapter].dtype)
248
+ dropout = self.vblora_dropout[active_adapter]
249
+ result = result + F.linear(F.linear(dropout(x), A), B)
250
+ result = result.to(previous_dtype)
251
+ return result
252
+
253
+ def supports_lora_conversion(self, adapter_name: str = "default") -> bool:
254
+ return True
255
+
256
+ def __repr__(self) -> str:
257
+ rep = super().__repr__()
258
+ return "vblora." + rep
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/vblora/model.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 warnings
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+ from transformers.pytorch_utils import Conv1D
21
+
22
+ from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer
23
+ from peft.utils import TRANSFORMERS_MODELS_TO_VBLORA_TARGET_MODULES_MAPPING
24
+
25
+ from .config import VBLoRAConfig
26
+ from .layer import Linear, VBLoRALayer
27
+
28
+
29
+ class VBLoRAModel(BaseTuner):
30
+ """
31
+ Creates VBLoRA model from a pretrained transformers model.
32
+
33
+ The method is described in detail in https://huggingface.co/papers/2405.15179.
34
+
35
+ Args:
36
+ model ([`~transformers.PreTrainedModel`]): The model to be adapted.
37
+ config ([`VBLoRAConfig`]): The configuration of the VBLoRA model.
38
+ adapter_name (`str`): The name of the adapter, defaults to `"default"`.
39
+ low_cpu_mem_usage (`bool`, `optional`, defaults to `False`):
40
+ Create empty adapter weights on meta device. Useful to speed up the loading process.
41
+
42
+ Returns:
43
+ `torch.nn.Module`: The VBLoRA model.
44
+
45
+ Example:
46
+
47
+ ```py
48
+ >>> from transformers import AutoModelForCausalLM
49
+ >>> from peft import VBLoRAConfig, get_peft_model
50
+
51
+ >>> base_model = AutoModelForCausalLM.from_pretrained("facebook/opt-125m")
52
+ >>> config = VBLoRAConfig(
53
+ ... task_type="SEQ_CLS",
54
+ ... r=4,
55
+ ... target_modules=["fc1", "fc2", "k_proj", "out_proj", "q_proj", "v_proj"],
56
+ ... num_vectors=60,
57
+ ... vector_length=256,
58
+ ... save_only_topk_weights=True,
59
+ ... )
60
+ >>> model = get_peft_model(base_model, config)
61
+ ```
62
+
63
+ **Attributes**:
64
+ - **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted.
65
+ - **peft_config** ([`VBLoRAConfig`]): The configuration of the VBLoRAConfig model.
66
+ """
67
+
68
+ prefix: str = "vblora_"
69
+ tuner_layer_cls = VBLoRALayer
70
+ target_module_mapping = TRANSFORMERS_MODELS_TO_VBLORA_TARGET_MODULES_MAPPING
71
+
72
+ def _init_vblora_vector_bank(self, config: VBLoRAConfig, adapter_name: str) -> None:
73
+ vblora_vector_bank = torch.zeros(config.num_vectors, config.vector_length)
74
+ torch.nn.init.uniform_(vblora_vector_bank, -config.init_vector_bank_bound, config.init_vector_bank_bound)
75
+ self.vblora_vector_bank[adapter_name] = vblora_vector_bank
76
+
77
+ def _pre_injection_hook(self, model: nn.Module, config: VBLoRAConfig, adapter_name: str) -> None:
78
+ self.vblora_vector_bank = nn.ParameterDict({})
79
+
80
+ def _create_and_replace(
81
+ self,
82
+ vblora_config,
83
+ adapter_name,
84
+ target,
85
+ target_name,
86
+ parent,
87
+ current_key,
88
+ ):
89
+ if current_key is None:
90
+ raise ValueError("Current Key shouldn't be `None`")
91
+
92
+ bias = hasattr(target, "bias") and target.bias is not None
93
+ kwargs = {
94
+ "fan_in_fan_out": vblora_config.fan_in_fan_out,
95
+ "bias": bias,
96
+ }
97
+ self._init_vblora_vector_bank(vblora_config, adapter_name)
98
+ # TODO: add quantization support
99
+
100
+ if isinstance(target, Linear):
101
+ target.update_layer(
102
+ adapter_name=adapter_name,
103
+ vblora_vector_bank=self.vblora_vector_bank,
104
+ r=vblora_config.r,
105
+ topk=vblora_config.topk,
106
+ num_vectors=vblora_config.num_vectors,
107
+ vector_length=vblora_config.vector_length,
108
+ vblora_dropout=vblora_config.vblora_dropout,
109
+ init_logits_std=vblora_config.init_logits_std,
110
+ )
111
+ else:
112
+ new_module = self._create_new_module(
113
+ vblora_config=vblora_config,
114
+ vblora_vector_bank=self.vblora_vector_bank,
115
+ adapter_name=adapter_name,
116
+ target=target,
117
+ **kwargs,
118
+ )
119
+ if adapter_name not in self.active_adapter:
120
+ # adding an additional adapter: it is not automatically trainable
121
+ new_module.requires_grad_(False)
122
+ self._replace_module(parent, target_name, new_module, target)
123
+
124
+ @staticmethod
125
+ def _create_new_module(vblora_config, vblora_vector_bank, adapter_name, target, **kwargs):
126
+ if isinstance(target, BaseTunerLayer):
127
+ target_base_layer = target.get_base_layer()
128
+ else:
129
+ target_base_layer = target
130
+
131
+ if isinstance(target_base_layer, torch.nn.Linear):
132
+ if kwargs["fan_in_fan_out"]:
133
+ warnings.warn(
134
+ "fan_in_fan_out is set to True but the target module is `torch.nn.Linear`. "
135
+ "Setting fan_in_fan_out to False."
136
+ )
137
+ kwargs["fan_in_fan_out"] = vblora_config.fan_in_fan_out = False
138
+ elif isinstance(target_base_layer, Conv1D):
139
+ kwargs["is_target_conv_1d_layer"] = True
140
+ if not kwargs["fan_in_fan_out"]:
141
+ warnings.warn(
142
+ "fan_in_fan_out is set to False but the target module is `Conv1D`. Setting fan_in_fan_out to True."
143
+ )
144
+ kwargs["fan_in_fan_out"] = vblora_config.fan_in_fan_out = True
145
+ else:
146
+ raise ValueError(
147
+ f"Target module {target} is not supported. Currently, only the following modules are supported: "
148
+ "`torch.nn.Linear`, `transformers.pytorch_utils.Conv1D`."
149
+ )
150
+ new_module = Linear(
151
+ base_layer=target,
152
+ vblora_vector_bank=vblora_vector_bank,
153
+ adapter_name=adapter_name,
154
+ r=vblora_config.r,
155
+ num_vectors=vblora_config.num_vectors,
156
+ vector_length=vblora_config.vector_length,
157
+ topk=vblora_config.topk,
158
+ vblora_dropout=vblora_config.vblora_dropout,
159
+ init_logits_std=vblora_config.init_logits_std,
160
+ **kwargs,
161
+ )
162
+
163
+ return new_module
164
+
165
+ def get_nb_savable_parameters(self, adapter="default") -> tuple[int, int]:
166
+ r"""
167
+ Returns the number of savable VB-LoRA parameters and other savable parameters.
168
+ """
169
+ logits_params = 0
170
+ vector_bank_params = 0
171
+ other_params = 0
172
+ for name, param in self.named_parameters():
173
+ if "vblora_logits" in name:
174
+ logits_params += param.numel()
175
+ elif "vblora_vector_bank" in name:
176
+ vector_bank_params += param.numel()
177
+ elif param.requires_grad:
178
+ other_params += param.numel()
179
+ if self.peft_config[adapter].save_only_topk_weights:
180
+ num_vectors = self.peft_config[adapter].num_vectors
181
+ factor = 1 # factor to count float32-equivalent parameters
182
+ if num_vectors < 2**8:
183
+ factor = 0.25
184
+ elif num_vectors < 2**15:
185
+ factor = 0.5
186
+ elif num_vectors < 2**31:
187
+ factor = 1
188
+ else:
189
+ factor = 2
190
+ topk_weight_params = (
191
+ logits_params / self.peft_config[adapter].num_vectors * (self.peft_config[adapter].topk - 1)
192
+ )
193
+ topk_indices_params = (
194
+ logits_params / self.peft_config[adapter].num_vectors * self.peft_config[adapter].topk * factor
195
+ )
196
+ vblora_params = int(vector_bank_params + topk_weight_params + topk_indices_params)
197
+ else:
198
+ vblora_params = vector_bank_params + logits_params
199
+ return vblora_params, other_params
200
+
201
+ def print_savable_parameters(self) -> None:
202
+ r"""
203
+ Prints the number of savable VB-LoRA parameters and total savable parameters.
204
+ """
205
+ vblora_params, other_params = self.get_nb_savable_parameters()
206
+ print(
207
+ f"VB-LoRA params to-be-saved (float32-equivalent): {vblora_params:,d} "
208
+ f"|| total params to-be-saved: {(vblora_params + other_params):,d}"
209
+ )
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/vera/__init__.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
16
+ from peft.utils import register_peft_method
17
+
18
+ from .config import VeraConfig
19
+ from .layer import Linear, VeraLayer
20
+ from .model import VeraModel
21
+
22
+
23
+ __all__ = ["Linear", "VeraConfig", "VeraLayer", "VeraModel"]
24
+
25
+
26
+ register_peft_method(name="vera", config_cls=VeraConfig, model_cls=VeraModel, prefix="vera_lambda_")
27
+
28
+
29
+ def __getattr__(name):
30
+ if (name == "Linear8bitLt") and is_bnb_available():
31
+ from .bnb import Linear8bitLt
32
+
33
+ return Linear8bitLt
34
+
35
+ if (name == "Linear4bit") and is_bnb_4bit_available():
36
+ from .bnb import Linear4bit
37
+
38
+ return Linear4bit
39
+
40
+ raise AttributeError(f"module {__name__} has no attribute {name}")
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/vera/bnb.py ADDED
@@ -0,0 +1,411 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 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 check_adapters_to_merge
24
+ from peft.utils.integrations import dequantize_bnb_weight
25
+ from peft.utils.other import transpose
26
+
27
+ from .layer import VeraLayer
28
+
29
+
30
+ if is_bnb_available():
31
+
32
+ class Linear8bitLt(torch.nn.Module, VeraLayer):
33
+ def __init__(
34
+ self,
35
+ base_layer: torch.nn.Module,
36
+ adapter_name: str,
37
+ vera_A,
38
+ vera_B,
39
+ r: int = 0,
40
+ vera_dropout: float = 0.0,
41
+ fan_in_fan_out: bool = False,
42
+ init_weights: bool = True,
43
+ d_initial: float = 0.1,
44
+ **kwargs,
45
+ ) -> None:
46
+ super().__init__()
47
+ VeraLayer.__init__(self, base_layer)
48
+ self.fan_in_fan_out = fan_in_fan_out
49
+
50
+ self._active_adapter = adapter_name
51
+ self.update_layer(
52
+ adapter_name,
53
+ vera_A,
54
+ vera_B,
55
+ r,
56
+ vera_dropout=vera_dropout,
57
+ init_weights=init_weights,
58
+ d_initial=d_initial,
59
+ )
60
+
61
+ def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None:
62
+ if self.merged:
63
+ warnings.warn(
64
+ f"Already following adapters were merged {','.join(self.merged_adapters)}. "
65
+ f"You are now additionally merging {','.join(self.active_adapters)}."
66
+ )
67
+
68
+ adapter_names = check_adapters_to_merge(self, adapter_names)
69
+ if not adapter_names:
70
+ return
71
+
72
+ for active_adapter in adapter_names:
73
+ if active_adapter not in self.vera_lambda_d.keys():
74
+ continue
75
+
76
+ warnings.warn(
77
+ "Merge vera module to 8-bit linear may get different generations due to rounding errors."
78
+ )
79
+ vera_data = self.get_delta_weight(active_adapter)
80
+
81
+ weight = self.get_base_layer().weight
82
+ state = self.get_base_layer().state
83
+ if state.SCB is None:
84
+ state.SCB = weight.SCB
85
+
86
+ output = dequantize_bnb_weight(weight, state)
87
+ w_data = output.to(vera_data.dtype).to(vera_data.device) + vera_data
88
+
89
+ if safe_merge and not torch.isfinite(w_data).all():
90
+ raise ValueError(
91
+ f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken"
92
+ )
93
+
94
+ self.get_base_layer().weight = bnb.nn.Int8Params(
95
+ w_data.to("cpu"), requires_grad=False, has_fp16_weights=weight.has_fp16_weights
96
+ ).to(weight.device)
97
+ state.reset_grads()
98
+ self.merged_adapters.append(active_adapter)
99
+
100
+ def unmerge(self) -> None:
101
+ if not self.merged:
102
+ warnings.warn("Already unmerged. Nothing to do")
103
+ return
104
+
105
+ while len(self.merged_adapters) > 0:
106
+ active_adapter = self.merged_adapters.pop()
107
+ if active_adapter not in self.vera_lambda_d.keys():
108
+ continue
109
+ warnings.warn(
110
+ "Unmerge vera module to 8-bit linear may get different generations due to rounding errors."
111
+ )
112
+ vera_data = self.get_delta_weight(active_adapter)
113
+
114
+ weight = self.get_base_layer().weight
115
+ state = self.get_base_layer().state
116
+ if state.SCB is None:
117
+ state.SCB = weight.SCB
118
+ output = dequantize_bnb_weight(weight, state=state)
119
+
120
+ w_data = output.to(vera_data.dtype).to(vera_data.device) - vera_data
121
+
122
+ self.get_base_layer().weight = bnb.nn.Int8Params(
123
+ w_data.to("cpu"), requires_grad=False, has_fp16_weights=weight.has_fp16_weights
124
+ ).to(weight.device)
125
+ state.reset_grads()
126
+
127
+ def get_delta_weight(self, adapter) -> torch.Tensor:
128
+ """
129
+ Compute the delta weight for the given adapter.
130
+
131
+ Args:
132
+ adapter (str): The name of the adapter for which the delta weight should be computed.
133
+
134
+ Returns:
135
+ torch.Tensor: The computed delta weight for the VeRA adapter.
136
+
137
+ Note:
138
+ This method implements the VeRA-specific weight update. Unlike LoRA, VeRA uses shared projection
139
+ matrices (vera_A and vera_B) across all layers, along with per-layer trainable parameters (lambda_d and
140
+ lambda_b).
141
+ """
142
+ # Retrieve shared projection matrices
143
+ vera_A = self.vera_A[adapter]
144
+ vera_B = self.vera_B[adapter]
145
+
146
+ # Retrieve per-layer trainable parameters
147
+ device = vera_B.device
148
+ dtype = vera_B.dtype
149
+
150
+ # In case users wants to merge the adapter weights that are in
151
+ # (b)float16 while being on CPU, we need to cast the weights to float32, perform the merge and then cast back to
152
+ # (b)float16 because some CPUs have slow bf16/fp16 matmuls.
153
+ cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16)
154
+
155
+ lambda_d = self.vera_lambda_d[adapter]
156
+ lambda_b = self.vera_lambda_b[adapter]
157
+
158
+ if cast_to_fp32:
159
+ vera_A = vera_A.float()
160
+ vera_B = vera_B.float()
161
+ lambda_d = lambda_d.float()
162
+ lambda_b = lambda_b.float()
163
+
164
+ sliced_A = vera_A[:, : self.in_features].to(lambda_d.device)
165
+ sliced_B = vera_B[: self.out_features, :].to(lambda_d.device)
166
+ lambda_b = lambda_b.unsqueeze(-1)
167
+ lambda_d = lambda_d.unsqueeze(-1)
168
+
169
+ # VeRA-specific computation:
170
+ # 1. Apply lambda_d to the input projection (vera_A)
171
+ # 2. Apply lambda_b to the output projection (vera_B)
172
+ # 3. Compute the outer product of the scaled projections
173
+ output_tensor = transpose((lambda_b * sliced_B) @ (lambda_d * sliced_A), self.fan_in_fan_out)
174
+
175
+ if cast_to_fp32:
176
+ output_tensor = output_tensor.to(dtype=dtype)
177
+
178
+ return output_tensor
179
+
180
+ def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor:
181
+ """
182
+ Perform the forward pass using the VeRA adapter.
183
+
184
+ Args:
185
+ x (torch.Tensor): Input tensor.
186
+
187
+ Returns:
188
+ torch.Tensor: Output tensor after applying the VeRA adaptation.
189
+
190
+ Note:
191
+ This method implements the VeRA-specific forward pass. It applies the shared projections (vera_A and
192
+ vera_B) along with the per-layer trainable parameters (lambda_d and lambda_b) to compute the adapter
193
+ output.
194
+ """
195
+ if self.disable_adapters:
196
+ if self.merged:
197
+ self.unmerge()
198
+ result = self.base_layer(x, *args, **kwargs)
199
+ elif self.merged:
200
+ result = self.base_layer(x, *args, **kwargs)
201
+ else:
202
+ result = self.base_layer(x, *args, **kwargs)
203
+ for active_adapter in self.active_adapters:
204
+ if active_adapter not in self.vera_lambda_d.keys():
205
+ continue
206
+
207
+ lambda_d = self.vera_lambda_d[active_adapter]
208
+ lambda_b = self.vera_lambda_b[active_adapter]
209
+
210
+ vera_A = self.vera_A[active_adapter]
211
+ vera_B = self.vera_B[active_adapter]
212
+
213
+ dropout = self.vera_dropout[active_adapter]
214
+
215
+ requires_conversion = not torch.is_autocast_enabled()
216
+ if requires_conversion:
217
+ expected_dtype = result.dtype
218
+ compute_dtype = lambda_d.dtype
219
+ if x.dtype != compute_dtype:
220
+ x = x.to(compute_dtype)
221
+
222
+ sliced_A = vera_A[:, : self.in_features].to(x.device)
223
+ sliced_B = vera_B[: self.out_features, :].to(x.device)
224
+
225
+ x_temp = dropout(x.to(lambda_d.dtype))
226
+
227
+ adapter_output = lambda_b * torch.nn.functional.linear(
228
+ lambda_d * torch.nn.functional.linear(x_temp, sliced_A), sliced_B
229
+ )
230
+
231
+ if requires_conversion:
232
+ adapter_output = adapter_output.to(expected_dtype)
233
+
234
+ result = result + adapter_output
235
+
236
+ # Ensure the output tensor has the same dtype as the input tensor
237
+ return result.to(x.dtype)
238
+
239
+ def __repr__(self) -> str:
240
+ rep = super().__repr__()
241
+ return "vera." + rep
242
+
243
+
244
+ if is_bnb_4bit_available():
245
+
246
+ class Linear4bit(torch.nn.Module, VeraLayer):
247
+ def __init__(
248
+ self,
249
+ base_layer: torch.nn.Module,
250
+ adapter_name: str,
251
+ vera_A,
252
+ vera_B,
253
+ r: int = 0,
254
+ vera_dropout: float = 0.0,
255
+ fan_in_fan_out: bool = False,
256
+ init_weights: bool = True,
257
+ d_initial: float = 0.1,
258
+ **kwargs,
259
+ ) -> None:
260
+ super().__init__()
261
+ VeraLayer.__init__(self, base_layer)
262
+ self.fan_in_fan_out = fan_in_fan_out
263
+
264
+ self._active_adapter = adapter_name
265
+ self.update_layer(
266
+ adapter_name,
267
+ vera_A,
268
+ vera_B,
269
+ r,
270
+ vera_dropout=vera_dropout,
271
+ init_weights=init_weights,
272
+ d_initial=d_initial,
273
+ )
274
+
275
+ def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None:
276
+ if self.merged:
277
+ warnings.warn(
278
+ f"Already following adapters were merged {','.join(self.merged_adapters)}. "
279
+ f"You are now additionally merging {','.join(self.active_adapters)}."
280
+ )
281
+
282
+ adapter_names = check_adapters_to_merge(self, adapter_names)
283
+ if not adapter_names:
284
+ return
285
+
286
+ for active_adapter in adapter_names:
287
+ if active_adapter not in self.vera_lambda_d.keys():
288
+ continue
289
+
290
+ warnings.warn(
291
+ "Merge vera module to 4-bit linear may get different generations due to rounding errors."
292
+ )
293
+ vera_data = self.get_delta_weight(active_adapter)
294
+
295
+ weight = self.get_base_layer().weight
296
+ kwargs = weight.__dict__
297
+ # torch.compile can introduce attributes preceded by '_', remove them
298
+ kwargs = {k: v for k, v in kwargs.items() if not k.startswith("_")}
299
+ w_data = bnb.functional.dequantize_4bit(weight.data, weight.quant_state) + vera_data
300
+
301
+ if safe_merge and not torch.isfinite(w_data).all():
302
+ raise ValueError(
303
+ f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken"
304
+ )
305
+
306
+ self.get_base_layer().weight = bnb.nn.Params4bit(w_data.to("cpu"), requires_grad=False, **kwargs).to(
307
+ weight.device
308
+ )
309
+ self.merged_adapters.append(active_adapter)
310
+
311
+ def unmerge(self) -> None:
312
+ if not self.merged:
313
+ warnings.warn("Already unmerged. Nothing to do")
314
+ return
315
+
316
+ while len(self.merged_adapters) > 0:
317
+ active_adapter = self.merged_adapters.pop()
318
+ if active_adapter not in self.vera_lambda_d.keys():
319
+ continue
320
+ warnings.warn(
321
+ "Unmerge vera module to 4-bit linear may get different generations due to rounding errors."
322
+ )
323
+ vera_data = self.get_delta_weight(active_adapter)
324
+
325
+ weight = self.get_base_layer().weight
326
+ kwargs = weight.__dict__
327
+ w_data = bnb.functional.dequantize_4bit(weight.data, weight.quant_state) - vera_data
328
+
329
+ self.get_base_layer().weight = bnb.nn.Params4bit(w_data.to("cpu"), requires_grad=False, **kwargs).to(
330
+ weight.device
331
+ )
332
+
333
+ def get_delta_weight(self, adapter) -> torch.Tensor:
334
+ vera_A = self.vera_A[adapter]
335
+ vera_B = self.vera_B[adapter]
336
+
337
+ device = vera_B.device
338
+ dtype = vera_B.dtype
339
+
340
+ cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16)
341
+
342
+ lambda_d = self.vera_lambda_d[adapter]
343
+ lambda_b = self.vera_lambda_b[adapter]
344
+
345
+ if cast_to_fp32:
346
+ vera_A = vera_A.float()
347
+ vera_B = vera_B.float()
348
+ lambda_d = lambda_d.float()
349
+ lambda_b = lambda_b.float()
350
+
351
+ sliced_A = vera_A[:, : self.in_features].to(lambda_d.device)
352
+ sliced_B = vera_B[: self.out_features, :].to(lambda_d.device)
353
+ lambda_b = lambda_b.unsqueeze(-1)
354
+ lambda_d = lambda_d.unsqueeze(-1)
355
+
356
+ output_tensor = transpose((lambda_b * sliced_B) @ (lambda_d * sliced_A), self.fan_in_fan_out)
357
+
358
+ if cast_to_fp32:
359
+ output_tensor = output_tensor.to(dtype=dtype)
360
+
361
+ return output_tensor
362
+
363
+ def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor:
364
+ if self.disable_adapters:
365
+ if self.merged:
366
+ self.unmerge()
367
+ result = self.base_layer(x, *args, **kwargs)
368
+ elif self.merged:
369
+ result = self.base_layer(x, *args, **kwargs)
370
+ else:
371
+ result = self.base_layer(x, *args, **kwargs)
372
+ result = result.clone()
373
+ for active_adapter in self.active_adapters:
374
+ if active_adapter not in self.vera_lambda_d.keys():
375
+ continue
376
+
377
+ lambda_d = self.vera_lambda_d[active_adapter]
378
+ lambda_b = self.vera_lambda_b[active_adapter]
379
+
380
+ vera_A = self.vera_A[active_adapter]
381
+ vera_B = self.vera_B[active_adapter]
382
+
383
+ dropout = self.vera_dropout[active_adapter]
384
+
385
+ requires_conversion = not torch.is_autocast_enabled()
386
+ if requires_conversion:
387
+ expected_dtype = result.dtype
388
+ compute_dtype = lambda_d.dtype
389
+ if x.dtype != compute_dtype:
390
+ x = x.to(compute_dtype)
391
+
392
+ sliced_A = vera_A[:, : self.in_features].to(x.device)
393
+ sliced_B = vera_B[: self.out_features, :].to(x.device)
394
+
395
+ x_temp = dropout(x.to(lambda_d.dtype))
396
+
397
+ adapter_output = lambda_b * torch.nn.functional.linear(
398
+ lambda_d * torch.nn.functional.linear(x_temp, sliced_A), sliced_B
399
+ )
400
+
401
+ if requires_conversion:
402
+ adapter_output = adapter_output.to(expected_dtype)
403
+
404
+ result = result + adapter_output
405
+
406
+ # Ensure the output tensor has the same dtype as the input tensor
407
+ return result.to(x.dtype)
408
+
409
+ def __repr__(self) -> str:
410
+ rep = super().__repr__()
411
+ return "vera." + rep
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/vera/config.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 dataclasses import dataclass, field
18
+ from typing import Optional, Union
19
+
20
+ from peft.config import PeftConfig
21
+ from peft.utils import PeftType
22
+
23
+
24
+ @dataclass
25
+ class VeraConfig(PeftConfig):
26
+ """
27
+ This is the configuration class to store the configuration of a [`VeraModel`].
28
+
29
+ Paper: https://huggingface.co/papers/2310.11454.
30
+
31
+ Args:
32
+ r (`int`, *optional*, defaults to `256`):
33
+ VeRA parameter dimension ("rank"). Choose higher values than LoRA ranks here, since VeRA uses far fewer
34
+ parameters than LoRA (see Table 1).
35
+ target_modules (`Union[List[str], str]`):
36
+ The names of the modules to apply Vera to. Only linear layers are supported.
37
+ projection_prng_key (`int`):
38
+ Vera PRNG init key. Used for initialising vera_A and vera_B for new models or when loading a checkpoint
39
+ that did not include these projections. Defaults to `0`.
40
+ save_projection (`bool`):
41
+ Whether to save the vera_A / vera_B projections in the state dict alongside per layer lambda_b / lambda_d
42
+ weights. This will increase the size of the checkpoint, but guarantee that we can reload the checkpoint on
43
+ all system configurations. Defaults to `True`.
44
+ vera_dropout (`float`):
45
+ The dropout probability for Vera layers.
46
+ d_initial (`float`, *optional*, defaults to `0.1`):
47
+ Initial init value for `vera_lambda_d` vector used when initializing the VeRA parameters. Small values
48
+ (<=0.1) are recommended (see Table 6c in the paper).
49
+ fan_in_fan_out (`bool`):
50
+ Set this to True if the layer to replace stores weight like (fan_in, fan_out). For example, gpt-2 uses
51
+ `Conv1D` which stores weights like (fan_in, fan_out) and hence this should be set to `True`.
52
+ bias (`str`):
53
+ Bias type for Vera. Can be 'none', 'all' or 'vera_only'. If 'all' or 'vera_only', the corresponding biases
54
+ will be updated during training. Be aware that this means that, even when disabling the adapters, the model
55
+ will not produce the same output as the base model would have without adaptation.
56
+ modules_to_save (`List[str]`):
57
+ List of modules apart from Vera layers to be set as trainable and saved in the final checkpoint.
58
+ init_weights (`bool`):
59
+ Whether to initialize the weights of the Vera layers with their default initialization. Don't change this
60
+ setting, except if you know exactly what you're doing.
61
+ layers_to_transform (`Union[List[int],int]`):
62
+ The layer indexes to transform, if this argument is specified, it will apply the Vera transformations on
63
+ the layer indexes that are specified in this list. If a single integer is passed, it will apply the Vera
64
+ transformations on the layer at this index.
65
+ layers_pattern (`Optional[Union[List[str], str]]`):
66
+ The layer pattern name, used only if `layers_to_transform` is different from `None`. This should target the
67
+ `nn.ModuleList` of the model, which is often called `'layers'` or `'h'`.
68
+ """
69
+
70
+ r: int = field(default=256, metadata={"help": "Vera attention dimension"})
71
+
72
+ target_modules: Optional[Union[list[str], str]] = field(
73
+ default=None,
74
+ metadata={
75
+ "help": (
76
+ "List of module names or regex expression of the module names to replace with Vera."
77
+ "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'. "
78
+ "Only linear layers are supported."
79
+ )
80
+ },
81
+ )
82
+ projection_prng_key: int = field(
83
+ default=0,
84
+ metadata={
85
+ "help": (
86
+ "Vera PRNG init key. Used for initialising vera_A and vera_B for new models or when loading a "
87
+ "checkpoint that did not include these projections."
88
+ )
89
+ },
90
+ )
91
+ save_projection: bool = field(
92
+ default=True,
93
+ metadata={
94
+ "help": (
95
+ "Whether to save the vera_A / vera_B projections in the state dict alongside per layer lambda_b / "
96
+ "lambda_d weights. This will increase the size of the checkpoint, but guarantee that we can reload "
97
+ "the checkpoint on all system configurations."
98
+ )
99
+ },
100
+ )
101
+ vera_dropout: float = field(default=0.0, metadata={"help": "Vera dropout"})
102
+ d_initial: float = field(default=0.1, metadata={"help": "Initial init value for d vector."})
103
+ fan_in_fan_out: bool = field(
104
+ default=False,
105
+ metadata={"help": "Set this to True if the layer to replace stores weight like (fan_in, fan_out)"},
106
+ )
107
+ bias: str = field(default="none", metadata={"help": "Bias type for Vera. Can be 'none', 'all' or 'vera_only'"})
108
+ modules_to_save: Optional[list[str]] = field(
109
+ default=None,
110
+ metadata={
111
+ "help": (
112
+ "List of modules apart from Vera layers to be set as trainable and saved in the final checkpoint. For"
113
+ " example, in Sequence Classification or Token Classification tasks, the final layer"
114
+ " `classifier/score` are randomly initialized and as such need to be trainable and saved."
115
+ )
116
+ },
117
+ )
118
+ init_weights: bool = field(
119
+ default=True,
120
+ metadata={
121
+ "help": (
122
+ "Whether to initialize the weights of the Vera layers with their default initialization. Don't change "
123
+ "this setting, except if you know exactly what you're doing."
124
+ ),
125
+ },
126
+ )
127
+ layers_to_transform: Optional[Union[list[int], int]] = field(
128
+ default=None,
129
+ metadata={
130
+ "help": (
131
+ "The layer indexes to transform, is this argument is specified, PEFT will transform only the layers"
132
+ " indexes that are specified inside this list. If a single integer is passed, PEFT will transform only"
133
+ " the layer at this index."
134
+ )
135
+ },
136
+ )
137
+ layers_pattern: Optional[Union[list[str], str]] = field(
138
+ default=None,
139
+ metadata={
140
+ "help": (
141
+ "The layer pattern name, used only if `layers_to_transform` is different to None and if the layer "
142
+ "pattern is not in the common layers pattern. This should target the `nn.ModuleList` of the "
143
+ "model, which is often called `'layers'` or `'h'`."
144
+ )
145
+ },
146
+ )
147
+
148
+ def __post_init__(self):
149
+ super().__post_init__()
150
+ self.peft_type = PeftType.VERA
151
+ self.target_modules = (
152
+ set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules
153
+ )
154
+ # check for layers_to_transform and layers_pattern
155
+ if self.layers_pattern and not self.layers_to_transform:
156
+ raise ValueError("When `layers_pattern` is specified, `layers_to_transform` must also be specified. ")
157
+ if not self.save_projection:
158
+ warnings.warn(
159
+ "Specified to not save vera_A and vera_B within the state dictionary, instead they will be restored "
160
+ "using the PRNG key store in `config.projection_prng_key`. Consider setting `config.save_projection` "
161
+ "to `True` to guarantee restoring the checkpoint correctly on all system configurations."
162
+ )
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/vera/layer.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 warnings
16
+ from typing import Optional
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+ import torch.nn.functional as F
21
+ from transformers.pytorch_utils import Conv1D
22
+
23
+ from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge
24
+ from peft.utils.other import transpose
25
+
26
+ from .._buffer_dict import BufferDict
27
+
28
+
29
+ class VeraLayer(BaseTunerLayer):
30
+ # List all names of layers that may contain adapter weights
31
+ adapter_layer_names = ("vera_lambda_b", "vera_lambda_d")
32
+ other_param_names = ("vera_A", "vera_B")
33
+
34
+ def __init__(self, base_layer: nn.Module, **kwargs):
35
+ self.base_layer = base_layer
36
+ self.r = {}
37
+ self.vera_dropout = nn.ModuleDict({})
38
+
39
+ # For storing vector scale
40
+ self.vera_lambda_b = nn.ParameterDict({})
41
+ self.vera_lambda_d = nn.ParameterDict({})
42
+
43
+ # Stores a reference to the vera_A/B BufferDict.
44
+ # Set to `None` otherwise to avoid computation with random weights
45
+ self.vera_A: Optional[BufferDict] = None
46
+ self.vera_B: Optional[BufferDict] = None
47
+
48
+ # Mark the weight as unmerged
49
+ self._disable_adapters = False
50
+ self.merged_adapters = []
51
+
52
+ base_layer = self.get_base_layer()
53
+ if isinstance(base_layer, nn.Linear):
54
+ in_features, out_features = base_layer.in_features, base_layer.out_features
55
+ elif isinstance(base_layer, Conv1D):
56
+ in_features, out_features = (
57
+ base_layer.weight.ds_shape if hasattr(base_layer.weight, "ds_shape") else base_layer.weight.shape
58
+ )
59
+
60
+ self.in_features = in_features
61
+ self.out_features = out_features
62
+ self.kwargs = kwargs
63
+
64
+ @property
65
+ def merged(self) -> bool:
66
+ return bool(self.merged_adapters)
67
+
68
+ def update_layer(
69
+ self,
70
+ adapter_name,
71
+ vera_A: BufferDict,
72
+ vera_B: BufferDict,
73
+ r,
74
+ vera_dropout,
75
+ init_weights,
76
+ d_initial: float = 0.1,
77
+ inference_mode: bool = False,
78
+ **kwargs,
79
+ ):
80
+ if r <= 0:
81
+ raise ValueError(f"`r` should be a positive integer value but the value passed is {r}")
82
+ self.r[adapter_name] = r
83
+ if vera_dropout > 0.0:
84
+ vera_dropout_layer = nn.Dropout(p=vera_dropout)
85
+ else:
86
+ vera_dropout_layer = nn.Identity()
87
+
88
+ self.vera_dropout.update(nn.ModuleDict({adapter_name: vera_dropout_layer}))
89
+ # Actual trainable parameters
90
+ self.vera_lambda_b[adapter_name] = nn.Parameter(torch.ones(self.out_features), requires_grad=True)
91
+ self.vera_lambda_d[adapter_name] = nn.Parameter(torch.randn(r), requires_grad=True)
92
+
93
+ # non trainable references to vera_A/B buffers
94
+ self.vera_A = vera_A
95
+ self.vera_B = vera_B
96
+ if adapter_name not in vera_A:
97
+ # This means that this is not the first VeRA adapter. We have to add an entry in the dict for this adapter.
98
+ if len(self.vera_A) < 1:
99
+ raise ValueError(
100
+ "The `vera_A` and `vera_B` buffers are empty. This should not happen. Please report this issue."
101
+ )
102
+ # we can take any of the existing adapter's parameters, as they should all be identical
103
+ vera_A_param = list(self.vera_A.values())[0]
104
+ vera_B_param = list(self.vera_B.values())[0]
105
+
106
+ error_tmpl = (
107
+ "{} has a size of {} but {} or greater is required; this probably happened because an additional VeRA "
108
+ "adapter was added after the first one with incompatible shapes."
109
+ )
110
+ # check input size
111
+ if vera_A_param.shape[1] < self.in_features:
112
+ raise ValueError(error_tmpl.format("vera_A", vera_A_param.shape[1], self.in_features))
113
+ # check output size
114
+ if vera_B_param.shape[0] < self.out_features:
115
+ raise ValueError(error_tmpl.format("vera_B", vera_B_param.shape[0], self.out_features))
116
+ # check r
117
+ error_tmpl = (
118
+ "{} has a size of {} but {} or greater is required; this probably happened because an additional VeRA "
119
+ "adapter with a lower rank was added after the first one; loading the adapters "
120
+ "in reverse order may solve this."
121
+ )
122
+ if vera_A_param.shape[0] < self.r[adapter_name]:
123
+ raise ValueError(error_tmpl.format("vera_A", vera_A_param.shape[0], self.r[adapter_name]))
124
+ if vera_B_param.shape[1] < self.r[adapter_name]:
125
+ raise ValueError(error_tmpl.format("vera_B", vera_B_param.shape[1], self.r[adapter_name]))
126
+
127
+ self.vera_A[adapter_name] = vera_A_param
128
+ self.vera_B[adapter_name] = vera_B_param
129
+
130
+ if init_weights:
131
+ self.reset_vera_parameters(adapter_name, d_initial=d_initial)
132
+
133
+ self._move_adapter_to_device_of_base_layer(adapter_name)
134
+ self.set_adapter(self.active_adapters, inference_mode=inference_mode)
135
+
136
+ def reset_vera_parameters(self, adapter_name, d_initial: float = 0.1):
137
+ if adapter_name in self.vera_lambda_d.keys():
138
+ with torch.no_grad():
139
+ nn.init.zeros_(self.vera_lambda_d[adapter_name]).fill_(d_initial)
140
+ nn.init.zeros_(self.vera_lambda_b[adapter_name])
141
+
142
+
143
+ class Linear(nn.Linear, VeraLayer):
144
+ # Vera implemented in a dense layer
145
+ def __init__(
146
+ self,
147
+ base_layer,
148
+ vera_A: BufferDict,
149
+ vera_B: BufferDict,
150
+ adapter_name: str,
151
+ r: int = 0,
152
+ vera_dropout: float = 0.0,
153
+ fan_in_fan_out: bool = False, # Set this to True if the layer to replace stores weight like (fan_in, fan_out)
154
+ is_target_conv_1d_layer: bool = False,
155
+ init_weights: bool = True,
156
+ d_initial: float = 0.1,
157
+ **kwargs,
158
+ ) -> None:
159
+ # this gets the init from nn.Linear's super perspective, i.e. nn.Module.__init__, which should always be called
160
+ super(nn.Linear, self).__init__()
161
+ VeraLayer.__init__(self, base_layer, **kwargs)
162
+ self.fan_in_fan_out = fan_in_fan_out
163
+
164
+ self._active_adapter = adapter_name
165
+ self.update_layer(adapter_name, vera_A, vera_B, r, vera_dropout, init_weights, d_initial=d_initial)
166
+ self.is_target_conv_1d_layer = is_target_conv_1d_layer
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
+ adapter_names = check_adapters_to_merge(self, adapter_names)
182
+ if not adapter_names:
183
+ # no adapter to merge
184
+ return
185
+
186
+ for active_adapter in adapter_names:
187
+ if active_adapter in self.vera_lambda_d.keys():
188
+ base_layer = self.get_base_layer()
189
+ if safe_merge:
190
+ # Note that safe_merge will be slower than the normal merge
191
+ # because of the copy operation.
192
+ orig_weights = base_layer.weight.data.clone()
193
+
194
+ orig_weights += self.get_delta_weight(active_adapter)
195
+
196
+ if not torch.isfinite(orig_weights).all():
197
+ raise ValueError(
198
+ f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken"
199
+ )
200
+
201
+ base_layer.weight.data = orig_weights
202
+ else:
203
+ base_layer.weight.data += self.get_delta_weight(active_adapter)
204
+ self.merged_adapters.append(active_adapter)
205
+
206
+ def unmerge(self) -> None:
207
+ if not self.merged:
208
+ warnings.warn("Already unmerged. Nothing to do.")
209
+ return
210
+
211
+ while len(self.merged_adapters) > 0:
212
+ active_adapter = self.merged_adapters.pop()
213
+ if active_adapter in self.vera_lambda_d.keys():
214
+ self.get_base_layer().weight.data -= self.get_delta_weight(active_adapter)
215
+
216
+ def get_delta_weight(self, adapter) -> torch.Tensor:
217
+ """
218
+ Compute the delta weight for the given adapter.
219
+
220
+ Args:
221
+ adapter (str):
222
+ The name of the adapter for which the delta weight should be computed.
223
+ """
224
+ vera_A = self.vera_A[adapter]
225
+ vera_B = self.vera_B[adapter]
226
+
227
+ device = vera_B.device
228
+ dtype = vera_B.dtype
229
+
230
+ # In case users wants to merge the adapter weights that are in
231
+ # (b)float16 while being on CPU, we need to cast the weights to float32, perform the merge and then cast back to
232
+ # (b)float16 because some CPUs have slow bf16/fp16 matmuls.
233
+ cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16)
234
+
235
+ lambda_d = self.vera_lambda_d[adapter]
236
+ lambda_b = self.vera_lambda_b[adapter]
237
+
238
+ if cast_to_fp32:
239
+ vera_A = vera_A.float()
240
+ vera_B = vera_B.float()
241
+ lambda_d = lambda_d.float()
242
+ lambda_b = lambda_b.float()
243
+
244
+ sliced_A = vera_A[:, : self.in_features].to(lambda_d.device)
245
+ sliced_B = vera_B[: self.out_features, :].to(lambda_d.device)
246
+ lambda_b = lambda_b.unsqueeze(-1)
247
+ lambda_d = lambda_d.unsqueeze(-1)
248
+ output_tensor = transpose((lambda_b * sliced_B) @ (lambda_d * sliced_A), self.fan_in_fan_out)
249
+
250
+ if cast_to_fp32:
251
+ output_tensor = output_tensor.to(dtype=dtype)
252
+
253
+ return output_tensor
254
+
255
+ def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor:
256
+ previous_dtype = x.dtype
257
+
258
+ if self.disable_adapters:
259
+ if self.merged:
260
+ self.unmerge()
261
+ result = self.base_layer(x, *args, **kwargs)
262
+ elif self.merged:
263
+ result = self.base_layer(x, *args, **kwargs)
264
+ else:
265
+ result = self.base_layer(x, *args, **kwargs)
266
+ for active_adapter in self.active_adapters:
267
+ if active_adapter not in self.vera_lambda_d.keys():
268
+ continue
269
+
270
+ lambda_d = self.vera_lambda_d[active_adapter]
271
+ lambda_b = self.vera_lambda_b[active_adapter]
272
+
273
+ vera_A = self.vera_A[active_adapter]
274
+ vera_B = self.vera_B[active_adapter]
275
+
276
+ # As adapted layers may have different shapes and VeRA contains a single shared pair of A and B matrices,
277
+ # we initialize these matrices with the largest required size for each dimension.
278
+ # During the forward pass, required submatrices are sliced out from the shared vera_A and vera_B.
279
+ sliced_A = vera_A[:, : self.in_features].to(x.device)
280
+ sliced_B = vera_B[: self.out_features, :].to(x.device)
281
+
282
+ dropout = self.vera_dropout[active_adapter]
283
+ x = x.to(lambda_d.dtype)
284
+ result = result + lambda_b * F.linear(lambda_d * F.linear(dropout(x), sliced_A), sliced_B)
285
+
286
+ result = result.to(previous_dtype)
287
+ return result
288
+
289
+ def supports_lora_conversion(self, adapter_name: str = "default") -> bool:
290
+ return True
291
+
292
+ def __repr__(self) -> str:
293
+ rep = super().__repr__()
294
+ return "vera." + rep
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/vera/model.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 math
18
+ import warnings
19
+ from typing import Union
20
+
21
+ import torch
22
+ import torch.nn as nn
23
+ from torch.nn.init import _calculate_correct_fan
24
+ from transformers.pytorch_utils import Conv1D
25
+
26
+ from peft.import_utils import is_bnb_4bit_available, is_bnb_available
27
+ from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer
28
+ from peft.utils import (
29
+ TRANSFORMERS_MODELS_TO_VERA_TARGET_MODULES_MAPPING,
30
+ )
31
+
32
+ from .._buffer_dict import BufferDict
33
+ from ..tuners_utils import _maybe_include_all_linear_layers
34
+ from .config import VeraConfig
35
+ from .layer import Linear, VeraLayer
36
+
37
+
38
+ def _kaiming_init(
39
+ tensor_or_shape: Union[torch.Tensor, tuple[int, ...]],
40
+ generator: torch.Generator,
41
+ ) -> torch.Tensor:
42
+ """
43
+ Kaiming Uniform Initialisation adapted to accept a `torch.Generator` object for PRNG.
44
+
45
+ Args:
46
+ tensor_or_shape (`Union[torch.Tensor, tuple[int, ...]]`):
47
+ Tensor to initialise, or shape of new tensor to create and then initialise.
48
+ generator: (`torch.Generator`):
49
+ Generator object that manages the state of the PRNG algorithm in use.
50
+
51
+ Returns:
52
+ `torch.Tensor`: The initialised tensor.
53
+ """
54
+ if isinstance(tensor_or_shape, tuple):
55
+ tensor = torch.empty(tensor_or_shape)
56
+ else:
57
+ tensor = tensor_or_shape
58
+ fan = _calculate_correct_fan(tensor, "fan_in")
59
+ gain = math.sqrt(2)
60
+ std = gain / math.sqrt(fan)
61
+ bound = math.sqrt(3.0) * std
62
+
63
+ with torch.no_grad():
64
+ return tensor.uniform_(-bound, bound, generator=generator)
65
+
66
+
67
+ class VeraModel(BaseTuner):
68
+ """
69
+ Creates Vector-based Random Matrix Adaptation (Vera) model from a pretrained transformers model.
70
+
71
+ Args:
72
+ model ([`~transformers.PreTrainedModel`]): The model to be adapted.
73
+ config ([`VeraConfig`]): The configuration of the Vera model.
74
+ adapter_name (`str`): The name of the adapter, defaults to `"default"`.
75
+ low_cpu_mem_usage (`bool`, `optional`, defaults to `False`):
76
+ Create empty adapter weights on meta device. Useful to speed up the loading process.
77
+
78
+ Returns:
79
+ `torch.nn.Module`: The Vera model.
80
+
81
+ Example:
82
+
83
+ ```py
84
+ >>> from transformers import AutoModelForCausalLM
85
+ >>> from peft import VeraConfig, get_peft_model
86
+
87
+ >>> base_model = AutoModelForCausalLM.from_pretrained("facebook/opt-125m")
88
+ >>> config = VeraConfig(r=128)
89
+ >>> model = get_peft_model(base_model, config)
90
+ ```
91
+
92
+ **Attributes**:
93
+ - **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted.
94
+ - **peft_config** ([`VeraConfig`]): The configuration of the Vera model.
95
+ """
96
+
97
+ prefix: str = "vera_lambda_"
98
+ tuner_layer_cls = VeraLayer
99
+ target_module_mapping = TRANSFORMERS_MODELS_TO_VERA_TARGET_MODULES_MAPPING
100
+
101
+ def _find_dim(self, config) -> tuple[int, int]:
102
+ """
103
+ Finds the largest input and output dimensions across linear layers that have been wrapped with VeRA.
104
+
105
+ This will be used for determining the size of the shared vera_A and vera_B matrices.
106
+ """
107
+ model_config = self.get_model_config(self.model)
108
+
109
+ peft_config = self._prepare_adapter_config(config, model_config)
110
+ peft_config = _maybe_include_all_linear_layers(peft_config, self.model)
111
+
112
+ largest_shape = None
113
+ for key, module in self.model.named_modules():
114
+ if not self._check_target_module_exists(peft_config, key):
115
+ continue
116
+
117
+ if isinstance(module, nn.Linear):
118
+ module_shape = module.out_features, module.in_features
119
+ elif isinstance(module, Conv1D):
120
+ module_shape = module.weight.ds_shape if hasattr(module.weight, "ds_shape") else module.weight.shape
121
+ module_shape = module_shape[::-1]
122
+ else:
123
+ continue
124
+
125
+ if largest_shape is None:
126
+ largest_shape = module_shape
127
+ continue
128
+
129
+ if module_shape != largest_shape:
130
+ largest_shape = tuple(max(a, b) for a, b in zip(largest_shape, module_shape))
131
+
132
+ if largest_shape is None:
133
+ msg = "No layers types compatible with VeRA were found. Please check `peft_config.target_modules`."
134
+ raise ValueError(msg)
135
+
136
+ return largest_shape
137
+
138
+ def _init_vera_A_vera_B(self, config: VeraConfig, adapter_name: str) -> None:
139
+ linear_out_dim, linear_in_dim = self._find_dim(config)
140
+
141
+ # use of persistent to exclude vera_A and vera_B from the state dict if we choose not to save them.
142
+ self.vera_A = BufferDict({}, persistent=config.save_projection)
143
+ self.vera_B = BufferDict({}, persistent=config.save_projection)
144
+
145
+ # deterministic init of vera_A and vera_B if we know the key
146
+ generator = torch.Generator(device="cpu").manual_seed(config.projection_prng_key)
147
+ vera_A = _kaiming_init((config.r, linear_in_dim), generator=generator)
148
+ vera_B = _kaiming_init((linear_out_dim, config.r), generator=generator)
149
+
150
+ self.vera_A[adapter_name] = vera_A
151
+ self.vera_B[adapter_name] = vera_B
152
+
153
+ def _pre_injection_hook(self, model: nn.Module, config: VeraConfig, adapter_name: str) -> None:
154
+ self._init_vera_A_vera_B(config, adapter_name)
155
+
156
+ def _check_new_adapter_config(self, config: VeraConfig) -> None:
157
+ """
158
+ A helper method to check the config when a new adapter is being added.
159
+
160
+ Raise a ValueError if there is something wrong with the config or if it conflicts with existing adapters.
161
+
162
+ """
163
+ super()._check_new_adapter_config(config)
164
+
165
+ for existing_config in self.peft_config.values():
166
+ if existing_config is config:
167
+ # skip the current config
168
+ continue
169
+
170
+ if existing_config.projection_prng_key != config.projection_prng_key:
171
+ raise ValueError(
172
+ f"Vera PRNG initialisation key must be the same for all adapters. Got {config.projection_prng_key=} but "
173
+ f"previous config had {existing_config.projection_prng_key}."
174
+ )
175
+
176
+ save_project_unique_values = sorted({config.save_projection for config in self.peft_config.values()})
177
+ if len(save_project_unique_values) > 1:
178
+ raise ValueError(
179
+ "VeRA projection weights must be saved for all adapters or none, but got multiple different values: "
180
+ f"{save_project_unique_values}"
181
+ )
182
+
183
+ def _create_and_replace(
184
+ self,
185
+ vera_config,
186
+ adapter_name,
187
+ target,
188
+ target_name,
189
+ parent,
190
+ current_key,
191
+ **optional_kwargs,
192
+ ):
193
+ if current_key is None:
194
+ raise ValueError("Current Key shouldn't be `None`")
195
+
196
+ r = vera_config.r
197
+ bias = hasattr(target, "bias") and target.bias is not None
198
+ kwargs = {
199
+ "r": r,
200
+ "vera_dropout": vera_config.vera_dropout,
201
+ "fan_in_fan_out": vera_config.fan_in_fan_out,
202
+ "init_weights": vera_config.init_weights,
203
+ "loaded_in_8bit": getattr(self.model, "is_loaded_in_8bit", False),
204
+ "loaded_in_4bit": getattr(self.model, "is_loaded_in_4bit", False),
205
+ }
206
+ kwargs["bias"] = bias
207
+
208
+ if isinstance(target, Linear):
209
+ target.update_layer(
210
+ adapter_name,
211
+ self.vera_A,
212
+ self.vera_B,
213
+ r,
214
+ vera_config.vera_dropout,
215
+ vera_config.init_weights,
216
+ d_initial=vera_config.d_initial,
217
+ )
218
+ else:
219
+ new_module = self._create_new_module(vera_config, self.vera_A, self.vera_B, adapter_name, target, **kwargs)
220
+ if adapter_name not in self.active_adapter:
221
+ # adding an additional adapter: it is not automatically trainable
222
+ new_module.requires_grad_(False)
223
+ self._replace_module(parent, target_name, new_module, target)
224
+
225
+ @staticmethod
226
+ def _create_new_module(vera_config, vera_A, vera_B, adapter_name, target, **kwargs):
227
+ # avoid eager bnb import
228
+ if is_bnb_available():
229
+ import bitsandbytes as bnb
230
+
231
+ from .bnb import Linear8bitLt
232
+
233
+ if is_bnb_4bit_available():
234
+ from .bnb import Linear4bit
235
+
236
+ bias = kwargs.pop("bias", False)
237
+ loaded_in_8bit = kwargs.get("loaded_in_8bit", False)
238
+ loaded_in_4bit = kwargs.get("loaded_in_4bit", False)
239
+
240
+ if isinstance(target, BaseTunerLayer):
241
+ target_base_layer = target.get_base_layer()
242
+ else:
243
+ target_base_layer = target
244
+
245
+ if loaded_in_8bit and isinstance(target_base_layer, bnb.nn.Linear8bitLt):
246
+ eightbit_kwargs = kwargs.copy()
247
+ eightbit_kwargs.update(
248
+ {
249
+ "has_fp16_weights": target_base_layer.state.has_fp16_weights,
250
+ "threshold": target_base_layer.state.threshold,
251
+ "index": target_base_layer.index,
252
+ }
253
+ )
254
+ return Linear8bitLt(target, adapter_name, vera_A, vera_B, **eightbit_kwargs)
255
+ elif loaded_in_4bit and isinstance(target_base_layer, bnb.nn.Linear4bit):
256
+ fourbit_kwargs = kwargs.copy()
257
+ fourbit_kwargs.update(
258
+ {
259
+ "compute_dtype": target_base_layer.compute_dtype,
260
+ "compress_statistics": target_base_layer.weight.compress_statistics,
261
+ "quant_type": target_base_layer.weight.quant_type,
262
+ }
263
+ )
264
+ return Linear4bit(target, adapter_name, vera_A, vera_B, **fourbit_kwargs)
265
+ elif isinstance(target_base_layer, torch.nn.Linear):
266
+ if kwargs["fan_in_fan_out"]:
267
+ warnings.warn(
268
+ "fan_in_fan_out is set to True but the target module is `torch.nn.Linear`. "
269
+ "Setting fan_in_fan_out to False."
270
+ )
271
+ kwargs["fan_in_fan_out"] = vera_config.fan_in_fan_out = False
272
+ elif isinstance(target_base_layer, Conv1D):
273
+ kwargs["is_target_conv_1d_layer"] = True
274
+ if not kwargs["fan_in_fan_out"]:
275
+ warnings.warn(
276
+ "fan_in_fan_out is set to False but the target module is `Conv1D`. Setting fan_in_fan_out to True."
277
+ )
278
+ kwargs["fan_in_fan_out"] = vera_config.fan_in_fan_out = True
279
+ else:
280
+ raise ValueError(
281
+ f"Target module {target} is not supported. Currently, only the following modules are supported: "
282
+ "`torch.nn.Linear`, `transformers.pytorch_utils.Conv1D`."
283
+ )
284
+ new_module = Linear(
285
+ target,
286
+ vera_A,
287
+ vera_B,
288
+ adapter_name,
289
+ bias=bias,
290
+ d_initial=vera_config.d_initial,
291
+ **kwargs,
292
+ )
293
+
294
+ return new_module
tasks/tasksmith-9aea936e30e4/tests/source/src/peft/tuners/waveft/__init__.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 peft.utils import register_peft_method
16
+
17
+ from .config import WaveFTConfig
18
+ from .layer import WaveFTLayer, WaveFTLinear
19
+ from .model import WaveFTModel
20
+
21
+
22
+ __all__ = ["WaveFTConfig", "WaveFTLayer", "WaveFTLinear", "WaveFTModel"]
23
+
24
+ register_peft_method(name="waveft", model_cls=WaveFTModel, config_cls=WaveFTConfig)