diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec56fc827c71d69f1374a919e94c0758e21889fd Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/__pycache__/_buffer_dict.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/__pycache__/_buffer_dict.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bcb90d7f911e4550110044eb5a97458c7b2df9a4 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/__pycache__/_buffer_dict.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/__pycache__/lycoris_utils.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/__pycache__/lycoris_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f9286a50d900d6d0351840a2d358b69a99e9ff4a Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/__pycache__/lycoris_utils.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/__pycache__/tuners_utils.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/__pycache__/tuners_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d7cb6bd84098723b876d65c3636c9be962000369 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/__pycache__/tuners_utils.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/aqlm.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/aqlm.py new file mode 100644 index 0000000000000000000000000000000000000000..fd7dec3991db18c5845a9b14151f70b79aa79a2b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/aqlm.py @@ -0,0 +1,109 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Any, Optional + +import torch + +from peft.import_utils import is_aqlm_available +from peft.tuners.lora.layer import LoraLayer +from peft.tuners.tuners_utils import BaseTunerLayer + +from .config import LoraConfig + + +if is_aqlm_available(): + from aqlm import QuantizedLinear + + +class AqlmLoraLinear(torch.nn.Module, LoraLayer): + def __init__( + self, + base_layer, + adapter_name: str, + config: LoraConfig, + r: int = 0, + lora_alpha: int = 1, + **kwargs, + ): + if config.use_dora: + raise ValueError(f"{self.__class__.__name__} does not support DoRA yet, please set it to False") + + super().__init__() + LoraLayer.__init__(self, base_layer) + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + r, + lora_alpha=lora_alpha, + config=config, + ) + + def forward(self, x: torch.Tensor): + # note: logic differs from default Linear because merging is not supported + result = self.base_layer(x) + + if self.disable_adapters: + return result + + for active_adapter in self.active_adapters: + if active_adapter not in self.lora_A.keys(): + continue + lora_A = self.lora_A[active_adapter] + lora_B = self.lora_B[active_adapter] + dropout = self.lora_dropout[active_adapter] + scaling = self.scaling[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + x = self._cast_input_dtype(x, lora_A.weight.dtype) + + output = lora_B(lora_A(dropout(x))) + if requires_conversion: + output = output.to(expected_dtype) + output = output * scaling + result += output + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "lora." + rep + + # TODO: Check if it is better as suggested by users https://github.com/PanQiWei/AutoGPTQ/pull/102 + # def reset_lora_parameters(self, adapter_name): + # if adapter_name in self.lora_A.keys(): + # torch.nn.init.xavier_uniform_(self.lora_A[adapter_name].weight) + # torch.nn.init.zeros_(self.lora_B[adapter_name].weight) + + +def dispatch_aqlm( + target: torch.nn.Module, + adapter_name: str, + config: LoraConfig, + **kwargs: Any, +) -> Optional[torch.nn.Module]: + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if is_aqlm_available() and isinstance(target_base_layer, QuantizedLinear): + new_module = AqlmLoraLinear(target, adapter_name, config=config, **kwargs) + target.qweight = target_base_layer.codes + + return new_module diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/arrow.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/arrow.py new file mode 100644 index 0000000000000000000000000000000000000000..8a6e7056eb3c08c863b31ce39b58ebc60e5d8e24 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/arrow.py @@ -0,0 +1,476 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import os +from typing import Any + +import torch +from torch import nn +from transformers import PreTrainedModel + +from .config import ArrowConfig + + +TASK_ADAPTER_PREFIX = "task_" +GKS_ADAPTER_PREFIX = "gks_" + + +class ArrowLoraLinearLayer(nn.Module): + """ + This class represent the main logic of the arrow routing algorithm for linear layers. + """ + + def __init__(self, in_features, arrow_config): + super().__init__() + # extra parameters needed for arrow + self.in_features = in_features + self._protos_ready = False + self.top_k = arrow_config.top_k + self.temperature = arrow_config.router_temperature + self.rng_seed = arrow_config.rng_seed + self.task_adapter_names = ( + arrow_config.task_adapter_names.copy() + ) # Set in create_arrow_model() with this format: task_0, task_1, ... + self.gks_adapter_names = ( + arrow_config.gks_adapter_names + ) # Set in create_arrow_model() with this format: gks_0, gks_1, ... + self.use_gks = arrow_config.use_gks + self.gks_done = False + self.gks_added_adapter_names = [] + self.in_features = in_features + self.cast_input_dtype_enabled = True + + @torch.no_grad() + def on_adapter_change(self, lora_A, lora_B): + """ + Called when adapters are added/removed/renamed so Arrow can refresh its internal state before the next forward + pass. + """ + all_ts_adapter_names = [ + k + for k in lora_A.keys() + if k in lora_B and k != "arrow_router" and not (k.startswith("gks_") and k[len("gks_") :].isdigit()) + ] + + if sorted(self.task_adapter_names) == sorted(all_ts_adapter_names): # No changes in the ts_adapters + return + + # Getting the name(s) of added adapter(s) + if len(self.task_adapter_names) < len(all_ts_adapter_names): # Adapter(s) are added. + self.gks_added_adapter_names = [x for x in all_ts_adapter_names if x not in self.task_adapter_names] + + # Updating the task_adapter_names + self.task_adapter_names = all_ts_adapter_names.copy() + # Invalidate caches so they’ll be rebuilt lazily on next forward() + self._protos_ready = False + # GKS will be handled by self.gks_added_adapter_names + + def top_right_singular_vec_from_BA(self, A, B, iters=15, eps=1e-8): + """ + Computes the top *right* singular vector of ΔW = B @ A without forming ΔW. + + Theory: + For any matrix M, the right singular vectors are the eigenvectors of Mᵀ M. If ΔW = B @ A (with A ∈ + ℝ^{r×in}, B ∈ ℝ^{out×r}), then + ΔWᵀ ΔW = (B @ A)ᵀ (B @ A) = Aᵀ (Bᵀ B) A ∈ ℝ^{in×in}. + Therefore, the dominant right singular vector of ΔW is the dominant eigenvector of M := Aᵀ (Bᵀ B) A. We + find it by *power iteration* on the linear operator + v ↦ Aᵀ (Bᵀ B) (A v), + which avoids materializing ΔW (out×in) or M (in×in). The result lives in the input/token space (size = + in_features), which is exactly what Arrow needs. (Right singular vectors ≡ eigenvectors of MᵀM; power + iteration converges to the dominant eigenvector under mild conditions.) + =============================== Practical notes: + - We perform all iteration in float32 for numerical stability, then cast back + to the LoRA dtype/device before storing/using the prototype. + - Convergence is checked with a simple fixed-iter cap (`iters`) and/or + `allclose` tolerance (`tol`). + - The returned vector is unique up to sign (±), as with any singular vector. + Downstream code should be sign-invariant. + """ + + # A: (r, in), B: (out, r) + A32 = A.to(torch.float32) + B32 = B.to(torch.float32) + C = B32.T @ B32 # (r, r) + + # Private RNG on A's device + gen = None + if self.rng_seed is not None: + gen = torch.Generator(device=A32.device.type) + gen.manual_seed(int(self.rng_seed)) + + # init vector in input space + v = torch.randn(A32.size(1), dtype=A32.dtype, device=A32.device, generator=gen) + v = v / (v.norm() + eps) + + for _ in range(iters): + # w = (ΔWᵀΔW) v = Aᵀ (BᵀB) (A v) + w = A32.T @ (C @ (A32 @ v)) + v = w / (w.norm() + eps) + + return v # fp32 + + @torch.no_grad() + def build_prototypes(self, lora_A, lora_B): + """ + Computes a prototype vector for each LoRA module in every layer by applying Singular Value Decomposition (SVD) + to the `lora_A` matrix and extracting the top right singular vector. + + These prototypes are later used to calculate the cosine similarity between each input token and each expert. + The resulting similarity scores serve as coefficients to compute a weighted average of the corresponding LoRA + modules, effectively routing each token through its most relevant experts. + + ** This prototype computation is done is done once for all experts and is re-done on newly added adapters.** + + Args: + lora_A : Matrices A in LoRA layer. + lora_B (optional): Matrices B in LoRA layer. Defaults to None. + """ + + if self._protos_ready: + return + protos = [] + for name in self.task_adapter_names: + A = lora_A[name].weight # (r, in_features) + B = lora_B[name].weight # (out_features, r) + + # Efficiently computing right singular vector of A @ B + proto32 = self.top_right_singular_vec_from_BA(A, B) + + proto = proto32.to(dtype=A.dtype, device=A.device) + protos.append(proto) + + proto_stack = torch.stack(protos, dim=0) # (E, in_features) + + # Register the prototypes buffer with correct dtype/device consistent with A and B weights + self.register_buffer("prototypes", proto_stack, persistent=False) + self._protos_ready = True + + @torch.no_grad() + def gen_know_sub(self, lora_A, lora_B): + """ + This function performs General Knowledge Subtraction. It takes an average of provided general_adapters, and + subtract it from each task_adapter. This subtraction tries to purify the task adapters, based on + "forgetting-via-negation" principle. Forgetting-via-negation is a task-arithmetic operation, explained in: + https://huggingface.co/papers/2212.04089 The task adapters will be more focused and isolated, enhancing the + performance on new tasks. + + Args: + lora_A : Matrices A in LoRA layer. + lora_B : Matrices A in LoRA layer. + """ + if not self.use_gks: + return + elif self.gks_done and not self.gks_added_adapter_names: + return + else: + # 1) compute average A/B over gks_adapter_names + avg_A = torch.stack([lora_A[n].weight for n in self.gks_adapter_names], dim=0).mean( + 0 + ) # shape (r, in_features) + avg_B = torch.stack([lora_B[n].weight for n in self.gks_adapter_names], dim=0).mean( + 0 + ) # shape (out_features, r) + + # 2) Subtract the average from task-specific experts + if self.gks_done is False: # GKS is done for all the experts, since it hasn't been done yet. + for name in self.task_adapter_names: + lora_A[name].weight.data.sub_(avg_A) + lora_B[name].weight.data.sub_(avg_B) + else: # GKS is only done on new added experts, since GKS has been done previously. + for name in self.gks_added_adapter_names: + lora_A[name].weight.data.sub_(avg_A) + lora_B[name].weight.data.sub_(avg_B) + + # 3) Set gks_done flag as true, so we won't do it again in ArrowLinearVariant.forward(). + self.gks_done = True + # Clearing the self.gks_added_adapter_names + self.gks_added_adapter_names = [] + + def _cast_input_dtype(self, x, dtype: torch.dtype): + """ + Whether to cast the dtype of the input of the forward method. + + Usually, we want to enable this to align the input dtype with the dtype of the weight, but by setting + layer.cast_input_dtype=False, this can be disabled if necessary. + + Enabling or disabling can be managed via the peft.helpers.disable_lora_input_dtype_casting context manager. + """ + if x is None: # useful e.g. if x is the bias, which can be None + return None + + cast_input_dtype_enabled = getattr(self, "cast_input_dtype_enabled", True) + if (not cast_input_dtype_enabled) or (x.dtype == dtype): + return x + return x.to(dtype=dtype) + + def forward(self, x, lora_A, lora_B, dropout, scaling): + """ + Applies Arrow routing inside a LoRA layer. + + Steps: + 1. Compute cosine similarity between each token representation and all adapter prototypes. + 2. Select the top-k experts per token and normalize their scores with a softmax. + 3. Project tokens into each selected expert’s low-rank space (A weights). + 4. Map back to the output space (B weights). + 5. Aggregate expert outputs via the weighted sum of their contributions. + 6. Apply dropout, scaling, and return the reshaped delta. + + - Conceptually, this is a Mixture-of-Experts (MoE) over LoRA adapters, + where coefficients are derived from prototype similarity. + + Returns: + delta: LoRA output adjustment computed by Arrow routing. + """ + x = self._cast_input_dtype(x, lora_A[self.task_adapter_names[0]].weight.dtype) + B, *rest, F_in = x.shape + tok = x.view(-1, F_in) # (t, F_in) + t, E = tok.size(0), self.prototypes.size(0) + + # We now turn scaling, which is a dict, to tensors in order to use them later + scales_tens = torch.tensor( + [scaling[n] for n in self.task_adapter_names], + device=tok.device, + dtype=tok.dtype, + ) # shape (E,) + + # 1) similarity — sign-agnostic + sim = torch.abs(tok @ self.prototypes.T) # (t, E) + + # 2) top-k + softmax over full E (non-top-k = -inf) + top_v, idx = torch.topk(sim, self.top_k, dim=1) + full_score = tok.new_full((t, E), float("-inf")) + full_score.scatter_(1, idx, top_v) + coeff = torch.softmax(full_score / self.temperature, dim=1) # (t, E) + + # 3) stack all A and B weights once + # A_stack: (E, r, in_features), B_stack: (E, out_features, r) + A_stack = torch.stack([lora_A[n].weight for n in self.task_adapter_names], dim=0) + B_stack = torch.stack([lora_B[n].weight for n in self.task_adapter_names], dim=0) + + # 4) project tokens into each expert’s low‑rank space: + # z[e] = tok @ A_e.T → shape (t, E, r) + z = torch.einsum("tf, erf -> ter", tok, A_stack) + + # 5) lift back each expert’s output: + # y[e] = z[e] @ B_e.T → shape (t, E, out_features) + y = torch.einsum("ter, eor -> teo", z, B_stack) + + # 6) apply per-expert scaling before the weighted sum + # y_scaled[t, e, o] = scales[e] * y[t, e, o] + y = y * scales_tens.view(1, -1, 1) + + # 6) weighted sum over experts: + # delta_flat[t,o] = Σ_e coeff[t,e] * y[t,e,o] + delta_flat = torch.einsum("te, teo -> to", coeff, y) # (t, out_features) + + # 7) dropout, scale, and reshape + delta = dropout(delta_flat) + out_dim = delta_flat.size(-1) + return delta.view(B, *rest, out_dim) + + +def check_loaded_lora_compatibility_arrow(model, adapter_names: list[str]): + """ + After loading all adapters into `model`, check they share: + - the same LoRA rank (r) + - identical weight shapes + - identical sets of target_modules + Returns (sorted list of target module names, agreed rank r). + """ + reference = None # {'r':…, 'shapes':(Ashape,Bshape), 'modules':set([...])} + + for name in adapter_names: + curr_modules = set() + curr_r = None + curr_shapes = None + + for full_name, module in model.named_modules(): + if hasattr(module, "lora_A") and name in module.lora_A: + A = module.lora_A[name].weight + B = module.lora_B[name].weight + mod_name = full_name.split(".")[-1] + curr_modules.add(mod_name) + # A has shape (r, in_features); B has shape (out_features, r) + curr_r = A.shape[0] + curr_shapes = (A.shape, B.shape) + + if reference is None: + reference = {"r": curr_r, "shapes": curr_shapes, "modules": curr_modules} + else: + if curr_r != reference["r"]: + raise ValueError(f"[{name}] rank mismatch: {curr_r} != {reference['r']}") + if curr_shapes != reference["shapes"]: + raise ValueError(f"[{name}] shape mismatch: {curr_shapes} != {reference['shapes']}") + if curr_modules != reference["modules"]: + raise ValueError( + f"[{name}] target_modules mismatch:\n" + f" this adapter -> {sorted(curr_modules)}\n" + f" reference -> {sorted(reference['modules'])}" + ) + + agreed_modules = sorted(reference["modules"]) + return agreed_modules, int(reference["r"]) + + +def ensure_adapters_target_linear_layers_only(model, adapter_names: list[str]): + """ + Validate that every module holding LoRA weights for any of `adapter_names` is Linear-like: nn.Linear, + bitsandbytes.nn.Linear4bit, nn.Conv1d, or transformers.models.gpt2.modeling_gpt2.Conv1D. If not, raise. + """ + import torch.nn as nn + + Linear4bit = None + try: + import bitsandbytes as bnb # type: ignore + + Linear4bit = bnb.nn.Linear4bit + except ImportError: + pass + + HFConv1D = None + try: + from transformers.models.gpt2.modeling_gpt2 import Conv1D as HFConv1D # type: ignore + except ImportError: + pass + + allowed_types = (nn.Linear, nn.Conv1d) + if Linear4bit is not None: + allowed_types = allowed_types + (Linear4bit,) + if HFConv1D is not None: + allowed_types = allowed_types + (HFConv1D,) + + offenders = [] + + for full_name, module in model.named_modules(): + if hasattr(module, "lora_A"): + for name in adapter_names: + if name in getattr(module, "lora_A", {}): + base = getattr(module, "base_layer", None) or getattr(module, "original_module", None) + layer_to_check = base if base is not None else module + + if not isinstance(layer_to_check, allowed_types): + offenders.append((name, full_name, type(layer_to_check).__name__)) + + if offenders: + lines = [ + "LoRA adapters must only target Linear-like layers " + "(nn.Linear, nn.Conv1d, HF Conv1D, or bitsandbytes.nn.Linear4bit). Found:" + ] + for name, full_name, tname in offenders: + lines.append(f" - adapter '{name}' on module '{full_name}' of type {tname}") + raise TypeError("\n".join(lines)) + + +def _resolve_adapter_source(path: str) -> tuple[str, str | None]: + """ + Resolve a user-provided adapter `path` into (model_id, subfolder). + + Supports: + - Local path to a folder that contains `adapter_config.json` + - Hub path with subfolder, e.g. "user/repo/ts_expert_0[/more/...]", which becomes: + model_id="user/repo", subfolder="ts_expert_0[/more/...]" + - Plain Hub repo id "user/repo" (no subfolder) + """ + if os.path.isdir(path): + if not os.path.isfile(os.path.join(path, "adapter_config.json")): + raise ValueError(f"Local adapter path '{path}' does not contain 'adapter_config.json'.") + return path, None + + parts = path.strip("/").split("/") + if len(parts) >= 2: + model_id = "/".join(parts[:2]) + if len(parts) > 2: + subfolder = "/".join(parts[2:]) + return model_id, subfolder + return model_id, None + + return path, None + + +def create_arrow_model( + base_model: PreTrainedModel, + task_specific_adapter_paths: list[str], + arrow_config: ArrowConfig, + general_adapter_paths: list[str] | None = None, + **adapter_kwargs: Any, +): + if task_specific_adapter_paths is None or len(task_specific_adapter_paths) == 0: + raise ValueError("`task_specific_adapter_paths` should contain at least one adapter path") + + from peft import LoraConfig, PeftModel + + model_id0, sub0 = _resolve_adapter_source(task_specific_adapter_paths[0]) + initial_ts_expert_name = f"{TASK_ADAPTER_PREFIX}0" + + first_kwargs = dict(adapter_kwargs) + if sub0 is not None and "subfolder" not in first_kwargs: + first_kwargs["subfolder"] = sub0 + + model = PeftModel.from_pretrained( + base_model, + model_id=model_id0, + adapter_name=initial_ts_expert_name, + **first_kwargs, + ) + + for i in range(1, len(task_specific_adapter_paths)): + ts_expert_name = f"{TASK_ADAPTER_PREFIX}{i}" + mid, sub = _resolve_adapter_source(task_specific_adapter_paths[i]) + more_kwargs = dict(adapter_kwargs) + if sub is not None and "subfolder" not in more_kwargs: + more_kwargs["subfolder"] = sub + model.load_adapter( + model_id=mid, + adapter_name=ts_expert_name, + **more_kwargs, + ) + arrow_config.task_adapter_names = [f"{TASK_ADAPTER_PREFIX}{i}" for i in range(len(task_specific_adapter_paths))] + + if arrow_config.use_gks: + if general_adapter_paths is None or len(general_adapter_paths) == 0: + raise ValueError("You should provide general LoRA paths if you want to use GenKnowSub.") + for i in range(len(general_adapter_paths)): + gen_expert_name = f"{GKS_ADAPTER_PREFIX}{i}" + mid, sub = _resolve_adapter_source(general_adapter_paths[i]) + gks_kwargs = dict(adapter_kwargs) + if sub is not None and "subfolder" not in gks_kwargs: + gks_kwargs["subfolder"] = sub + model.load_adapter( + model_id=mid, + adapter_name=gen_expert_name, + **gks_kwargs, + ) + arrow_config.gks_adapter_names = [f"{GKS_ADAPTER_PREFIX}{i}" for i in range(len(general_adapter_paths))] + else: + arrow_config.gks_adapter_names = [] + + target_modules, r = check_loaded_lora_compatibility_arrow( + model, adapter_names=arrow_config.task_adapter_names + arrow_config.gks_adapter_names + ) + + ensure_adapters_target_linear_layers_only( + model, adapter_names=arrow_config.task_adapter_names + arrow_config.gks_adapter_names + ) + + router_cfg = LoraConfig( + arrow_config=arrow_config, + target_modules=target_modules, + r=r, + ) + model.add_adapter(adapter_name="arrow_router", peft_config=router_cfg) + model.set_adapter("arrow_router") + + return model diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/awq.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/awq.py new file mode 100644 index 0000000000000000000000000000000000000000..3311bba9358aecc72561c8c44f0493a0cd59688b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/awq.py @@ -0,0 +1,104 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Any, Optional + +import torch + +from peft.import_utils import is_gptqmodel_available +from peft.tuners.lora.layer import LoraLayer +from peft.tuners.tuners_utils import BaseTunerLayer + +from .config import LoraConfig + + +class AwqLoraLinear(torch.nn.Module, LoraLayer): + def __init__( + self, + base_layer, + adapter_name, + config: LoraConfig, + r: int = 0, + lora_alpha: int = 1, + **kwargs, + ): + if config.use_dora: + raise ValueError(f"{self.__class__.__name__} does not support DoRA yet, please set it to False") + + super().__init__() + LoraLayer.__init__(self, base_layer) + + # self.base_layer and self.quant_linear_module are the same; we need the former for consistency and the latter + # for backwards compatibility + self.quant_linear_module = base_layer + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + r, + lora_alpha=lora_alpha, + config=config, + ) + + def forward(self, x: torch.Tensor): + result = self.quant_linear_module(x) + + if self.disable_adapters: + return result + + for active_adapter in self.active_adapters: + if active_adapter not in self.lora_A.keys(): + continue + lora_A = self.lora_A[active_adapter] + lora_B = self.lora_B[active_adapter] + dropout = self.lora_dropout[active_adapter] + scaling = self.scaling[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + x = self._cast_input_dtype(x, lora_A.weight.dtype) + + output = lora_B(lora_A(dropout(x))) + if requires_conversion: + output = output.to(expected_dtype) + output = output * scaling + result = result + output + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "lora." + rep + + +def dispatch_awq( + target: torch.nn.Module, + adapter_name: str, + config: LoraConfig, + **kwargs: Any, +) -> Optional[torch.nn.Module]: + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if is_gptqmodel_available(): + from gptqmodel.nn_modules.qlinear.gemm_awq import AwqGEMMQuantLinear + + if isinstance(target_base_layer, AwqGEMMQuantLinear): + new_module = AwqLoraLinear(target, adapter_name, config=config, **kwargs) + target.qweight = target_base_layer.qweight + + return new_module diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/bnb.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/bnb.py new file mode 100644 index 0000000000000000000000000000000000000000..c6f4e769584fcee809ad5e44afb7217897165c82 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/bnb.py @@ -0,0 +1,587 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import warnings +from typing import Any, Optional + +import bitsandbytes as bnb +import torch + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge +from peft.utils.integrations import dequantize_bnb_weight +from peft.utils.other import transpose + +from .config import LoraConfig +from .layer import LoraLayer, LoraVariant + + +VARIANT_KWARG_KEYS = ["alora_offsets"] + +if is_bnb_available(): + + class Linear8bitLt(torch.nn.Module, LoraLayer): + # Lora implemented in a dense layer + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + config: LoraConfig, + r: int = 0, + lora_alpha: int = 1, + **kwargs, + ) -> None: + super().__init__() + LoraLayer.__init__(self, base_layer) + self.fan_in_fan_out = False + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + r, + lora_alpha=lora_alpha, + config=config, + ) + + def resolve_lora_variant(self, *, config, **kwargs) -> Optional[LoraVariant]: + if config.arrow_config is not None: + from .variants import ArrowLinearVariant + + return ArrowLinearVariant() + + use_alora = config.alora_invocation_tokens is not None + if not config.use_dora and not use_alora: + return None + + from .variants import ALoraLinearVariant, DoraLinearVariant + + if use_alora: + return ALoraLinearVariant() + else: + return DoraLinearVariant() + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`list[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. + Defaults to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter not in self.lora_A.keys(): + continue + + warnings.warn( + "Merge lora module to 8-bit linear may get different generations due to rounding errors." + ) + + weight = self.get_base_layer().weight + state = self.get_base_layer().state + if state.SCB is None: + state.SCB = weight.SCB + + # Dequantize the result of identity matrix and int8 weight because bitsandbytes does not support int8 + # dequantization directly + output = dequantize_bnb_weight(weight, state=state) + if active_adapter not in self.lora_variant: # vanilla LoRA + lora_data = self.get_delta_weight(active_adapter) + w_data = output.to(lora_data.dtype).to(lora_data.device) + lora_data + else: + w_data = self.lora_variant[active_adapter].merge_safe(self, active_adapter, output) + + if safe_merge and not torch.isfinite(w_data).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + self.get_base_layer().weight = bnb.nn.Int8Params( + w_data.to("cpu"), requires_grad=False, has_fp16_weights=weight.has_fp16_weights + ).to(weight.device) + + if self.lora_bias[active_adapter]: + bias_data = self.get_base_layer().bias.data + self.lora_B[active_adapter].bias + if safe_merge and not torch.isfinite(bias_data): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + self.get_base_layer().bias.data = bias_data + + state.reset_grads() + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter not in self.lora_A.keys(): + continue + warnings.warn( + "Unmerge lora module to 8-bit linear may get different generations due to rounding errors." + ) + + weight = self.get_base_layer().weight + state = self.get_base_layer().state + if state.SCB is None: + state.SCB = weight.SCB + output = dequantize_bnb_weight(weight, state=state) + + if active_adapter not in self.lora_variant: # vanilla LoRA + lora_data = self.get_delta_weight(active_adapter) + w_data = output.to(lora_data.dtype).to(lora_data.device) - lora_data + else: + w_data = self.lora_variant[active_adapter].unmerge(self, active_adapter, output) + + self.get_base_layer().weight = bnb.nn.Int8Params( + w_data.to("cpu"), requires_grad=False, has_fp16_weights=weight.has_fp16_weights + ).to(weight.device) + + if self.lora_bias[active_adapter]: + self.get_base_layer().bias.data -= self.lora_B[active_adapter].bias + state.reset_grads() + + def get_delta_weight(self, adapter): + return ( + transpose( + self.lora_B[adapter].weight @ self.lora_A[adapter].weight, + False, + ) + * self.scaling[adapter] + ) + + def _mixed_batch_forward( + self, x: torch.Tensor, *args: Any, adapter_names: list[str], **kwargs: Any + ) -> torch.Tensor: + # This is a special method that handles the case when users pass the argument `adapter_names`. This is an + # extra argument that allows mixing different adapters in the same batch at inference time. + variant_kwargs = {k: kwargs.pop(k, None) for k in VARIANT_KWARG_KEYS} # don't pass these to base_layer + result = self.base_layer(x, *args, **kwargs) + + unique_adapters = set(adapter_names) + sub_batch_indices_list = [] + for adapter in unique_adapters: + sub_batch_indices_list.append([index for index, item in enumerate(adapter_names) if item == adapter]) + + for i, active_adapter in enumerate(unique_adapters): + if active_adapter == "__base__": + continue + if active_adapter not in self.lora_A.keys(): + continue + + lora_A = self.lora_A[active_adapter] + lora_B = self.lora_B[active_adapter] + dropout = self.lora_dropout[active_adapter] + scaling = self.scaling[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + x = self._cast_input_dtype(x, lora_A.weight.dtype) + + # getting the sub-batch, passing it to LoRA layers and updating the corresponding indices of the linear + # layer output + sub_batch = x[sub_batch_indices_list[i]] + if active_adapter not in self.lora_variant: # vanilla LoRA: + output = lora_B(lora_A(dropout(sub_batch))) * scaling + if requires_conversion: + output = output.to(expected_dtype) + result[sub_batch_indices_list[i]] += output + else: + alora_offsets = variant_kwargs.get("alora_offsets", None) + if alora_offsets is not None: + variant_kwargs["alora_offsets"] = [alora_offsets[j] for j in sub_batch_indices_list[i]] + output = self.lora_variant[active_adapter].forward( + self, + active_adapter=active_adapter, + x=sub_batch, + result=result[sub_batch_indices_list[i]], + **variant_kwargs, + **kwargs, + ) + if requires_conversion: + output = output.to(expected_dtype) + result[sub_batch_indices_list[i]] = output + + return result + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + self._check_forward_args(x, *args, **kwargs) + adapter_names = kwargs.pop("adapter_names", None) + variant_kwargs = {k: kwargs.pop(k, None) for k in VARIANT_KWARG_KEYS} # don't pass these to base_layer + + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif adapter_names is not None: + result = self._mixed_batch_forward(x, *args, adapter_names=adapter_names, **variant_kwargs, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + for active_adapter in self.active_adapters: + if active_adapter not in self.lora_A.keys(): + continue + lora_A = self.lora_A[active_adapter] + lora_B = self.lora_B[active_adapter] + dropout = self.lora_dropout[active_adapter] + scaling = self.scaling[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + x = self._cast_input_dtype(x, lora_A.weight.dtype) + + if active_adapter not in self.lora_variant: # vanilla LoRA + output = lora_B(lora_A(dropout(x))) * scaling + if requires_conversion: + output = output.to(expected_dtype) + result = result + output + else: + result = self.lora_variant[active_adapter].forward( + self, + active_adapter=active_adapter, + x=x, + result=result, + **variant_kwargs, + **kwargs, + ) + if requires_conversion: + result = result.to(expected_dtype) + + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "lora." + rep + + def dispatch_bnb_8bit(target: torch.nn.Module, adapter_name: str, config: LoraConfig, **kwargs): + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + loaded_in_8bit = kwargs.get("loaded_in_8bit", False) + if loaded_in_8bit and isinstance(target_base_layer, bnb.nn.Linear8bitLt): + eightbit_kwargs = kwargs.copy() + eightbit_kwargs.update( + { + "has_fp16_weights": target.state.has_fp16_weights, + "threshold": target.state.threshold, + "index": target.index, + } + ) + new_module = Linear8bitLt(target, adapter_name, config=config, **eightbit_kwargs) + + return new_module + + +if is_bnb_4bit_available(): + + class Linear4bit(torch.nn.Module, LoraLayer): + # Lora implemented in a dense layer + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + config: LoraConfig, + r: int = 0, + lora_alpha: int = 1, + **kwargs, + ) -> None: + super().__init__() + LoraLayer.__init__(self, base_layer) + self.fan_in_fan_out = False + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + r, + lora_alpha=lora_alpha, + config=config, + ) + + def resolve_lora_variant(self, *, config: LoraConfig, **kwargs) -> Optional[LoraVariant]: + if config.arrow_config is not None: + from .variants import ArrowLinearVariant + + return ArrowLinearVariant() + + use_alora = config.alora_invocation_tokens is not None + if not config.use_dora and not use_alora: + return None + + from .variants import ALoraLinearVariant, DoraLinearVariant + + if use_alora: + return ALoraLinearVariant() + else: + return DoraLinearVariant() + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`list[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. + Defaults to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter not in self.lora_A.keys(): + continue + + warnings.warn( + "Merge lora module to 4-bit linear may get different generations due to rounding errors." + ) + # Refer to https://gist.github.com/ChrisHayduk/1a53463331f52dca205e55982baf9930 + weight = self.get_base_layer().weight + kwargs = weight.__dict__ + + output = dequantize_bnb_weight(weight, state=weight.quant_state) + if active_adapter not in self.lora_variant: # vanilla LoRA + lora_data = self.get_delta_weight(active_adapter) + w_data = output + lora_data + else: + w_data = self.lora_variant[active_adapter].merge_safe(self, active_adapter, output) + + if safe_merge and not torch.isfinite(w_data).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + if "bnb_quantized" in kwargs: + kwargs["bnb_quantized"] = False + kwargs["requires_grad"] = False + kwargs.pop("data", None) + # torch.compile can introduce attributes preceded by '_', remove them + kwargs = {k: v for k, v in kwargs.items() if not k.startswith("_")} + self.get_base_layer().weight = bnb.nn.Params4bit(w_data.to("cpu"), **kwargs).to(weight.device) + + if self.lora_bias[active_adapter]: + bias_data = self.get_base_layer().bias.data + self.lora_B[active_adapter].bias + if safe_merge and not torch.isfinite(bias_data): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + self.get_base_layer().bias.data = bias_data + + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter not in self.lora_A.keys(): + continue + warnings.warn( + "Unmerge lora module to 4-bit linear may get different generations due to rounding errors." + ) + + weight = self.get_base_layer().weight + kwargs = weight.__dict__ + output = dequantize_bnb_weight(weight, state=weight.quant_state) + + if active_adapter not in self.lora_variant: # vanilla LoRA + lora_data = self.get_delta_weight(active_adapter) + w_data = output - lora_data + else: + w_data = self.lora_variant[active_adapter].unmerge(self, active_adapter, output) + + if "bnb_quantized" in kwargs: + kwargs["bnb_quantized"] = False + kwargs["requires_grad"] = False + kwargs.pop("data", None) + self.get_base_layer().weight = bnb.nn.Params4bit(w_data.to("cpu"), **kwargs).to(weight.device) + + if self.lora_bias[active_adapter]: + self.get_base_layer().bias.data -= self.lora_B[active_adapter].bias + + def get_delta_weight(self, adapter): + return ( + transpose( + self.lora_B[adapter].weight @ self.lora_A[adapter].weight, + False, + ) + * self.scaling[adapter] + ) + + def _mixed_batch_forward( + self, x: torch.Tensor, *args: Any, adapter_names: list[str], **kwargs: Any + ) -> torch.Tensor: + # This is a special method that handles the case when users pass the argument `adapter_names`. This is an + # extra argument that allows mixing different adapters in the same batch at inference time. + variant_kwargs = {k: kwargs.pop(k, None) for k in VARIANT_KWARG_KEYS} # don't pass these to base_layer + result = self.base_layer(x, *args, **kwargs) + + unique_adapters = set(adapter_names) + sub_batch_indices_list = [] + for adapter in unique_adapters: + sub_batch_indices_list.append([index for index, item in enumerate(adapter_names) if item == adapter]) + + for i, active_adapter in enumerate(unique_adapters): + if active_adapter == "__base__": + continue + if active_adapter not in self.lora_A.keys(): + continue + + lora_A = self.lora_A[active_adapter] + lora_B = self.lora_B[active_adapter] + dropout = self.lora_dropout[active_adapter] + scaling = self.scaling[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + x = self._cast_input_dtype(x, lora_A.weight.dtype) + + # getting the sub-batch, passing it to LoRA layers and updating the corresponding indices of the linear + # layer output + sub_batch = x[sub_batch_indices_list[i]] + if active_adapter not in self.lora_variant: # vanilla LoRA + output = lora_B(lora_A(dropout(sub_batch))) * scaling + if requires_conversion: + output = output.to(expected_dtype) + result[sub_batch_indices_list[i]] += output + else: + alora_offsets = variant_kwargs.get("alora_offsets", None) + if alora_offsets is not None: + variant_kwargs["alora_offsets"] = [alora_offsets[j] for j in sub_batch_indices_list[i]] + output = self.lora_variant[active_adapter].forward( + self, + active_adapter=active_adapter, + x=sub_batch, + result=result[sub_batch_indices_list[i]], + **variant_kwargs, + **kwargs, + ) + if requires_conversion: + output = output.to(expected_dtype) + result[sub_batch_indices_list[i]] = output + + return result + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + self._check_forward_args(x, *args, **kwargs) + adapter_names = kwargs.pop("adapter_names", None) + variant_kwargs = {k: kwargs.pop(k, None) for k in VARIANT_KWARG_KEYS} # don't pass these to base_layer + + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif adapter_names is not None: + result = self._mixed_batch_forward(x, *args, adapter_names=adapter_names, **variant_kwargs, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + # As per Tim Dettmers, for 4bit, we need to defensively clone here. + # The reason is that in some cases, an error can occur that backprop + # does not work on a manipulated view. This issue may be solved with + # newer PyTorch versions but this would need extensive testing to be + # sure. + result = result.clone() + + for active_adapter in self.active_adapters: + if active_adapter not in self.lora_A.keys(): + continue + lora_A = self.lora_A[active_adapter] + lora_B = self.lora_B[active_adapter] + dropout = self.lora_dropout[active_adapter] + scaling = self.scaling[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + x = self._cast_input_dtype(x, lora_A.weight.dtype) + + if active_adapter not in self.lora_variant: # vanilla LoRA + output = lora_B(lora_A(dropout(x))) * scaling + if requires_conversion: + output = output.to(expected_dtype) + result = result + output + else: + result = self.lora_variant[active_adapter].forward( + self, + active_adapter=active_adapter, + x=x, + result=result, + **variant_kwargs, + **kwargs, + ) + if requires_conversion: + result = result.to(expected_dtype) + + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "lora." + rep + + def dispatch_bnb_4bit(target: torch.nn.Module, adapter_name: str, config: LoraConfig, **kwargs): + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + loaded_in_4bit = kwargs.get("loaded_in_4bit", False) + if loaded_in_4bit and is_bnb_4bit_available() and isinstance(target_base_layer, bnb.nn.Linear4bit): + fourbit_kwargs = kwargs.copy() + fourbit_kwargs.update( + { + "compute_dtype": target_base_layer.compute_dtype, + "compress_statistics": target_base_layer.weight.compress_statistics, + "quant_type": target_base_layer.weight.quant_type, + } + ) + new_module = Linear4bit(target, adapter_name, config=config, **fourbit_kwargs) + + return new_module diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/dora.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/dora.py new file mode 100644 index 0000000000000000000000000000000000000000..f7a397fe51b5c6959c93d57e06660e40fafa0d8d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/dora.py @@ -0,0 +1,287 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from copy import deepcopy +from functools import wraps +from typing import Any, Optional + +import torch +import torch.nn.functional as F +from torch import nn + +from peft.utils.integrations import dequantize_module_weight, gather_params_ctx +from peft.utils.other import transpose + + +ENABLE_DORA_CACHING = False +"""Whether to enable DoRA caching, which makes it faster at inference but requires more memory""" + + +def cache_decorator(cache_key: str): + """Caching decorator for DoRA + + Caching is only enabled if ENABLE_DORA_CACHING is set to True (default: False), when in eval mode, and when the + adapter_name is passed (e.g. not during layer initialization). + + """ + + def cache_value(func): + @wraps(func) + def wrapper(self, *args, **kwargs): + # if adapter_name is not passed, no caching + adapter_name = kwargs.get("adapter_name") + if (not ENABLE_DORA_CACHING) or self.training or (adapter_name is None): + self._cache_clear() + return func(self, *args, **kwargs) + + cache_key_adapter = f"{cache_key}-{adapter_name}" + output = self._cache_get(cache_key_adapter, None) + if output is not None: + return output + + output = func(self, *args, **kwargs) + self._cache_store(cache_key_adapter, output) + return output + + return wrapper + + return cache_value + + +class DoraLinearLayer(nn.Module): + def __init__(self, fan_in_fan_out): + super().__init__() + self.fan_in_fan_out = fan_in_fan_out + self._dora_cache: dict[str, Any] = {} # small ad hoc cache; values are not part of the state_dict + + def _cache_store(self, key: str, value: Any) -> None: + # cache intermediate values, e.g. weight norm of DoRA + self._dora_cache[key] = value + + def _cache_get(self, key: str, default: Optional[Any]) -> Optional[Any]: + # retrieve from ad hoc cache + return self._dora_cache.get(key, default) + + def _cache_clear(self) -> None: + self._dora_cache.clear() + + def train(self, mode: bool = True): + if mode: + self._cache_clear() + super().train(mode=mode) + return self + + @cache_decorator("weight-norm") + def get_weight_norm(self, weight, lora_weight, scaling, adapter_name: Optional[str] = None) -> torch.Tensor: + # calculate L2 norm of weight matrix, column-wise + weight = transpose(weight, self.fan_in_fan_out) + weight = weight + scaling * lora_weight + weight_norm = torch.linalg.norm(weight, dim=1).to(weight.dtype) + return weight_norm + + @cache_decorator("lora-weight") + def get_lora_weight(self, lora_A, lora_B, adapter_name: Optional[str] = None): + # Don't use `lora_weight = lora_B.weight @ lora_A.weight` because this causes errors with FSDP. Instead, + # calculate the same but using forward. + x_eye = torch.eye(lora_A.weight.shape[1], device=lora_A.weight.device, dtype=lora_A.weight.dtype) + lora_weight = lora_B(lora_A(x_eye)).T + return lora_weight + + def update_layer(self, *, base_layer, lora_A, lora_B, scaling, place_on_cpu=False) -> None: + # temporarily convert fp16 to fp32, as fp16 can cause trouble on CPU with PyTorch < 2.2 + dtype_is_fp16 = lora_A.dtype == torch.float16 + if dtype_is_fp16: + lora_A = lora_A.float() + lora_B = lora_B.float() + + with gather_params_ctx(base_layer.parameters()): + if base_layer.__class__.__name__ == "Linear4bit": + # We have to create a copy of the base layer, otherwise, FSDP will throw an error. 8bit does not work + # yet because Int8Params cannot be correctly deep-copied (attributes vanish) + base_layer = deepcopy(base_layer) + + weight = dequantize_module_weight(base_layer) + if weight.data.ndim >= 3: # For handling LoRAs applied to Conv layers. + r = lora_A.shape[0] + lora_weight = torch.mm(lora_B.view([-1, r]), lora_A.view([r, -1])) + lora_weight = lora_weight.reshape(weight.shape) + else: + lora_weight = lora_B @ lora_A + + if dtype_is_fp16: + lora_weight = lora_weight.half() + weight_norm = self.get_weight_norm( + weight=weight.to(lora_A.device), lora_weight=lora_weight, scaling=scaling + ) + + if place_on_cpu: + weight_norm = weight_norm.to("cpu") + self.weight = nn.Parameter(weight_norm, requires_grad=True) + + def forward(self, x, *, lora_A, lora_B, scaling, base_layer, base_result=None, adapter_name="default"): + """ + For DoRA, calculate the extra output from LoRA with DoRA applied. This should be added on top of the base layer + output. + """ + lora_weight = self.get_lora_weight(lora_A=lora_A, lora_B=lora_B, adapter_name=adapter_name) + lora_weight = lora_weight.to(x.dtype) + + magnitude = self.weight + weight = dequantize_module_weight(base_layer) + weight = weight.to(x.dtype) + weight_norm = self.get_weight_norm( + weight=weight, lora_weight=lora_weight.detach(), scaling=scaling, adapter_name=adapter_name + ) + # see section 4.3 of DoRA (https://huggingface.co/papers/2402.09353) + # "[...] we suggest treating ||V +∆V ||_c in + # Eq. (5) as a constant, thereby detaching it from the gradient + # graph. This means that while ||V + ∆V ||_c dynamically + # reflects the updates of ∆V , it won’t receive any gradient + # during backpropagation" + weight_norm = weight_norm.detach() + mag_norm_scale = (magnitude / weight_norm).view(1, -1) + + lora_result = lora_B(lora_A(x)) + + bias = None + if base_result is not None: + bias = base_layer.bias + if bias is not None: + base_result = base_result - bias + else: + base_result = F.linear(x, transpose(weight, self.fan_in_fan_out)) + + result_dora = (mag_norm_scale - 1) * base_result + mag_norm_scale * lora_result * scaling + return result_dora + + def __repr__(self) -> str: + rep = super().__repr__() + return "lora.dora." + rep + + +class DoraEmbeddingLayer(DoraLinearLayer): + @cache_decorator("lora-weight") + def get_lora_weight(self, lora_A, lora_B, adapter_name: Optional[str] = None): + return (lora_A @ lora_B).T + + def forward(self, x, *, lora_A, lora_B, scaling, base_layer, embed_fn, adapter_name="default"): + """ + For DoRA, calculate the extra output from LoRA with DoRA applied. This should be added on top of the base layer + output. + """ + lora_weight = self.get_lora_weight(lora_A=lora_A, lora_B=lora_B, adapter_name=adapter_name) + magnitude = self.weight + weight = base_layer.weight + weight_norm = self.get_weight_norm( + weight=weight, lora_weight=lora_weight.detach(), scaling=scaling, adapter_name=adapter_name + ) + # see section 4.3 of DoRA (https://huggingface.co/papers/2402.09353) + # "[...] we suggest treating ||V +∆V ||_c in + # Eq. (5) as a constant, thereby detaching it from the gradient + # graph. This means that while ||V + ∆V ||_c dynamically + # reflects the updates of ∆V , it won’t receive any gradient + # during backpropagation" + weight_norm = weight_norm.detach() + mag_norm_scale = magnitude / weight_norm + result_dora = mag_norm_scale * (embed_fn(x, lora_A) @ lora_B) * scaling + return mag_norm_scale, result_dora + + def __repr__(self) -> str: + rep = super().__repr__() + return "lora.dora." + rep + + +class _DoraConvNdLayer(DoraLinearLayer): + @cache_decorator("weight-norm") + def get_weight_norm(self, weight, lora_weight, scaling, adapter_name: Optional[str] = None) -> torch.Tensor: + # calculate L2 norm of weight matrix, column-wise + weight = weight + scaling * lora_weight + # the following is needed to have compatibility with the 4/5D weight tensors of Conv2D/3D + dim = tuple(range(1, weight.dim())) + weight_norm = weight.norm(p=2, dim=dim, keepdim=True).transpose(1, 0) + return weight_norm + + @cache_decorator("lora-weight") + def get_lora_weight(self, lora_A, lora_B, adapter_name: Optional[str] = None) -> torch.Tensor: + # Don't use `lora_weight = lora_B.weight @ lora_A.weight` because this causes errors with FSDP. Instead, + # calculate the same but using forward. + r = lora_A.weight.shape[0] + lora_weight = torch.mm(lora_B.weight.view([-1, r]), lora_A.weight.view([r, -1])) + return lora_weight + + def forward( + self, x, *, lora_A, lora_B, scaling, base_layer, base_result=None, adapter_name: str = "default" + ) -> torch.Tensor: + """ + For DoRA, calculate the extra output from LoRA with DoRA applied. This should be added on top of the base layer + output. + """ + weight = base_layer.weight + lora_weight = self.get_lora_weight(lora_A=lora_A, lora_B=lora_B, adapter_name=adapter_name).reshape( + weight.shape + ) + magnitude = self.weight + weight_norm = self.get_weight_norm( + weight=weight, lora_weight=lora_weight.detach(), scaling=scaling, adapter_name=adapter_name + ) + # see section 4.3 of DoRA (https://huggingface.co/papers/2402.09353) + # "[...] we suggest treating ||V +∆V ||_c in + # Eq. (5) as a constant, thereby detaching it from the gradient + # graph. This means that while ||V + ∆V ||_c dynamically + # reflects the updates of ∆V , it won’t receive any gradient + # during backpropagation" + weight_norm = weight_norm.detach() + mag_norm_scale = magnitude / weight_norm + + if base_result is None: + base_result = self.conv_fn( + x, + weight, + bias=None, + stride=base_layer.stride, + padding=base_layer.padding, + dilation=base_layer.dilation, + groups=base_layer.groups, + ) + else: + bias = base_layer.bias + if bias is not None: + # reshape bias to (1, -1, 1, ...) + bias_shape = (1, -1) + (1,) * (base_result.dim() - 2) + base_result = base_result - bias.view(*bias_shape) + + result_dora = (mag_norm_scale - 1) * base_result + mag_norm_scale * lora_B(lora_A(x)) * scaling + return result_dora + + def __repr__(self) -> str: + rep = super().__repr__() + return "lora.dora." + rep + + +class DoraConv1dLayer(_DoraConvNdLayer): + def __init__(self, fan_in_fan_out): + super().__init__(fan_in_fan_out) + self.conv_fn = F.conv1d + + +class DoraConv2dLayer(_DoraConvNdLayer): + def __init__(self, fan_in_fan_out): + super().__init__(fan_in_fan_out) + self.conv_fn = F.conv2d + + +class DoraConv3dLayer(_DoraConvNdLayer): + def __init__(self, fan_in_fan_out): + super().__init__(fan_in_fan_out) + self.conv_fn = F.conv3d diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/eva.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/eva.py new file mode 100644 index 0000000000000000000000000000000000000000..40ada16dcc7e91d7040dd43cab1504cc0afe30c0 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/eva.py @@ -0,0 +1,734 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from collections import Counter, defaultdict +from collections.abc import Callable, Iterable, Mapping +from contextlib import nullcontext +from copy import copy, deepcopy +from functools import partial +from itertools import cycle +from typing import Optional, Union + +import torch +import torch.distributed as dist +from tqdm import tqdm +from transformers.pytorch_utils import Conv1D + +from peft.tuners.tuners_utils import _find_minimal_target_modules, check_target_module_exists +from peft.utils.constants import MIN_TARGET_MODULES_FOR_OPTIMIZATION +from peft.utils.incremental_pca import IncrementalPCA +from peft.utils.other import _get_submodules, get_pattern_key + +from .config import LoraConfig +from .layer import Embedding, LoraLayer, MultiheadAttention, _ConvNd + + +UNSUPPORTED_LORA_MODULES = (Embedding, MultiheadAttention, _ConvNd) + + +class _Hook: + """ + A base class for hooks that prepares layer inputs for EVA. + """ + + def __init__( + self, + name: str, + prepare_layer_inputs_fn: Optional[Callable] = None, + gather_distributed_inputs: bool = True, + ): + self.name = name + self.gather_distributed_inputs = gather_distributed_inputs + if prepare_layer_inputs_fn is None: + self._prepare_layer_inputs_fn = self._prepare_layer_inputs_fn_default + else: + self._prepare_layer_inputs_fn = prepare_layer_inputs_fn + self.model_input = None + + @staticmethod + def _prepare_layer_inputs_fn_default(layer_input, model_input, layer_name) -> torch.Tensor: + if isinstance(layer_input, torch.Tensor): + pass + elif isinstance(layer_input, (tuple, list)): + layer_input = layer_input[0] + else: + raise ValueError( + f"unsupported input type {type(layer_input)} for prepare_layer_inputs_fn in layer {layer_name}, " + "please provide a custom prepare_layer_inputs_fn" + ) + # if the input has more than 2 dimensions, we flatten all but the last dimension + if layer_input.ndim > 2: + layer_input = layer_input.view(-1, layer_input.size(-1)) + return layer_input + + @torch.no_grad() + def prepare_layer_inputs(self, layer_input): + return self._prepare_layer_inputs_fn(layer_input, self.model_input, self.name) + + def gather_layer_inputs(self, layer_input): + if dist.is_initialized() and self.gather_distributed_inputs: + world_size = dist.get_world_size() + + # First gather sizes from all processes more efficiently + local_size = torch.tensor([layer_input.shape[0]], device=layer_input.device) + all_sizes = torch.empty(world_size, dtype=local_size.dtype, device=layer_input.device) + dist.all_gather_into_tensor(all_sizes, local_size) + all_sizes = all_sizes.tolist() + + # Find maximum size and pad tensors + padded_input = layer_input.new_zeros((max(all_sizes), *layer_input.shape[1:])) + padded_input[: layer_input.shape[0]] = layer_input + + # Gather padded tensors + gathered_inputs = [torch.zeros_like(padded_input) for _ in range(world_size)] + dist.all_gather(gathered_inputs, padded_input.contiguous()) + + # Remove padding for each gathered tensor + gathered_inputs = [tensor[:size] for tensor, size in zip(gathered_inputs, all_sizes)] + + # Concatenate along batch dimension + return torch.cat(gathered_inputs, dim=0) + return layer_input + + +class SVDHook(_Hook): + """ + A forward hook for calculating incremental SVD on layer inputs. The hook is designed to be registered to a PyTorch + module using the `register_forward_hook` method. + + This hook performs a step of incremental Singular Value Decomposition (SVD) on the inputs of a specified layer + during the forward pass of a neural network. The hook also tracks convergence of the computed components using + cosine similarity between the current and previous components. + + Args: + name (str): Name of the layer to which this hook is attached. + n_components (int): Number of principal components to compute. + sim_thresh (Union[float, torch.Tensor]): Similarity threshold for convergence. + prepare_layer_inputs_fn (Optional[Callable]): Function to prepare layer inputs for SVD. + """ + + def __init__( + self, + n_components: int, + sim_thresh: Union[float, torch.Tensor], + **base_class_kwargs, + ): + super().__init__(**base_class_kwargs) + self.n_components = n_components + self.sim_thresh = sim_thresh + if isinstance(sim_thresh, torch.Tensor) and len(sim_thresh.shape) > 0: + check1 = sim_thresh.size(0) == n_components or sim_thresh.size(0) == 1 + check2 = len(sim_thresh.shape) == 1 + if not (check1 and check2): + raise ValueError( + "if sim_thresh is a tensor with more than 0 dimensions it must have shape (n_components,) or (1,)" + ) + self.svd = IncrementalPCA( + n_components=n_components, + copy=True, + lowrank=True, + lowrank_seed=42, + ) + self.model_input = None + self.converged = torch.zeros((n_components,), dtype=torch.bool) + + @torch.no_grad() + def __call__(self, model, input, output): + previous_components = None + if hasattr(self.svd, "components_"): + previous_components = self.svd.components_.clone().detach() + states = self.prepare_layer_inputs(input) + states = self.gather_layer_inputs(states) + # check if batch sizes is more than the number of components + if states.size(0) < self.n_components: + print(f"skipping SVD for {self.name} because there are less than {self.n_components} examples") + return + self.svd.partial_fit(states.to(torch.float32)) + # add if statement to check if we are in the first step where previous_components is None + if previous_components is None: + return + components = self.svd.components_ + if len(components.shape) == 1: + components = components.reshape(1, -1) + previous_components = previous_components.reshape(1, -1) + # consider as converged if enough components have converged via cossim + sim = torch.nn.functional.cosine_similarity(components, previous_components) + self.converged = sim >= self.sim_thresh + + +# This is used to determine if inputs of two different layers are equal. For such cases, SVD +# needs to be done for only for one of the equal inputs. +class HashHook(_Hook): + """ + A forward hook for hashing layer inputs. The hook is designed to be registered to a PyTorch module using the + `register_forward_hook` method. + + This hook hashes the inputs of a specified layer during the forward pass of a neural network and stores the hash + values for later analysis or comparison. + + Args: + name (str): Name of the layer to which this hook is attached. hashed_inputs (list): List of hashed inputs. + prepare_layer_inputs_fn (Optional[Callable]): Function to prepare layer inputs for hashing. + """ + + def __init__(self, **base_class_kwargs): + super().__init__(**base_class_kwargs) + self.hashed_inputs = [] + + @staticmethod + def hash_fn(tensor): + return hash(tuple(tensor.view(-1).tolist())) + + @torch.no_grad() + def __call__(self, model, input, output): + x = self.prepare_layer_inputs(input) + x = self.gather_layer_inputs(x) + self.hashed_inputs.append(self.hash_fn(x.cpu())) + + +def find_equal_values(dictionary: dict) -> dict: + """ + Find keys in a dictionary that have the same value. + + This function takes a dictionary and returns a new dictionary containing keys that have the same value. The keys in + the output dictionary are the values from the input dictionary, and the values are lists of keys that share the + same value. + """ + value_dict = defaultdict(list) + for k, v in dictionary.items(): + value_dict[v].append(k) + return {k: v for k, v in value_dict.items() if len(v) > 1} + + +def get_device_with_meta_params(model: torch.nn.Module) -> torch.device: + """ + Get the device of the model's parameters. Useful if some parameters are on meta device. + """ + devices = list({p.device for p in model.parameters() if p.device.type != "meta"}) + if len(devices) > 1: + warnings.warn(f"Could not determine device, model has multiple devices: {devices}") + return + return devices[0] + + +def move_inputs_to_device(inputs, device: Union[str, torch.device]): + """ + Move the inputs to the specified device. Adapted from hf.Trainer. + """ + if hasattr(inputs, "to"): + return inputs.to(device) + if isinstance(inputs, Mapping): + return type(inputs)({k: move_inputs_to_device(v, device) for k, v in inputs.items()}) + elif isinstance(inputs, (tuple, list)): + return type(inputs)(move_inputs_to_device(v, device) for v in inputs) + else: + warnings.warn(f"input of type {type(inputs)} could not be moved to the correct device") + return inputs + + +def prepare_model_inputs_fn_language_modeling(model_input, peft_config: LoraConfig): + """ + Get the indices of the items that should be used for SVD. + + Attributes: + model_input (dict): The model inputs. + peft_config (LoraConfig): The configuration for the LoRA layers. + """ + if not isinstance(model_input, dict): + raise ValueError("When using `prepare_model_inputs_fn_language_modeling` inputs must be a dictionary") + mask = model_input.get("attention_mask", torch.ones_like(model_input["input_ids"])).bool() + if peft_config.eva_config.use_label_mask and hasattr(model_input, "labels"): + mask = torch.logical_and(mask, model_input["labels"] != peft_config.eva_config.label_mask_value) + return mask.nonzero() + + +def prepare_layer_inputs_fn_language_modeling(layer_input, model_input, layer_name) -> torch.Tensor: + """ + if not all items in the input should be used for SVD, this function can be used to get the indices of the items + that should be used. + + Attributes: + layer_input (torch.Tensor): The layer inputs. + model_input (torch.Tensor): + The model inputs or if `prepare_model_inputs_fn` is not None the output of this function. + layer_name (str): The name of the layer. + + Returns: + torch.Tensor: The input to the SVD. + """ + # if layer inputs are not a tensor, we simply get the first item + if isinstance(layer_input, torch.Tensor): + pass + elif isinstance(layer_input, (tuple, list)): + layer_input = layer_input[0] + else: + raise ValueError( + f"unsupported input type {type(layer_input)} for prepare_layer_inputs_fn in layer {layer_name}, " + "please provide a custom prepare_layer_inputs_fn" + ) + # in this case model_input is the output of `prepare_model_inputs_fn_language_modeling` + return layer_input[model_input.T.unbind()] + + +def forward_fn_dict(model, inputs): + return model(**inputs) + + +def _get_eva_state_dict( + model: torch.nn.Module, + dataloader: Iterable, + peft_config: Optional[LoraConfig], + target_module_check_fn: Callable, + forward_fn: Optional[Callable], + prepare_model_inputs_fn: Optional[Callable], + prepare_layer_inputs_fn: Union[Callable, dict[str, Callable], None], + gather_distributed_inputs: bool, + show_progress_bar: bool, +) -> dict: + # Computes the rank distribution for each layer based on the explained variance ratio. + # when rank_pattern flag is False, all values in max_components are the same + def _get_rank_distribution(hooks, layer_hook_map, equal_inputs_map, rank_budget, max_components): + exp_vars = {k: h[0].svd.explained_variance_ratio_[: max_components[k]] for k, h in hooks.items()} + keys, values = zip(*[(k, c) for k, name in layer_hook_map.items() for c in exp_vars[name]]) + idx = torch.stack(values).argsort(descending=True) + counts = Counter([keys[i] for i in idx[:rank_budget]]) + counts = {k: counts.get(k, 0) for k in layer_hook_map.keys()} # add layers with 0 rank + for k, k_hook in equal_inputs_map.items(): + # ensure hook layers have the highest rank if they are equal to another layer + rank, rank_hook = counts[k], counts[k_hook] + if rank_hook >= rank: + continue + counts[k_hook], counts[k] = rank, rank_hook + return counts + + # dataloader is not empty + if len(dataloader) == 0: + raise ValueError("dataloader is empty") + + # check if dist is initialized + if dist.is_initialized() and gather_distributed_inputs: + warnings.warn( + "torch.distributed is initialized and `gather_distributed_inputs` is True, " + "therefore EVA initialization will gather tensors from all ranks. " + "Ensure the model does not receive the same inputs on different ranks." + ) + + # for unusually high rho values, define an upper limit + rho_threshold = 1000 + rho = peft_config.eva_config.rho + if rho > rho_threshold: + max_dim = max(max(p.shape) for p in model.parameters()) + rho_ceil = max_dim // peft_config.r + rho = min(rho, rho_ceil) + + training = model.training + device = get_device_with_meta_params(model) + model.eval() + + # get model inputs + inputs = next(iter(dataloader)) + if device is not None: + inputs = move_inputs_to_device(inputs, device) + if prepare_model_inputs_fn is not None: + model_inputs_for_hooks = prepare_model_inputs_fn(inputs, peft_config) + else: + model_inputs_for_hooks = deepcopy(inputs) + + hooks = {} + max_components = {} + rank_budget = 0 + for name, module in model.named_modules(): + if not target_module_check_fn(name, module): + continue + if isinstance(prepare_layer_inputs_fn, Mapping): + fn = prepare_layer_inputs_fn.pop(name, None) + else: + fn = prepare_layer_inputs_fn + hook = HashHook(name=name, prepare_layer_inputs_fn=fn, gather_distributed_inputs=gather_distributed_inputs) + hook.model_input = model_inputs_for_hooks + handle = module.register_forward_hook(hook) + hooks[name] = (hook, handle) + layer_rank = peft_config.rank_pattern.get( + get_pattern_key(peft_config.rank_pattern.keys(), name), peft_config.r + ) + max_components[name] = round(layer_rank * rho) + rank_budget += layer_rank + if isinstance(prepare_layer_inputs_fn, Mapping) and len(prepare_layer_inputs_fn) > 0: + raise ValueError( + "prepare_layer_inputs_fn is a mapping but the following module names were not found in the model: " + f"{prepare_layer_inputs_fn.keys()}" + ) + + # forward for one batch to check which layer inputs are equal to avoid unneeded svd calculations + forward_fn(model, inputs) + hash_dict = {k: h[0].hashed_inputs[0] for k, h in hooks.items()} + # equal input maps groups layers which receive the same input. One layer is defined as the key and receives an svd + # hook. For the remaining layers the svd results can be skipped. + equal_inputs = list(find_equal_values(hash_dict).values()) + equal_inputs_map = {vv: v[0] for v in equal_inputs for vv in v[1:]} + # for layers with equal inputs we need to make sure that the max_components are the same + for names in equal_inputs: + max_value = max(max_components[n] for n in names) + for n in names: + max_components[n] = max_value + + # initialize svd hooks + for name in list(hooks.keys()): + hook, handle = hooks.pop(name) + handle.remove() + if name in equal_inputs_map: + continue + hook = SVDHook( + n_components=max_components[name], + sim_thresh=peft_config.eva_config.tau, + name=name, + prepare_layer_inputs_fn=hook._prepare_layer_inputs_fn, + gather_distributed_inputs=gather_distributed_inputs, + ) + module = model.get_submodule(name) + handle = module.register_forward_hook(hook) + hooks[name] = (hook, handle) # adding the old handle here so we dont get errors in the first forward pass + layer_hook_map = {**dict(zip(hooks.keys(), hooks.keys())), **equal_inputs_map} + + # start svd calculation + if show_progress_bar and (not dist.is_initialized() or dist.get_rank() == 0): + pbar = tqdm(iter(cycle(dataloader)), position=0, leave=False) + use_tqdm = True + else: + pbar = iter(cycle(dataloader)) + use_tqdm = False + convergence_dict = {k: False for k in hooks.keys()} + rank_dist = max_components.copy() + for inputs in pbar: + if device is not None: + inputs = move_inputs_to_device(inputs, device) + if prepare_model_inputs_fn is not None: + model_inputs_for_hooks = prepare_model_inputs_fn(inputs, peft_config) + else: + model_inputs_for_hooks = deepcopy(inputs) + + for name in list(hooks.keys()): + hook, handle = hooks[name] + # check if all components that are needed for the rank distribution have converged + converged = torch.all(hook.converged[: rank_dist[name]]) + # if a layer has switched from not converged to converged in the current step + if (not convergence_dict[name]) and converged and handle: + handle.remove() + handle = None + convergence_dict[name] = True + continue + # if a layer has switched from converged to not converged in the current step + elif convergence_dict[name] and not converged: + module = model.get_submodule(name) + handle = module.register_forward_hook(hook) + convergence_dict[name] = False + hook.model_input = model_inputs_for_hooks + hooks[name] = (hook, handle) + + if use_tqdm: + layer_converged = list(convergence_dict.values()) + [ + convergence_dict[v] for v in equal_inputs_map.values() + ] + pbar.set_description(f"{sum(layer_converged)}/{len(layer_converged)} layers have converged") + + if all(convergence_dict.values()): + break + + forward_fn(model, inputs) + + # in case some hooks have to skip the svd calculation because the number of tokens is less than the number of + # components + if not all(hasattr(h[0].svd, "components_") for h in hooks.values()): + continue + + rank_dist = _get_rank_distribution(hooks, layer_hook_map, equal_inputs_map, rank_budget, max_components) + + # check all custom hooks have been removed + remaining_hooks = {n for n, m in model.named_modules() for v in m._forward_hooks.values() if isinstance(v, _Hook)} + if len(remaining_hooks) > 0: + raise ValueError( + f"Found active hooks added by EVA that weren't properly removed: {remaining_hooks}. " + "Please report this issue at https://github.com/huggingface/peft/issues" + ) + + eva_state_dict = {} + for name, rank in rank_dist.items(): + hook = hooks[layer_hook_map[name]][0] + if not torch.all(hook.converged[:rank]): + raise ValueError( + f"Layer {name} has not converged but was assigned rank {rank}. " + "Please report this issue at https://github.com/huggingface/peft/issues" + ) + u = hook.svd.components_[:rank] + if peft_config.eva_config.whiten: + u /= hook.svd.singular_values_[:rank].sqrt().reshape(-1, 1) + eva_state_dict[name] = u + + # restore model state + model.train(training) + + # move tensors to device + if device is not None: + eva_state_dict = {k: v.to(device) for k, v in eva_state_dict.items()} + + return eva_state_dict + + +def _load_eva_state_dict( + model: torch.nn.Module, + eva_state_dict: dict, + adapter_name: str, +): + peft_config = copy(model.peft_config[adapter_name]) + missing_eva_inits = [] + new_target_modules = [] + other_module_names = [] + rank_pattern = {} + alpha_pattern = {} + for name, module in model.named_modules(): + name_in_base_model = name.replace("base_model.model.", "") + if not isinstance(module, LoraLayer): + other_module_names.append(name_in_base_model) + continue + # Regexp matching - Find key which matches current target_name in patterns provided + r = peft_config.rank_pattern.get(get_pattern_key(peft_config.rank_pattern.keys(), name), peft_config.r) + alpha = peft_config.alpha_pattern.get( + get_pattern_key(peft_config.alpha_pattern.keys(), name), peft_config.lora_alpha + ) + if name in eva_state_dict: + w = eva_state_dict.pop(name) + new_rank = w.size(0) + if new_rank == 0: + parent, _, target_name = _get_submodules(model, name) + setattr(parent, target_name, module.get_base_layer()) + continue + elif new_rank != r: + if peft_config.eva_config.adjust_scaling_factors: + alpha *= new_rank / r + if new_rank != r or module.lora_A[adapter_name].weight.device.type == "meta": + peft_config.init_lora_weights = "eva" + module.update_layer(adapter_name=adapter_name, r=new_rank, lora_alpha=alpha, config=peft_config) + module.lora_A[adapter_name].weight.copy_(w) + new_target_modules.append(name_in_base_model) + else: + peft_config.init_lora_weights = True + module.update_layer(adapter_name=adapter_name, r=r, lora_alpha=alpha, config=peft_config) + missing_eva_inits.append(name_in_base_model) + new_rank = r + # update rank pattern and alpha pattern + if new_rank != peft_config.r: + rank_pattern[name_in_base_model] = new_rank + if alpha != peft_config.lora_alpha: + alpha_pattern[name_in_base_model] = alpha + + # update target modules if some lora layers have been removed due to their EVA rank being 0 + new_target_modules = new_target_modules + missing_eva_inits + if len(new_target_modules) >= MIN_TARGET_MODULES_FOR_OPTIMIZATION: + new_target_modules = _find_minimal_target_modules(new_target_modules, other_module_names) + model.peft_config[adapter_name].target_modules = new_target_modules + + # set rank pattern obtained from EVA + model.peft_config[adapter_name].rank_pattern = rank_pattern + + # when adjust_scaling_factors is True, lora scaling factors have been adjusted after the rank redistribution + model.peft_config[adapter_name].alpha_pattern = alpha_pattern + + if missing_eva_inits: + warnings.warn( + "the following layers were initialized with init_lora_weights=True because they " + f"were not found in the eva state_dict: {missing_eva_inits}\ncurrently the " + f"following lora modules are not supported by EVA: {UNSUPPORTED_LORA_MODULES}" + ) + + +@torch.no_grad() +def get_eva_state_dict( + model: torch.nn.Module, + dataloader: Iterable, + peft_config: Optional[LoraConfig] = None, + forward_fn: Optional[Callable] = forward_fn_dict, + prepare_model_inputs_fn: Optional[Callable] = prepare_model_inputs_fn_language_modeling, + prepare_layer_inputs_fn: Union[Callable, dict[str, Callable], None] = prepare_layer_inputs_fn_language_modeling, + adapter_name: str = "default", + gather_distributed_inputs: bool = True, + show_progress_bar: bool = True, +) -> dict: + """ + Compute the SVD for each layer in the model. + + This function computes the Singular Value Decomposition (SVD) for each layer in the model. It uses the incremental + PCA method to compute the SVD components. The function also checks for convergence of the computed components using + cosine similarity. The rank distribution for each layer is determined based on the explained variance ratio. + + Args: + model (torch.nn.Module): The model to compute the SVD for. Does not need to be a PeftModel. + dataloader (Iterable): The dataloader to use for the forward pass. + peft_config (Optional[LoraConfig]): + The configuration for the LoRA layers. Only required if `model` is not a PeftModel. + forward_fn (Callable): + The forward function to use for the forward pass. Takes two arguments: `model` and `inputs`. Default + behavior is `return model(**inputs)` + prepare_model_inputs_fn (Optional[Callable]): + This function receives the model inputs and the peft_config and passes the output to + `prepare_layer_inputs_fn`. Can be used to modify the input to the SVD computation based on the original + model inputs. For example for language modeling the attention mask is used to determine which indices are + padding tokens and should not be used for SVD. Any function defined here expects two arguments: + `model_input` and `peft_config`. `peft.tuners.lora.eva.prepare_model_inputs_fn_language_modeling` is used + by default. + prepare_layer_inputs_fn (Union[Callable, Dict[str, Callable], None]): + This function receives the layer inputs, the model inputs (potentially modified by + `prepare_model_inputs_fn`) and the name of the layer and returns the inputs that should be used for SVD for + that particular layer. Any custom function defined here expects three arguments: `layer_input`, + `model_input`, and `layer_name` and should return a 2d tensor. The default logic can be found in + peft.tuners.lora.eva.prepare_layer_inputs_fn_language_modeling and works for language modeling. In this + case model_inputs is the mask used to determine which indices should be used for SVD (created by + `prepare_model_inputs_fn_language_modeling`). + adapter_name (str): The name of the adapter to compute the SVD for. + gather_distributed_inputs (bool): + Whether to gather the layer inputs from all ranks. Default is True meaning in a distributed setting the + layer inputs will be gathered from all ranks for the SVD computation. For non-distributed settings this + argument is ignored. Set to False if you are using a non-distributed dataloader in a distributed setting. + show_progress_bar (bool): Whether to show a progress bar. Default is True. + + Returns: + eva_state_dict (dict): The state dictionary containing the SVD components for each layer. + """ + + def target_module_check_fn_peft_model(name, module, unsupported_lora_modules): + "check if a module is an adapter module via base_layer attribute" + return hasattr(module, "base_layer") and not isinstance(module, unsupported_lora_modules) + + def target_module_check_fn_default(name, module, peft_config): + "check if a module is an adapter module via target_modules" + is_target_module = True + if peft_config.target_modules is not None: + is_target_module = check_target_module_exists(peft_config, name) + # Conv1D for GPT2 support + return isinstance(module, (torch.nn.Linear, Conv1D)) and is_target_module + + is_peft_model = hasattr(model, "peft_config") + + # get peft_config + if is_peft_model and peft_config is None: + peft_config = model.peft_config[adapter_name] + elif peft_config is None: + raise ValueError("peft_config is required if model is not a PeftModel") + + # setup context and target module check function + if is_peft_model: + ctx = model.disable_adapter() + target_module_check_fn = partial( + target_module_check_fn_peft_model, unsupported_lora_modules=UNSUPPORTED_LORA_MODULES + ) + else: + ctx = nullcontext() + target_module_check_fn = partial(target_module_check_fn_default, peft_config=peft_config) + + with ctx: + eva_state_dict = _get_eva_state_dict( + model=model, + dataloader=dataloader, + peft_config=peft_config, + target_module_check_fn=target_module_check_fn, + forward_fn=forward_fn, + prepare_model_inputs_fn=prepare_model_inputs_fn, + prepare_layer_inputs_fn=prepare_layer_inputs_fn, + gather_distributed_inputs=gather_distributed_inputs, + show_progress_bar=show_progress_bar, + ) + return eva_state_dict + + +@torch.no_grad() +def initialize_lora_eva_weights( + model: torch.nn.Module, + dataloader: Optional[Iterable] = None, + eva_state_dict: Optional[dict] = None, + forward_fn: Optional[Callable] = forward_fn_dict, + prepare_model_inputs_fn: Optional[Callable] = prepare_model_inputs_fn_language_modeling, + prepare_layer_inputs_fn: Union[Callable, dict[str, Callable], None] = prepare_layer_inputs_fn_language_modeling, + adapter_name: str = "default", + gather_distributed_inputs: bool = True, + show_progress_bar: bool = True, +): + """ + Initialize the weights of the LoRA layers using the EVA method. + + This function initializes the weights of the LoRA layers using the EVA method. It computes the SVD for each adapter + layer and updates the weights accordingly. + + Args: + model (PeftModel): The peft model to compute the SVD for. + dataloader (Optional[Iterable]): + The dataloader to use for the forward pass. If None, eva_state_dict needs to be provided. + eva_state_dict (Optional[dict]): + The state_dict to load into the model. If None, a dataloader needs to be provided and the state_dict will + be computed using `get_eva_state_dict`. + forward_fn (Callable): + The forward function to use for the forward pass. Takes two arguments: `model` and `inputs`. Default + behavior is `return model(**inputs)` + prepare_model_inputs_fn (Optional[Callable]): + This function receives the model inputs and the peft_config and passes the output to + `prepare_layer_inputs_fn`. Can be used to modify the input to the SVD computation based on the original + model inputs. For example for language modeling the attention mask is used to determine which indices are + padding tokens and should not be used for SVD. Any function defined here expects two arguments: + `model_input` and `peft_config`. `peft.tuners.lora.eva.prepare_model_inputs_fn_language_modeling` is used + by default. + prepare_layer_inputs_fn (Union[Callable, Dict[str, Callable], None]): + This function receives the layer inputs, the model inputs (potentially modified by + `prepare_model_inputs_fn`) and the name of the layer and returns the inputs that should be used for SVD for + that particular layer. Any custom function defined here expects three arguments: `layer_input`, + `model_input`, and `layer_name` and should return a 2d tensor. The default logic can be found in + peft.tuners.lora.eva.prepare_layer_inputs_fn_language_modeling and works for language modeling. In this + case model_inputs is the mask used to determine which indices should be used for SVD (created by + `prepare_model_inputs_fn_language_modeling`). + adapter_name (str): The name of the adapter to initialize the weights for. + gather_distributed_inputs (bool): + Whether to gather the layer inputs from all ranks. Default is True meaning in a distributed setting the + layer inputs will be gathered from all ranks for the SVD computation. For non-distributed settings this + argument is ignored. Set to False if you are using a non-distributed dataloader in a distributed setting. + show_progress_bar (bool): Whether to show a progress bar. Default is True. + + Returns: + model (torch.nn.Module): The model with the initialized LoRA weights. + """ + if not hasattr(model, "peft_config"): + raise ValueError("model must be a PeftModel") + + # eva currently only works with a single active adapter + # Important: when removing this requirement, make sure eva init works correctly if the new rank is 0. + if len(model.active_adapters) > 1: + raise ValueError("`initialize_lora_eva_weights` currently only works with a single active adapter") + + # initialize_lora_eva_weights only works with `init_lora_weights='eva'` + if model.peft_config[adapter_name].init_lora_weights != "eva": + raise ValueError("`initialize_lora_eva_weights` can only be used with `init_lora_weights='eva'`") + + # compute svd + if eva_state_dict is None: + if dataloader is None: + raise ValueError("dataloader is required if eva_state_dict is not provided") + eva_state_dict = get_eva_state_dict( + model=model, + dataloader=dataloader, + forward_fn=forward_fn, + prepare_model_inputs_fn=prepare_model_inputs_fn, + prepare_layer_inputs_fn=prepare_layer_inputs_fn, + adapter_name=adapter_name, + gather_distributed_inputs=gather_distributed_inputs, + show_progress_bar=show_progress_bar, + ) + + _load_eva_state_dict(model, eva_state_dict, adapter_name) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/hqq.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/hqq.py new file mode 100644 index 0000000000000000000000000000000000000000..31f9a3f893db3746a5b0bbc1f0c6d78c6642ff8c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/hqq.py @@ -0,0 +1,244 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import copy +import warnings +from typing import Any, Optional + +import torch + +from peft.import_utils import is_hqq_available +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge +from peft.utils.other import transpose + +from .config import LoraConfig +from .layer import LoraLayer, LoraVariant + + +if is_hqq_available(): + from hqq.core.quantize import HQQLinear + + class HqqLoraLinear(torch.nn.Module, LoraLayer): + # Lora implemented in a dense layer + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + config: LoraConfig, + r: int = 0, + lora_alpha: int = 1, + **kwargs, + ) -> None: + if config.lora_bias: + raise ValueError(f"{self.__class__.__name__} does not support lora_bias yet, set it to False") + + super().__init__() + LoraLayer.__init__(self, base_layer) + self.fan_in_fan_out = False + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + r, + lora_alpha=lora_alpha, + config=config, + ) + + def resolve_lora_variant(self, *, config: LoraConfig, **kwargs) -> Optional[LoraVariant]: + if not config.use_dora: + return None + + from .variants import DoraLinearVariant + + return DoraLinearVariant() + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`list[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. + Defaults to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter not in self.lora_A.keys(): + continue + + layer = self.get_base_layer() + quant_config = {**copy.deepcopy(layer.quant_config), "offload_meta": layer.offload_meta} + + output = layer.dequantize() + if active_adapter not in self.lora_variant: # vanilla LoRA + lora_data = self.get_delta_weight(active_adapter) + w_data = output + lora_data + else: + w_data = self.lora_variant[active_adapter].merge_safe(self, active_adapter, output) + + if safe_merge and not torch.isfinite(w_data).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + new_hqq_layer = HQQLinear(None, quant_config, compute_dtype=layer.compute_dtype, device=layer.device) + quant_config.pop("offload_meta", None) + new_hqq_layer.quantize(w_data, **quant_config) + self.base_layer = new_hqq_layer + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter not in self.lora_A.keys(): + continue + + layer = self.get_base_layer() + quant_config = {**copy.deepcopy(layer.quant_config), "offload_meta": layer.offload_meta} + output = layer.dequantize() + + if active_adapter not in self.lora_variant: # vanilla LoRA + lora_data = self.get_delta_weight(active_adapter) + w_data = output.to(lora_data.dtype).to(lora_data.device) - lora_data + else: + w_data = self.lora_variant[active_adapter].unmerge(self, active_adapter, output) + + new_hqq_layer = HQQLinear(None, quant_config, compute_dtype=layer.compute_dtype, device=layer.device) + quant_config.pop("offload_meta", None) + new_hqq_layer.quantize(w_data, **quant_config) + self.base_layer = new_hqq_layer + + def get_delta_weight(self, adapter): + return ( + transpose( + self.lora_B[adapter].weight @ self.lora_A[adapter].weight, + False, + ) + * self.scaling[adapter] + ) + + def _mixed_batch_forward( + self, x: torch.Tensor, *args: Any, adapter_names: list[str], **kwargs: Any + ) -> torch.Tensor: + # This is a special method that handles the case when users pass the argument `adapter_names`. This is an + # extra argument that allows mixing different adapters in the same batch at inference time. + result = self.base_layer(x, *args, **kwargs) + + unique_adapters = set(adapter_names) + sub_batch_indices_list = [] + for adapter in unique_adapters: + sub_batch_indices_list.append([index for index, item in enumerate(adapter_names) if item == adapter]) + + for i, active_adapter in enumerate(unique_adapters): + if active_adapter == "__base__": + continue + if active_adapter not in self.lora_A.keys(): + continue + + lora_A = self.lora_A[active_adapter] + lora_B = self.lora_B[active_adapter] + dropout = self.lora_dropout[active_adapter] + scaling = self.scaling[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + x = self._cast_input_dtype(x, lora_A.weight.dtype) + + # getting the sub-batch, passing it to LoRA layers and updating the corresponding indices of the linear + # layer output + sub_batch = x[sub_batch_indices_list[i]] + output = lora_B(lora_A(dropout(sub_batch))) * scaling + if requires_conversion: + output = output.to(expected_dtype) + result[sub_batch_indices_list[i]] += output + + return result + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + self._check_forward_args(x, *args, **kwargs) + adapter_names = kwargs.pop("adapter_names", None) + + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif adapter_names is not None: + result = self._mixed_batch_forward(x, *args, adapter_names=adapter_names, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + + for active_adapter in self.active_adapters: + if active_adapter not in self.lora_A.keys(): + continue + lora_A = self.lora_A[active_adapter] + lora_B = self.lora_B[active_adapter] + dropout = self.lora_dropout[active_adapter] + scaling = self.scaling[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + x = self._cast_input_dtype(x, lora_A.weight.dtype) + + if active_adapter not in self.lora_variant: # vanilla LoRA + result = result + lora_B(lora_A(dropout(x))) * scaling + else: + result = self.lora_variant[active_adapter].forward( + self, + active_adapter=active_adapter, + x=x, + result=result, + ) + + if requires_conversion: + result = result.to(expected_dtype) + + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "lora." + rep + + +def dispatch_hqq(target: torch.nn.Module, adapter_name: str, config: LoraConfig, **kwargs): + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if is_hqq_available() and isinstance(target_base_layer, HQQLinear): + new_module = HqqLoraLinear(target_base_layer, adapter_name, config=config, **kwargs) + + return new_module diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/intruders.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/intruders.py new file mode 100644 index 0000000000000000000000000000000000000000..81f0ae479087ef8ed2010dc7f6aeeec5c3d21635 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/intruders.py @@ -0,0 +1,160 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch + +from .layer import LoraLayer + + +def reduce_intruder_dimension( + peft_model, + old_adapter_name="default", + new_adapter_name="intruder_reduced", + top_k=10, + threshold_epsilon=0.5, + mitigation_lambda=0.75, + logging_sink=print, +): + """ + Intruder dimension mitigation based on https://huggingface.co/papers/2410.21228 ("LoRA vs Full Fine-tuning: An + Illusion of Equivalence"). + + This method can recover previous knowledge (i.e. mitigate forgetting) by post-processing already trained low-rank + adapters. This comes at a cost of task accuracy - tuning the `migration_lambda` value can be used to trade between + these two factors. + + After mitigation is done there will be a new adapter with the name set in `new_adapter_name` which is also set to + be the currently active adapter. Inference on the mitigated model will therefore use the modified adapter. To + switch back to the original adapter you can use `peft_model.set_adapter()`. + + Currently only LoRA is supported as it is not clear whether this method generalizes to other delta-weight methods. + + Parameters: + peft_model: + The PEFT model with a loaded LoRA adapter with the name provided in `old_adapter_name`. Currently mixed + models are not supported. + + top_k (default: 10) + Consider the top-k dimensions for intruder detection. The larger the value, the more dimensions will be + considered for intruder detection analysis (and the more false-postiives there can be). Operates on the + cosine similarity between base weights and adapter weights roughly sorted by influence of dimension + (determined by singular value decomposition), so a top-k of 10 will look at the 10 most 'important' + dimensions. + + threshold_epsilon (default: 0.5) + Threshold value when to consider a cosine similarity between base weight and adapter weight as intruder. + According to the paper, intruder dimensions show near-zero absolute cosine similarity with pre-trained + singular vectors. The lower this value, the less potential intruder dimensions are identified. The higher + the value, the more potential false-positives are considered as intruders. + + mitigation_lambda (default: 0.75) + The relative portion of the intruder dimensions that is subtracted from the adapter's delta weight. The + higher the value the more of the intruder dimension is subtracted but the more information is lost. Refer + to Figure 8 in the paper for a trade-off analysis. + + logging_sink (default: print) + Function that prints information about the mitigation process. Set to None if you don't want any output. + """ + # Note that this function currently doesn't support `compile_kwargs` similar to the LoRA conversion tooling + # since there's was no clear way how `torch.compile` can be used to improve performance at the time of + # implementation. See discussion: https://github.com/huggingface/peft/pull/2999#discussion_r2717989613 + + def no_logging_sink(*args, **kwargs): + pass + + if logging_sink is None: + logging_sink = no_logging_sink + + if peft_model.peft_type != "LORA": + raise ValueError("The provided model is not using LoRA and is therefore not supported.") + + peft_model.add_adapter(new_adapter_name, peft_model.peft_config[old_adapter_name]) + + # apply mitigation on the old adapter's weights and move them to the new adapter's weights + for layer_name, layer in peft_model.named_modules(): + if not isinstance(layer, LoraLayer): + continue + + W = layer.get_base_layer().weight.data + dW = layer.get_delta_weight(old_adapter_name) + W_merged = W + dW + is_embedding = old_adapter_name not in layer.lora_B + + cast_to_fp32 = W.dtype in (torch.float16, torch.bfloat16) + + if cast_to_fp32: + W_dtype = W.dtype + W = W.float() + + # compare base weights and adapter weights using cosine similarity. + # based on this similarity we can find intruder dimensions using threshold_epsilon + # on the top_k dimensions + U_base, _S_base, _V_base = torch.linalg.svd(W, full_matrices=False) + U_merged, S_merged, V_merged = torch.linalg.svd(W_merged, full_matrices=False) + + cos_sim = (U_merged.T @ U_base).abs().max(dim=1).values + intruder_idcs = torch.where(cos_sim[:top_k] < threshold_epsilon)[0].tolist() + + if not intruder_idcs: + logging_sink(f"{layer_name}: No intruders") + + # we're not modifying the weights since there are no intruders but we make sure to copy the + # adapter weights unmodified to the new adapter, otherwise these weights will be + # initialized randomly + if is_embedding: + layer.lora_embedding_B[new_adapter_name].data = layer.lora_embedding_B[old_adapter_name].data.clone() + layer.lora_embedding_A[new_adapter_name].data = layer.lora_embedding_A[old_adapter_name].data.clone() + else: + layer.lora_B[new_adapter_name].weight.data = layer.lora_B[old_adapter_name].weight.data.clone() + layer.lora_A[new_adapter_name].weight.data = layer.lora_A[old_adapter_name].weight.data.clone() + continue + else: + logging_sink(f"{layer_name}: Intruders: {len(intruder_idcs)}") + + # the paper computes the intruder dimensions that are subtracted on (W + dW), so we do the same. experiments + # showed that this achieves better knowledge recovery than on dW alone. + B_intruder = U_merged[:, intruder_idcs] @ torch.diag(S_merged)[intruder_idcs, :].sqrt() + A_intruder = (torch.diag(S_merged)[:, intruder_idcs]).sqrt() @ V_merged[intruder_idcs, :] + + # apply mitigation and recover dW = (B@A). + # (W+dW+mitigation)-W = dW+mitigation, so we can convert dW back to A/B using SVD + # since we know the effective rank from the adapter config. + # + # note that we also remove the scaling from dW which is applied in get_delta_weight() since + # it impacts mitigation performance both in task accuracy and forgetting. + W_mitigated = W_merged + (mitigation_lambda - 1) * (B_intruder @ A_intruder) + dW_mitigated = W_mitigated - W + dW_mitigated /= layer.scaling[old_adapter_name] + + U_dW, S_dW, V_dW = torch.linalg.svd(dW_mitigated, full_matrices=False) + + # Note: share scaling by S equally between B and A to avoid one matrix having a significantly + # different norm and avoid possibly weird training dynamics. + effective_rank = layer.r[old_adapter_name] + B_new = U_dW[:, :effective_rank] @ torch.diag(S_dW[:effective_rank]).sqrt() + A_new = torch.diag(S_dW[:effective_rank]).sqrt() @ V_dW[:effective_rank] + + if is_embedding: + layer.lora_embedding_B[new_adapter_name].data = B_new + layer.lora_embedding_A[new_adapter_name].data = A_new + else: + layer.lora_B[new_adapter_name].weight.data = B_new + layer.lora_A[new_adapter_name].weight.data = A_new + + # cast W back from float32 to whatever it was before to save memory in the long run + if cast_to_fp32: + W = W.to(W_dtype) + + logging_sink(f"Enabling new adapter {new_adapter_name}") + peft_model.set_adapter(new_adapter_name) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/loraga.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/loraga.py new file mode 100644 index 0000000000000000000000000000000000000000..0e73c5fe7ae50cac89e10d5702410e4dd1275b71 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/lora/loraga.py @@ -0,0 +1,191 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Reference code: https://github.com/Outsider565/LoRA-GA +# Reference paper: https://arxiv.org/abs/2407.05000 + +import os +from collections.abc import Callable +from typing import Any, Optional + +import torch +import torch.nn as nn +from transformers.pytorch_utils import Conv1D + +from peft.tuners.lora.config import LoraConfig +from peft.tuners.lora.model import LoraModel + + +def get_target_modules(model: nn.Module, config: LoraConfig): + """ + Iterate over LoRA-GA target name and modules of a model. A module is a target if its name is in + `config.target_modules` and is `nn.Linear` or `Conv1D`. + """ + for name, module in model.named_modules(): + if LoraModel._check_target_module_exists(config, name) and isinstance(module, (nn.Linear, Conv1D)): + yield name, module + + +def get_model_device(model: nn.Module) -> str: + if hasattr(model, "module"): # Handle DeepSpeed/DataParallel + model = model.module + return next(iter(model.parameters())).device + + +@torch.no_grad() +def preprocess_loraga( + model: nn.Module, + lora_config: LoraConfig, + train_step: Callable[[], None], + cache_file: Optional[str] = None, +): + """ + Build necessary LoRA-GA fields for a model by estimating gradients. + + For each linear layer, gradients will be estimated by running the provided train_step callback. These gradients are + then attached to the modules and used during initialization. + + Args: + model (`nn.Module`): + Model to preprocess. + lora_config (`LoraConfig`): + Lora configuration of the model. `lora_config.lora_ga_config` should be set. + train_step (`Callable[[], None]`): + Callback to run gradient estimation. Typically you should run model forward and backward passes in this + callback. The gradients will be accumulated across all calls within this callback. + cache_file (`Optional[str]`): + Optional path to cache file for saving/loading gradients. If provided and the file exists, gradients will + be loaded from cache. Otherwise, gradients will be estimated and saved to this path. + + Upon completion, the following fields are set for each target module: + _peft_loraga_grad (`torch.Tensor`): + Accumulated gradient for the weight matrix. + """ + if lora_config.lora_ga_config is None: + raise ValueError( + "If you want to use LoRA-GA, please initialize the LoraConfig with " + "init_lora_weights='lora_ga' and lora_ga_config=LoraGAConfig(...)." + ) + + # Populate target_modules from defaults if empty + # This logic mirrors BaseTuner._prepare_adapter_config which runs after get_peft_model. + # Since preprocess_loraga is called before get_peft_model, we need to handle this ourselves. + if lora_config.target_modules is None: + model_config = LoraModel.get_model_config(model) + target_modules = LoraModel.target_module_mapping.get(model_config["model_type"]) + if target_modules is None: + raise ValueError("Please specify `target_modules` in `peft_config`") + lora_config.target_modules = set(target_modules) + + # Check for quantized models - LoRA-GA requires full-precision gradients + for name, module in get_target_modules(model, lora_config): + if hasattr(module, "quant_state"): + raise ValueError( + f"LoRA-GA does not support quantized models. Found quantized module: '{name}'. " + "LoRA-GA requires full-precision gradients during preprocessing." + ) + + # If cache exists, load from cache + if cache_file is not None and os.path.exists(cache_file) and os.path.getsize(cache_file) > 0: + cache = torch.load(cache_file, map_location=get_model_device(model)) + for name, module in get_target_modules(model, lora_config): + module._peft_loraga_grad = cache[f"{name}._peft_loraga_grad"] + else: + # Estimate gradients by running train_step + estimate_gradients(model, lora_config, train_step) + + # Save cache to disk if specified + if cache_file is not None: + cache: dict[str, Any] = {} + for name, module in get_target_modules(model, lora_config): + cache[f"{name}._peft_loraga_grad"] = module._peft_loraga_grad + + os.makedirs(os.path.dirname(cache_file), exist_ok=True) + torch.save(cache, cache_file) + + +def estimate_gradients( + model: nn.Module, + lora_config: LoraConfig, + train_step: Callable[[], None], +): + """ + Estimate gradients for LoRA-GA initialization. + + This function enables gradient computation ONLY on target module weights and runs the train_step callback. This is + more memory-efficient than enabling gradients globally. + """ + # Remember original training state + was_training = model.training + model.train() + + # Get target modules list once for efficiency + target_module_list = list(get_target_modules(model, lora_config)) + + # Check if any supported layers were found + if not target_module_list: + raise ValueError( + "No supported layers found for LoRA-GA initialization. " + "LoRA-GA only supports nn.Linear and Conv1D layers. " + "Please ensure your model contains at least one of these layer types in target_modules." + ) + + # Initialize gradient storage and count for each target module + for name, module in target_module_list: + module._peft_loraga_grad_count = 0 + + # Memory-efficient gradient computation: disable gradients for all parameters first, + # then enable only for target module weights + original_requires_grad = {} + for name, param in model.named_parameters(): + original_requires_grad[name] = param.requires_grad + param.requires_grad = False + + # Enable gradients ONLY for target module weights + for name, module in target_module_list: + module.weight.requires_grad = True + + # Register backward hooks to count gradient computations + hooks = [] + + def backward_hook(module, grad_input, grad_output): + module._peft_loraga_grad_count += 1 + + for name, module in target_module_list: + hook = module.register_full_backward_hook(backward_hook) + hooks.append(hook) + + # Enable gradient computation and run train_step + with torch.enable_grad(): + train_step() + + # Remove hooks + for hook in hooks: + hook.remove() + + # Restore original requires_grad state for all parameters + for name, param in model.named_parameters(): + if name in original_requires_grad: + param.requires_grad = original_requires_grad[name] + + # Average gradients and clean up temporary fields + for name, module in target_module_list: + if module._peft_loraga_grad_count > 0: + module._peft_loraga_grad = module.weight.grad.detach() / module._peft_loraga_grad_count + module.weight.grad = None + del module._peft_loraga_grad_count + + # Restore original training state + if not was_training: + model.eval() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/multitask_prompt_tuning/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/multitask_prompt_tuning/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fe692a93378254601753cc9b17218fdd5a92b8de --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/multitask_prompt_tuning/__init__.py @@ -0,0 +1,25 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from peft.utils import register_peft_method + +from .config import MultitaskPromptTuningConfig, MultitaskPromptTuningInit +from .model import MultitaskPromptEmbedding + + +__all__ = ["MultitaskPromptEmbedding", "MultitaskPromptTuningConfig", "MultitaskPromptTuningInit"] + +register_peft_method( + name="multitask_prompt_tuning", config_cls=MultitaskPromptTuningConfig, model_cls=MultitaskPromptEmbedding +) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/multitask_prompt_tuning/__pycache__/config.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/multitask_prompt_tuning/__pycache__/config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..200f0042b40be447475365416079e7e78abeb455 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/multitask_prompt_tuning/__pycache__/config.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/multitask_prompt_tuning/__pycache__/model.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/multitask_prompt_tuning/__pycache__/model.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..357869ac280ee309e5e8b65d011f35324985b914 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/multitask_prompt_tuning/__pycache__/model.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/multitask_prompt_tuning/config.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/multitask_prompt_tuning/config.py new file mode 100644 index 0000000000000000000000000000000000000000..6cb279573559e4fa33a973aa35e052647a6ab8f9 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/multitask_prompt_tuning/config.py @@ -0,0 +1,62 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import enum +from dataclasses import dataclass, field +from typing import Optional, Union + +from peft.tuners.prompt_tuning import PromptTuningConfig +from peft.utils import PeftType + + +class MultitaskPromptTuningInit(str, enum.Enum): + # initialize prompt with text + TEXT = "TEXT" + # initialize prompt with random matrix + RANDOM = "RANDOM" + # average the prefix and column matrices obtained during source training + AVERAGE_SOURCE_TASKS = "AVERAGE_SOURCE_TASKS" + # pick prefix and column matrices for a particular task obtained during source training + EXACT_SOURCE_TASK = "EXACT_SOURCE_TASK" + # only use the prompt embeddings trained during source training + ONLY_SOURCE_SHARED = "ONLY_SOURCE_SHARED" + + +@dataclass +class MultitaskPromptTuningConfig(PromptTuningConfig): + prompt_tuning_init: Union[MultitaskPromptTuningInit, str] = field( + default=MultitaskPromptTuningInit.RANDOM, + metadata={ + "help": ( + "How to initialize the prompt tuning parameters. Can be one of TEXT, RANDOM, AVERAGE_SOURCE_TASKS, " + "EXACT_SOURCE_TASK, ONLY_SOURCE_SHARED." + ), + }, + ) + prompt_tuning_init_state_dict_path: Optional[str] = field( + default=None, + metadata={ + "help": ( + "The path of source state dict. This is required when training the downstream target prompt from " + "the pretrained source prompt" + ), + }, + ) + prompt_tuning_init_task: Optional[int] = field(default=0, metadata={"help": "source task id for initialization"}) + num_ranks: Optional[int] = field(default=1, metadata={"help": "ranks"}) + num_tasks: Optional[int] = field(default=1, metadata={"help": "number of tasks"}) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.MULTITASK_PROMPT_TUNING diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/multitask_prompt_tuning/model.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/multitask_prompt_tuning/model.py new file mode 100644 index 0000000000000000000000000000000000000000..20d9d498f48c4f3bc7087c38b4f8072d8de66637 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/multitask_prompt_tuning/model.py @@ -0,0 +1,120 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch + +from peft.tuners.prompt_tuning import PromptEmbedding +from peft.utils import TaskType +from peft.utils.save_and_load import torch_load + +from .config import MultitaskPromptTuningConfig, MultitaskPromptTuningInit + + +# This code is adapted for the paper: https://huggingface.co/papers/2303.02861 and +# constitutes the work done at MIT-IBM Watson Research Lab. + + +class MultitaskPromptEmbedding(PromptEmbedding): + def __init__(self, config: MultitaskPromptTuningConfig, word_embeddings): + super().__init__(config, word_embeddings) + + self.num_tasks = config.num_tasks + self.num_ranks = config.num_ranks + self.num_virtual_tokens = config.num_virtual_tokens + + self.num_transformer_submodules = config.num_transformer_submodules + if self.num_transformer_submodules is None: + self.num_transformer_submodules = 2 if config.task_type == TaskType.SEQ_2_SEQ_LM else 1 + + self.token_dim = config.token_dim + + total_virtual_tokens = self.num_virtual_tokens * self.num_transformer_submodules + + self.prefix_task_cols = torch.nn.Parameter( + torch.normal( + mean=0, + std=0.02, + size=(self.num_tasks, total_virtual_tokens, self.num_ranks), + ) + ) + self.prefix_task_rows = torch.nn.Parameter( + torch.normal( + mean=0, + std=0.02, + size=(self.num_tasks, self.num_ranks, self.token_dim), + ) + ) + + if config.prompt_tuning_init in [ + MultitaskPromptTuningInit.AVERAGE_SOURCE_TASKS, + MultitaskPromptTuningInit.EXACT_SOURCE_TASK, + MultitaskPromptTuningInit.ONLY_SOURCE_SHARED, + ]: + if config.prompt_tuning_init_state_dict_path is None: + raise ValueError( + f"prompt_tuning_init_state_dict_path needs to be specified with {config.prompt_tuning_init} " + "init method" + ) + + if config.prompt_tuning_init_state_dict_path.endswith(".safetensors"): + from safetensors.torch import load_file + + state_dict: dict = load_file(config.prompt_tuning_init_state_dict_path) + else: + state_dict: dict = torch_load( + config.prompt_tuning_init_state_dict_path, + map_location=word_embeddings.weight.device, + ) + + if config.prompt_tuning_init in [ + MultitaskPromptTuningInit.AVERAGE_SOURCE_TASKS, + MultitaskPromptTuningInit.EXACT_SOURCE_TASK, + ]: + prefix_task_cols_: torch.Tensor = state_dict["prefix_task_cols"] + prefix_task_rows_: torch.Tensor = state_dict["prefix_task_rows"] + + if config.prompt_tuning_init == MultitaskPromptTuningInit.AVERAGE_SOURCE_TASKS: + prefix_task_cols_ = prefix_task_cols_.mean(0, keepdim=True) + prefix_task_rows_ = prefix_task_rows_.mean(0, keepdim=True) + elif config.prompt_tuning_init == MultitaskPromptTuningInit.EXACT_SOURCE_TASK: + prefix_task_cols_ = prefix_task_cols_[config.prompt_tuning_init_task, ...].unsqueeze(0) + prefix_task_rows_ = prefix_task_rows_[config.prompt_tuning_init_task, ...].unsqueeze(0) + + state_dict = { + "embedding.weight": state_dict["prompt_embeddings"], + "prefix_task_cols": prefix_task_cols_, + "prefix_task_rows": prefix_task_rows_, + } + + self.load_state_dict(state_dict, strict=True) + elif config.prompt_tuning_init == MultitaskPromptTuningInit.ONLY_SOURCE_SHARED: + state_dict = { + "embedding.weight": state_dict["prompt_embeddings"], + } + + self.load_state_dict(state_dict, strict=False) + + def forward(self, indices, task_ids): + if task_ids is None: + raise ValueError("task_ids cannot be None") + + prompt_embeddings = self.embedding(indices) + + task_cols = torch.index_select(self.prefix_task_cols, 0, task_ids) + task_rows = torch.index_select(self.prefix_task_rows, 0, task_ids) + task_prompts = torch.matmul(task_cols, task_rows) + + prompt_embeddings *= task_prompts + + return prompt_embeddings diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..32e21e32f64b02315731642542cf0bf31227d7a4 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__init__.py @@ -0,0 +1,52 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available, is_eetq_available +from peft.utils import register_peft_method + +from .config import OFTConfig +from .gptq import GPTQOFTLinear +from .layer import Conv2d, Linear, OFTLayer +from .model import OFTModel + + +__all__ = [ + "Conv2d", + "GPTQOFTLinear", + "Linear", + "OFTConfig", + "OFTLayer", + "OFTModel", +] + +register_peft_method(name="oft", config_cls=OFTConfig, model_cls=OFTModel) + + +def __getattr__(name): + if (name == "Linear8bitLt") and is_bnb_available(): + from .bnb import Linear8bitLt + + return Linear8bitLt + + if (name == "Linear4bit") and is_bnb_4bit_available(): + from .bnb import Linear4bit + + return Linear4bit + + if (name == "EetqOFTLinear") and is_eetq_available(): + from .eetq import EetqOFTLinear + + return EetqOFTLinear + + raise AttributeError(f"module {__name__} has no attribute {name}") diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99ab50237f7bd22c6608e9bced6fd7b4bf1ab04d Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/aqlm.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/aqlm.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c86734541513e78e8aa7527a48e87fae4352f390 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/aqlm.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/awq.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/awq.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..74f7eb49e4d792511fd8876fe42a744d8746f491 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/awq.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/bnb.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/bnb.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d934f42990ea2162f2c053f8be2f8f72f82003fa Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/bnb.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/config.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4fa9a5d6953231f11996861fcfef0df7176bcbf7 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/config.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/eetq.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/eetq.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ff1d920ac7196ae65618a846220d32636071647 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/eetq.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/gptq.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/gptq.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..966bb1af990eb12711b5e9654e395f830f836cac Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/gptq.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/hqq.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/hqq.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83e9fe0c079ffed6fc843b22f1bb8ddd7bf2a68e Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/hqq.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/inc.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/inc.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b670e6be94a4c9790adb2b89d0aed25ad1766b9b Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/inc.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/layer.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/layer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..23ec46f7d0534103175b1cfb2651aba36a727629 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/layer.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/model.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/model.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1dbea75c49f67cbe3bf5e172d24c5d203089dac Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/__pycache__/model.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/aqlm.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/aqlm.py new file mode 100644 index 0000000000000000000000000000000000000000..d455d2fe4149be2d78e8386c1aee668de4a74829 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/aqlm.py @@ -0,0 +1,105 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Any, Optional + +import torch + +from peft.import_utils import is_aqlm_available +from peft.tuners.oft.layer import OFTLayer +from peft.tuners.tuners_utils import BaseTunerLayer + + +if is_aqlm_available(): + from aqlm import QuantizedLinear + + +class AqlmOFTLinear(torch.nn.Module, OFTLayer): + def __init__( + self, + base_layer, + adapter_name: str, + r: int = 0, + oft_block_size: int = 32, + module_dropout: float = 0.0, + init_weights: bool = True, + coft: bool = False, + eps: float = 6e-5, + block_share: bool = False, + fan_in_fan_out: bool = False, # Set this to True if the layer to replace stores weight like (fan_in, fan_out) + use_cayley_neumann: bool = False, + num_cayley_neumann_terms: int = 5, + **kwargs, + ): + super().__init__() + OFTLayer.__init__(self, base_layer) + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + r, + oft_block_size=oft_block_size, + module_dropout=module_dropout, + init_weights=init_weights, + coft=coft, + eps=eps, + block_share=block_share, + use_cayley_neumann=use_cayley_neumann, + num_cayley_neumann_terms=num_cayley_neumann_terms, + ) + + def forward(self, x: torch.Tensor): + # note: logic differs from default Linear because merging is not supported + if self.disable_adapters: + return self.base_layer(x) + + for active_adapter in self.active_adapters: + if active_adapter not in self.oft_R.keys(): + continue + oft_R = self.oft_R[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = x.dtype + x = self._cast_input_dtype(x, oft_R.weight.dtype) + + x = oft_R(x) + + result = self.base_layer(x) + if requires_conversion: + result = result.to(expected_dtype) + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "oft." + rep + + +def dispatch_aqlm( + target: torch.nn.Module, + adapter_name: str, + **kwargs: Any, +) -> Optional[torch.nn.Module]: + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if is_aqlm_available() and isinstance(target_base_layer, QuantizedLinear): + new_module = AqlmOFTLinear(target, adapter_name, **kwargs) + target.qweight = target_base_layer.codes + + return new_module diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/awq.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/awq.py new file mode 100644 index 0000000000000000000000000000000000000000..9629d20dd49113fb250a8ca0923be4b241bde9eb --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/awq.py @@ -0,0 +1,107 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Any, Optional + +import torch + +from peft.import_utils import is_gptqmodel_available +from peft.tuners.oft.layer import OFTLayer +from peft.tuners.tuners_utils import BaseTunerLayer + + +class AwqOFTLinear(torch.nn.Module, OFTLayer): + def __init__( + self, + base_layer, + adapter_name, + r: int = 0, + oft_block_size: int = 32, + module_dropout: float = 0.0, + coft: bool = False, + eps: float = 6e-5, + block_share: bool = False, + fan_in_fan_out: bool = False, # Set this to True if the layer to replace stores weight like (fan_in, fan_out) + init_weights: bool = True, + use_cayley_neumann: bool = False, + num_cayley_neumann_terms: int = 5, + **kwargs, + ): + super().__init__() + OFTLayer.__init__(self, base_layer) + + # self.base_layer and self.quant_linear_module are the same; we need the former for consistency and the latter + # for backwards compatibility + self.quant_linear_module = base_layer + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + r, + oft_block_size=oft_block_size, + module_dropout=module_dropout, + coft=coft, + eps=eps, + block_share=block_share, + init_weights=init_weights, + use_cayley_neumann=use_cayley_neumann, + num_cayley_neumann_terms=num_cayley_neumann_terms, + ) + + def forward(self, x: torch.Tensor): + if self.disable_adapters: + result = self.quant_linear_module(x) + return result + + for active_adapter in self.active_adapters: + if active_adapter not in self.oft_R.keys(): + continue + oft_R = self.oft_R[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = x.dtype + x = self._cast_input_dtype(x, oft_R.weight.dtype) + + x = oft_R(x) + if requires_conversion: + x = x.to(expected_dtype) + + result = self.quant_linear_module(x) + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "oft." + rep + + +def dispatch_awq( + target: torch.nn.Module, + adapter_name: str, + **kwargs: Any, +) -> Optional[torch.nn.Module]: + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if is_gptqmodel_available(): + from gptqmodel.nn_modules.qlinear.gemm_awq import AwqGEMMQuantLinear + + if isinstance(target_base_layer, AwqGEMMQuantLinear): + new_module = AwqOFTLinear(target, adapter_name, **kwargs) + target.qweight = target_base_layer.qweight + + return new_module diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/bnb.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/bnb.py new file mode 100644 index 0000000000000000000000000000000000000000..a5da56279bac877da807faacbb74121fb10e3875 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/bnb.py @@ -0,0 +1,388 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import warnings +from typing import Optional + +import bitsandbytes as bnb +import torch + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge +from peft.utils.integrations import dequantize_bnb_weight + +from .layer import OFTLayer + + +if is_bnb_available(): + + class Linear8bitLt(torch.nn.Module, OFTLayer): + # OFT implemented in a dense layer + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + r: int = 8, + oft_block_size: int = 0, + module_dropout: float = 0.0, + init_weights: bool = True, + coft: bool = False, + eps: float = 6e-5, + block_share: bool = False, + use_cayley_neumann: bool = False, + num_cayley_neumann_terms: int = 5, + **kwargs, + ) -> None: + super().__init__() + OFTLayer.__init__(self, base_layer) + self.fan_in_fan_out = False + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + r, + oft_block_size=oft_block_size, + module_dropout=module_dropout, + coft=coft, + eps=eps, + block_share=block_share, + init_weights=init_weights, + use_cayley_neumann=use_cayley_neumann, + num_cayley_neumann_terms=num_cayley_neumann_terms, + ) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`list[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. + Defaults to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter not in self.oft_R.keys(): + continue + + warnings.warn("Merge oft module to 8-bit linear may get different generations due to rounding errors.") + + weight = self.get_base_layer().weight + state = self.get_base_layer().state + if state.SCB is None: + state.SCB = weight.SCB + + # Dequantize the result of identity matrix and int8 weight because bitsandbytes does not support int8 + # dequantization directly + output = dequantize_bnb_weight(weight, state=state) + oft_data = self.get_delta_weight(active_adapter) + + output = torch.transpose(output, 0, 1) + w_data = torch.mm(oft_data, output.to(oft_data.dtype)) + w_data = torch.transpose(w_data, 0, 1) + w_data = output.to(oft_data.dtype).to(oft_data.device) + + if safe_merge and not torch.isfinite(w_data).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + self.get_base_layer().weight = bnb.nn.Int8Params( + w_data.to("cpu"), requires_grad=False, has_fp16_weights=weight.has_fp16_weights + ).to(weight.device) + + state.reset_grads() + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter not in self.oft_R.keys(): + continue + warnings.warn( + "Unmerge oft module to 8-bit linear may get different generations due to rounding errors." + ) + + weight = self.get_base_layer().weight + state = self.get_base_layer().state + if state.SCB is None: + state.SCB = weight.SCB + output = dequantize_bnb_weight(weight, state=state) + + oft_data = self.get_delta_weight(active_adapter) + + output = torch.transpose(output, 0, 1) + w_data = torch.mm(oft_data.t(), output.to(oft_data.dtype)) + w_data = torch.transpose(w_data, 0, 1) + w_data = w_data.to(oft_data.dtype).to(oft_data.device) + + self.get_base_layer().weight = bnb.nn.Int8Params( + w_data.to("cpu"), requires_grad=False, has_fp16_weights=weight.has_fp16_weights + ).to(weight.device) + + state.reset_grads() + + def get_delta_weight(self, adapter): + return self.oft_R[adapter].get_weight() + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + for active_adapter in self.active_adapters: + if active_adapter not in self.oft_R.keys(): + continue + oft_R = self.oft_R[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = x.dtype + x = self._cast_input_dtype(x, oft_R.weight.dtype) + + x = oft_R(x) + if requires_conversion: + x = x.to(expected_dtype) + + result = self.base_layer(x, *args, **kwargs) + + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "oft." + rep + + def dispatch_bnb_8bit(target: torch.nn.Module, adapter_name: str, **kwargs): + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + loaded_in_8bit = kwargs.get("loaded_in_8bit", False) + if loaded_in_8bit and isinstance(target_base_layer, bnb.nn.Linear8bitLt): + eightbit_kwargs = kwargs.copy() + eightbit_kwargs.update( + { + "has_fp16_weights": target.state.has_fp16_weights, + "threshold": target.state.threshold, + "index": target.index, + } + ) + new_module = Linear8bitLt(target, adapter_name, **eightbit_kwargs) + + return new_module + + +if is_bnb_4bit_available(): + + class Linear4bit(torch.nn.Module, OFTLayer): + # OFT implemented in a dense layer + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + r: int = 8, + oft_block_size: int = 0, + module_dropout: float = 0.0, + coft: bool = False, + eps: float = 6e-5, + block_share: bool = False, + init_weights: bool = True, + use_cayley_neumann: bool = False, + num_cayley_neumann_terms: int = 5, + **kwargs, + ) -> None: + super().__init__() + OFTLayer.__init__(self, base_layer) + self.fan_in_fan_out = False + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + r, + oft_block_size=oft_block_size, + module_dropout=module_dropout, + coft=coft, + eps=eps, + block_share=block_share, + init_weights=init_weights, + use_cayley_neumann=use_cayley_neumann, + num_cayley_neumann_terms=num_cayley_neumann_terms, + ) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`list[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. + Defaults to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter not in self.oft_R.keys(): + continue + + warnings.warn("Merge oft module to 4-bit linear may get different generations due to rounding errors.") + # Refer to https://gist.github.com/ChrisHayduk/1a53463331f52dca205e55982baf9930 + weight = self.get_base_layer().weight + kwargs = weight.__dict__ + + output = dequantize_bnb_weight(weight, state=weight.quant_state) + + oft_data = self.get_delta_weight(active_adapter) + output = torch.transpose(output, 0, 1) + w_data = torch.mm(oft_data, output.to(oft_data.dtype)) + w_data = torch.transpose(w_data, 0, 1) + w_data = output.to(oft_data.dtype).to(oft_data.device) + + if safe_merge and not torch.isfinite(w_data).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + if "bnb_quantized" in kwargs: + kwargs["bnb_quantized"] = False + kwargs["requires_grad"] = False + kwargs.pop("data", None) + # torch.compile can introduce attributes preceded by '_', remove them + kwargs = {k: v for k, v in kwargs.items() if not k.startswith("_")} + self.get_base_layer().weight = bnb.nn.Params4bit(w_data.to("cpu"), **kwargs).to(weight.device) + + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter not in self.oft_R.keys(): + continue + warnings.warn( + "Unmerge oft module to 4-bit linear may get different generations due to rounding errors." + ) + + weight = self.get_base_layer().weight + kwargs = weight.__dict__ + output = dequantize_bnb_weight(weight, state=weight.quant_state) + + oft_data = self.get_delta_weight(active_adapter) + + output = torch.transpose(output, 0, 1) + w_data = torch.mm(oft_data.t(), output.to(oft_data.dtype)) + w_data = torch.transpose(w_data, 0, 1) + w_data = output.to(oft_data.dtype).to(oft_data.device) + + if "bnb_quantized" in kwargs: + kwargs["bnb_quantized"] = False + kwargs["requires_grad"] = False + kwargs.pop("data", None) + self.get_base_layer().weight = bnb.nn.Params4bit(w_data.to("cpu"), **kwargs).to(weight.device) + + def get_delta_weight(self, adapter): + return self.oft_R[adapter].get_weight() + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + # As per Tim Dettmers, for 4bit, we need to defensively clone here. + # The reason is that in some cases, an error can occur that backprop + # does not work on a manipulated view. This issue may be solved with + # newer PyTorch versions but this would need extensive testing to be + # sure. + # result = result.clone() + + for active_adapter in self.active_adapters: + if active_adapter not in self.oft_R.keys(): + continue + oft_R = self.oft_R[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = x.dtype + x = self._cast_input_dtype(x, oft_R.weight.dtype) + + x = oft_R(x) + if requires_conversion: + x = x.to(expected_dtype) + + result = self.base_layer(x, *args, **kwargs) + + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "oft." + rep + + def dispatch_bnb_4bit(target: torch.nn.Module, adapter_name: str, **kwargs): + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + loaded_in_4bit = kwargs.get("loaded_in_4bit", False) + if loaded_in_4bit and is_bnb_4bit_available() and isinstance(target_base_layer, bnb.nn.Linear4bit): + fourbit_kwargs = kwargs.copy() + fourbit_kwargs.update( + { + "compute_dtype": target_base_layer.compute_dtype, + "compress_statistics": target_base_layer.weight.compress_statistics, + "quant_type": target_base_layer.weight.quant_type, + } + ) + new_module = Linear4bit(target, adapter_name, **fourbit_kwargs) + + return new_module diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/config.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/config.py new file mode 100644 index 0000000000000000000000000000000000000000..9c62e1becea23cd3ca0f0d568f8c176d96c70a78 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/config.py @@ -0,0 +1,213 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import warnings +from dataclasses import dataclass, field +from typing import Literal, Optional, Union + +import packaging.version + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class OFTConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`OFTModel`]. + + Args: + r (`int`): OFT rank, number of OFT blocks per injected layer. + oft_block_size (`int`): OFT block size across different layers. + module_dropout (`float`): + The multiplicative dropout probability, by setting OFT blocks to identity during training, similar to the + dropout layer in LoRA. + target_modules (`Optional[Union[list[str], str]]`): + The names of the modules to apply the adapter to. If this is specified, only the modules with the specified + names will be replaced. When passing a string, a regex match will be performed. When passing a list of + strings, either an exact match will be performed or it is checked if the name of the module ends with any + of the passed strings. If this is specified as 'all-linear', then all linear modules are chosen, excluding + the output layer. If this is not specified, modules will be chosen according to the model architecture. If + the architecture is not known, an error will be raised -- in this case, you should specify the target + modules manually. + fan_in_fan_out (`bool`): Set this to True if the layer to replace stores weight like (fan_in, fan_out). + bias (`str`): Bias type for OFT. Can be 'none', 'all' or 'oft_only'. If 'all' or 'oft_only', the + corresponding biases will be updated during training. Be aware that this means that, even when disabling + the adapters, the model will not produce the same output as the base model would have without adaptation. + exclude_modules (`Optional[Union[List[str], str]]`): + The names of the modules to not apply the adapter. When passing a string, a regex match will be performed. + When passing a list of strings, either an exact match will be performed or it is checked if the name of the + module ends with any of the passed strings. + init_weights (`bool`): + Whether to perform initialization of OFT weights. + layers_to_transform (`Union[List[int], int]`): + The layer indices to transform. If a list of ints is passed, it will apply the adapter to the layer indices + that are specified in this list. If a single integer is passed, it will apply the transformations on the + layer at this index. + layers_pattern (`Optional[Union[List[str], str]]`): + The layer pattern name, used only if `layers_to_transform` is different from `None`. This should target the + `nn.ModuleList` of the model, which is often called `'layers'` or `'h'`. + modules_to_save (`List[str]`): + List of modules apart from adapter layers to be set as trainable and saved in the final checkpoint. + coft (`bool`): + Whether to use the constrained variant of OFT or not, off by default. + eps (`float`): + The control strength of COFT. The freedom of rotation. Only has an effect if `coft` is set to True. + block_share (`bool`): + Whether to share the OFT parameters between blocks or not. This is `False` by default. + """ + + r: int = field(default=0, metadata={"help": "OFT rank, number of OFT blocks per injected layer."}) + oft_block_size: int = field( + default=32, + metadata={ + "help": "OFT block size across different layers.", + "note": "You can only specify either r or oft_block_size, but not both simultaneously, because r x oft_block_size = layer dimension.", + }, + ) + module_dropout: float = field( + default=0.0, + metadata={ + "help": "OFT multiplicative dropout, randomly setting blocks of OFT to be identity matrix, similar to the dropout layer in LoRA." + }, + ) + target_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": "List of module names or regex expression of the module names to replace with OFT." + "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$' " + "This can also be a wildcard 'all-linear' which matches all linear/Conv1D layers except the output layer." + }, + ) + fan_in_fan_out: bool = field( + default=False, + metadata={"help": "Set this to True if the layer to replace stores weight like (fan_in, fan_out)"}, + ) + bias: Literal["none", "all", "oft_only"] = field( + default="none", metadata={"help": "Bias type for OFT. Can be 'none', 'all' or 'oft_only'"} + ) + exclude_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={"help": "List of module names or regex expression of the module names to exclude from OFT."}, + ) + init_weights: bool = field( + default=True, + metadata={ + "help": ( + "Whether to initialize the weights of the OFT layers with their default initialization. Don't change " + "this setting, except if you know exactly what you're doing." + ), + }, + ) + layers_to_transform: Optional[Union[list[int], int]] = field( + default=None, + metadata={ + "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." + }, + ) + layers_pattern: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "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. " + "This should target the `nn.ModuleList` of the model, which is often called `'layers'` or `'h'`." + }, + ) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": "List of modules apart from OFT layers to be set as trainable and saved in the final checkpoint. " + "For example, in Sequence Classification or Token Classification tasks, " + "the final layer `classifier/score` are randomly initialized and as such need to be trainable and saved." + }, + ) + coft: bool = field( + default=False, + metadata={"help": "Whether to use the constrained variant of OFT or not."}, + ) + eps: float = field( + default=6e-5, + metadata={ + "help": "The control strength of COFT. The freedom of rotation. Only has an effect if `coft` is set to True." + }, + ) + block_share: bool = field( + default=False, + metadata={"help": "Whether to share the OFT parameters between blocks or not."}, + ) + use_cayley_neumann: bool = field( + default=True, + metadata={ + "help": "Whether to use the Cayley-Neumann Formulation of OFT or not. Set to True to improve computational efficiency but comes at costs of bigger approximation error for orthogonality." + }, + ) + num_cayley_neumann_terms: int = field( + default=5, + metadata={ + "help": "Number of Cayley-Neumann terms to use. Higher number results in less approximation error for orthogonality." + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.OFT + self.target_modules = ( + set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules + ) + self.exclude_modules = ( + set(self.exclude_modules) if isinstance(self.exclude_modules, list) else self.exclude_modules + ) + # check for layers_to_transform and layers_pattern + if self.layers_pattern and not self.layers_to_transform: + raise ValueError("When `layers_pattern` is specified, `layers_to_transform` must also be specified. ") + if self.r == 0 and self.oft_block_size == 0: + raise ValueError( + f"Either `r` or `oft_block_size` must be non-zero. Currently, r = {self.r} and oft_block_size = {self.oft_block_size}." + ) + if not (self.r != 0) ^ (self.oft_block_size != 0): + raise ValueError( + f"You can only specify either r ({self.r}) or oft_block_size ({self.oft_block_size}), but not both simultaneously, because r x oft_block_size == in_features." + ) + + @classmethod + def check_kwargs(cls, **kwargs): + r""" + Check if the kwargs are valid for the configuration. + + Args: + kwargs (additional keyword arguments, *optional*): + Additional keyword arguments passed along to the child class initialization. + """ + if "oft_block_size" not in kwargs: + raise ValueError( + "OFT has been updated since PEFT 0.14.0. Your trained adapter weights are incompatible " + "with the latest version of OFT. Please retrain your adapter weights with newer PEFT versions. " + "Alternatively, downgrade PEFT to version 0.13.0 to use the old adapter weights." + ) + if kwargs.get("use_cayley_neumann", False): + peft_version = kwargs.get("peft_version", "0.0.0") # if not present, set a low dummy version + # remove commit hash, if present + peft_version = peft_version.partition("@")[0] + parsed_version = packaging.version.Version(peft_version) + min_version = packaging.version.Version("0.18.0") + # note: config.peft_version was added in 0.18.0, so if it's missing, it means we're below min version + if parsed_version < min_version: + msg = ( + "The cayley-neumann parameterization has been slightly changed to be more numerically stable in " + "PEFT 0.18.0. Please retrain your adapter weights with newer PEFT versions. Alternatively, " + "downgrade PEFT to version 0.17.0 to use the old parameterization." + ) + warnings.warn(msg) + return super().check_kwargs(**kwargs) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/eetq.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/eetq.py new file mode 100644 index 0000000000000000000000000000000000000000..2d6538165a4f040617e68ff1bceca494f112c3e5 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/eetq.py @@ -0,0 +1,116 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Any, Optional + +import torch + +from peft.import_utils import is_eetq_available +from peft.tuners.oft.layer import OFTLayer +from peft.tuners.tuners_utils import BaseTunerLayer + + +if is_eetq_available(): + from eetq import EetqLinear + + class EetqOFTLinear(torch.nn.Module, OFTLayer): + def __init__( + self, + base_layer, + adapter_name, + r: int = 0, + oft_block_size: int = 0, + module_dropout: float = 0.0, + init_weights: bool = True, + coft: bool = False, + eps: float = 6e-5, + block_share: bool = False, + use_cayley_neumann: bool = False, + num_cayley_neumann_terms: int = 5, + fan_in_fan_out: bool = False, + **kwargs, + ): + super().__init__() + OFTLayer.__init__(self, base_layer) + + # self.base_layer and self.quant_linear_module are the same; we need the former for consistency and the latter + # for backwards compatibility + self.quant_linear_module = base_layer + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + r, + oft_block_size=oft_block_size, + module_dropout=module_dropout, + init_weights=init_weights, + coft=coft, + eps=eps, + block_share=block_share, + fan_in_fan_out=fan_in_fan_out, + use_cayley_neumann=use_cayley_neumann, + num_cayley_neumann_terms=num_cayley_neumann_terms, + ) + + def forward(self, x: torch.Tensor): + if self.disable_adapters: + return self.quant_linear_module(x) + + for active_adapter in self.active_adapters: + if active_adapter not in self.oft_R.keys(): + continue + oft_R = self.oft_R[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = x.dtype + x = self._cast_input_dtype(x, oft_R.weight.dtype) + + x = oft_R(x) + + result = self.quant_linear_module(x) + if requires_conversion: + result = result.to(expected_dtype) + return result + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + raise AttributeError("Merging LoRA layers is not supported for Eetq layers.") + + def unmerge(self) -> None: + raise AttributeError("Unmerging LoRA layers is not supported for Eetq layers.") + + def __repr__(self) -> str: + rep = super().__repr__() + return "oft." + rep + + +def dispatch_eetq( + target: torch.nn.Module, + adapter_name: str, + **kwargs: Any, +) -> Optional[torch.nn.Module]: + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if is_eetq_available() and isinstance(target_base_layer, EetqLinear): + new_module = EetqOFTLinear(target, adapter_name, **kwargs) + target.weight = target_base_layer.weight + + if hasattr(target, "bias"): + target.bias = target_base_layer.bias + + return new_module diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/gptq.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/gptq.py new file mode 100644 index 0000000000000000000000000000000000000000..df6c03b9bd86205a47eb3fe0b7ce3c904ffd185c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/gptq.py @@ -0,0 +1,106 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Any, Optional + +import torch + +from peft.import_utils import is_gptqmodel_available +from peft.tuners.oft.layer import OFTLayer +from peft.tuners.tuners_utils import BaseTunerLayer + + +class GPTQOFTLinear(torch.nn.Module, OFTLayer): + def __init__( + self, + base_layer, + adapter_name: str, + r: int = 8, + oft_block_size: int = 0, + module_dropout: float = 0.0, + coft: bool = False, + eps: float = 6e-5, + block_share: bool = False, + use_cayley_neumann: bool = False, + num_cayley_neumann_terms: int = 5, + fan_in_fan_out: bool = False, # Set this to True if the layer to replace stores weight like (fan_in, fan_out) + init_weights: bool = True, + **kwargs, + ): + super().__init__() + OFTLayer.__init__(self, base_layer) + + # self.base_layer and self.quant_linear_module are the same; we need the former for consistency and the latter + # for backwards compatibility + self.quant_linear_module = base_layer + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + r, + oft_block_size=oft_block_size, + module_dropout=module_dropout, + coft=coft, + eps=eps, + block_share=block_share, + init_weights=init_weights, + use_cayley_neumann=use_cayley_neumann, + num_cayley_neumann_terms=num_cayley_neumann_terms, + ) + + def forward(self, x: torch.Tensor): + # note: logic differs from default Linear because merging is not supported + if self.disable_adapters: + return self.quant_linear_module(x) + + for active_adapter in self.active_adapters: + if active_adapter not in self.oft_R.keys(): + continue + + oft_R = self.oft_R[active_adapter] + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = x.dtype + x = self._cast_input_dtype(x, oft_R.weight.dtype) + + x = oft_R(x) + if requires_conversion: + x = x.to(expected_dtype) + + result = self.quant_linear_module(x) + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "oft." + rep + + +def dispatch_gptq( + target: torch.nn.Module, + adapter_name: str, + **kwargs: Any, +) -> Optional[torch.nn.Module]: + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if is_gptqmodel_available(): + from gptqmodel.nn_modules.qlinear import BaseQuantLinear + + if isinstance(target_base_layer, BaseQuantLinear): + new_module = GPTQOFTLinear(target, adapter_name, **kwargs) + target.qweight = target_base_layer.qweight + + return new_module diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/hqq.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/hqq.py new file mode 100644 index 0000000000000000000000000000000000000000..5f83dd11b0bb4f4c349dd1beb95733b5e617c158 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/hqq.py @@ -0,0 +1,186 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import copy +import warnings +from typing import Optional + +import torch + +from peft.import_utils import is_hqq_available +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge + +from .layer import OFTLayer + + +if is_hqq_available(): + from hqq.core.quantize import HQQLinear + + class HqqOFTLinear(torch.nn.Module, OFTLayer): + # Lora implemented in a dense layer + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + r: int = 8, + oft_block_size: int = 0, + module_dropout: float = 0.0, + init_weights: bool = True, + coft: bool = False, + eps: float = 6e-5, + block_share: bool = False, + use_cayley_neumann: bool = False, + num_cayley_neumann_terms: int = 5, + **kwargs, + ) -> None: + super().__init__() + OFTLayer.__init__(self, base_layer) + self.fan_in_fan_out = False + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + r, + oft_block_size=oft_block_size, + module_dropout=module_dropout, + init_weights=init_weights, + coft=coft, + eps=eps, + block_share=block_share, + use_cayley_neumann=use_cayley_neumann, + num_cayley_neumann_terms=num_cayley_neumann_terms, + ) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`list[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. + Defaults to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter not in self.lora_A.keys(): + continue + + layer = self.get_base_layer() + quant_config = {**copy.deepcopy(layer.quant_config), "offload_meta": layer.offload_meta} + + output = layer.dequantize() + oft_data = self.get_delta_weight(active_adapter) + + output = torch.transpose(output, 0, 1) + w_data = torch.mm(oft_data, output.to(oft_data.dtype)) + w_data = torch.transpose(w_data, 0, 1) + w_data = output.to(oft_data.dtype).to(oft_data.device) + + if safe_merge and not torch.isfinite(w_data).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + new_hqq_layer = HQQLinear(None, quant_config, compute_dtype=layer.compute_dtype, device=layer.device) + quant_config.pop("offload_meta", None) + new_hqq_layer.quantize(w_data, **quant_config) + self.base_layer = new_hqq_layer + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter not in self.oft_R.keys(): + continue + + layer = self.get_base_layer() + quant_config = {**copy.deepcopy(layer.quant_config), "offload_meta": layer.offload_meta} + output = layer.dequantize() + + oft_data = self.get_delta_weight(active_adapter) + + output = torch.transpose(output, 0, 1) + w_data = torch.mm(oft_data.t(), output.to(oft_data.dtype)) + w_data = torch.transpose(w_data, 0, 1) + w_data = w_data.to(oft_data.dtype).to(oft_data.device) + + new_hqq_layer = HQQLinear(None, quant_config, compute_dtype=layer.compute_dtype, device=layer.device) + quant_config.pop("offload_meta", None) + new_hqq_layer.quantize(w_data, **quant_config) + self.base_layer = new_hqq_layer + + def get_delta_weight(self, adapter): + return self.oft_R[adapter].get_weight() + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + self._check_forward_args(x, *args, **kwargs) + adapter_names = kwargs.pop("adapter_names", None) + + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + for active_adapter in self.active_adapters: + if active_adapter not in self.oft_R.keys(): + continue + oft_R = self.oft_R[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = x.dtype + x = self._cast_input_dtype(x, oft_R.weight.dtype) + + x = oft_R(x) + + result = self.base_layer(x, *args, **kwargs) + if requires_conversion: + result = result.to(expected_dtype) + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "oft." + rep + + +def dispatch_hqq(target: torch.nn.Module, adapter_name: str, **kwargs): + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if is_hqq_available() and isinstance(target_base_layer, HQQLinear): + new_module = HqqOFTLinear(target_base_layer, adapter_name, **kwargs) + + return new_module diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/inc.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/inc.py new file mode 100644 index 0000000000000000000000000000000000000000..6ed855bc7dc65af10d77a2f486abb8fc27c12dd5 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/inc.py @@ -0,0 +1,78 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# NOTE: PEFT tests related to INC are handled under Optimum-Habana repository: +# - LLMs: https://github.com/huggingface/optimum-habana/blob/main/tests/test_peft_inference.py +# - Diffusers: https://github.com/huggingface/optimum-habana/blob/main/tests/test_diffusers.py + +from typing import Optional + +import torch + +from peft.import_utils import is_inc_available +from peft.tuners.tuners_utils import BaseTunerLayer + +from .layer import Linear + + +if is_inc_available(): + + class IncOFTLinear(Linear): + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + **kwargs, + ): + super().__init__(base_layer, adapter_name, **kwargs) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`list[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. + Defaults to `None`. + """ + raise NotImplementedError("Merging OFT with INC layers is not yet implemented") + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + raise NotImplementedError("Unmerging OFT from INC layers is not yet implemented") + + +def dispatch_inc(target: torch.nn.Module, adapter_name: str, **kwargs): + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if is_inc_available(): + from neural_compressor.torch.algorithms.fp8_quant._quant_common.helper_modules import ( + PatchedLinear, + ) + + if isinstance(target_base_layer, PatchedLinear): + new_module = IncOFTLinear(target, adapter_name, **kwargs) + + return new_module diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/layer.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..7653dd3d6075d11b9f0fd5bc9a9914c80d1b4105 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/layer.py @@ -0,0 +1,1229 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import warnings +from typing import Any, Optional, Union + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge + +from .config import OFTConfig + + +class MultiplicativeDropoutLayer(nn.Module): + """ + Implements the multiplicative dropout layer for OFT. + """ + + def __init__(self, p=0.0): + """ + Initializes the multiplicative dropout layer. + + Parameters: + p (float): The probability of dropping out a block. Defaults to 0.0. + """ + super().__init__() + self.p = p + + def forward(self, x): + """ + Applies multiplicative dropout to the input tensor. + + Parameters: + x (Tensor): The input tensor of shape (D, H, H), where `D` represents + the number of OFT blocks, and `H` is the size of the square blocks along the last two dimensions, + the block size in OFT. + """ + if self.training and self.p > 0: + # Ensure the last two dimensions are the same + if x.shape[-1] != x.shape[-2]: + raise ValueError("The last two dimensions of input should be the same!") + + D, H, _ = x.shape + + # If block share, skip the multiplicative dropout + if D == 1: + return x + + num_to_replace = int(self.p * D) + num_zeros = D - num_to_replace + mask = torch.cat([torch.ones(num_to_replace, device=x.device), torch.zeros(num_zeros, device=x.device)]) + mask = mask[torch.randperm(D)].view(D, 1, 1) + eye_matrix = torch.eye(H, device=x.device).repeat(D, 1, 1) + x = (1 - mask) * x + mask * eye_matrix + return x + + +class OFTRotationModule(nn.Module): + def __init__( + self, + r, + n_elements, + block_size, + in_features, + coft=False, + eps=6e-5, + block_share=False, + kernel_size=(0, 0), + use_cayley_neumann=True, + num_cayley_neumann_terms=5, + ): + super().__init__() + self.r = r + self.n_elements = n_elements + self.block_size = block_size + self.in_features = in_features + self.weight = nn.Parameter(torch.empty(r, n_elements)) + self.coft = coft + self.eps = eps + self.block_share = block_share + # Conv2d specific parameters + self.kernel_size = kernel_size + self.use_cayley_neumann = use_cayley_neumann + self.num_cayley_neumann_terms = num_cayley_neumann_terms + # Create indices for upper triangle (excluding diagonal) + rows, cols = torch.triu_indices(block_size, block_size, 1) + self.register_buffer("rows", rows, persistent=False) + self.register_buffer("cols", cols, persistent=False) + + def _pytorch_skew_symmetric(self, vec, block_size): + batch_size = vec.shape[0] + matrix = torch.zeros(batch_size, block_size, block_size, device=vec.device, dtype=vec.dtype) + + matrix[:, self.rows, self.cols] = vec + matrix = matrix - matrix.transpose(-2, -1) + return matrix + + def _pytorch_skew_symmetric_inv(self, matrix, block_size): + batch_size = matrix.shape[0] + + # Extract the upper triangular elements + vec = matrix[:, self.rows, self.cols] + return vec + + def _cayley_batch( + self, Q: torch.Tensor, block_size: int, use_cayley_neumann: bool = True, num_neumann_terms: int = 5 + ) -> torch.Tensor: + """ + Perform the Cayley parametrization on a batch of skew-symmetric matrices. + + Args: + data: A batch of skew-symmetric matrices of shape (b, r, c). + """ + + b, _ = Q.shape + previous_dtype = Q.dtype + + # Q_skew = SkewSymmetric.apply(Q, block_size) + Q_skew = self._pytorch_skew_symmetric(Q, block_size) + + if use_cayley_neumann: + R = torch.eye(block_size, device=Q.device, dtype=Q.dtype).repeat(b, 1, 1) + if num_neumann_terms > 1: + R.add_(Q_skew, alpha=2.0) + if num_neumann_terms > 2: + Q_squared = torch.bmm(Q_skew, Q_skew) + R.add_(Q_squared, alpha=2.0) + + Q_power = Q_squared + for _ in range(3, num_neumann_terms - 1): + Q_power = torch.bmm(Q_power, Q_skew) + R.add_(Q_power, alpha=2.0) + Q_power = torch.bmm(Q_power, Q_skew) + R.add_(Q_power) + else: + id_mat = ( + torch.eye(Q_skew.shape[-1], device=Q_skew.device) + .unsqueeze(0) + .expand(b, Q_skew.shape[-1], Q_skew.shape[-1]) + ) + R = torch.linalg.solve(id_mat + Q_skew, id_mat - Q_skew, left=False) + + return R.to(previous_dtype) + + # Copied from https://github.com/Zeju1997/oft/blob/84cebb965df69781e3d9c3c875f5980b421eaf24/oft-control/oft.py#L52 + def _project_batch(self, Q, eps=1e-5): + oft_R = self._pytorch_skew_symmetric(Q, self.block_size) + # scaling factor for each of the smaller block matrix + eps = eps * 1 / torch.sqrt(torch.tensor(oft_R.shape[0])) + I = ( # noqa: E741 + torch.zeros((oft_R.size(1), oft_R.size(1)), device=oft_R.device, dtype=oft_R.dtype) + .unsqueeze(0) + .expand_as(oft_R) + ) + diff = oft_R - I + norm_diff = torch.norm(oft_R - I, dim=(1, 2), keepdim=True) + mask = (norm_diff <= eps).bool() + out = torch.where(mask, oft_R, I + eps * (diff / norm_diff)) + + return self._pytorch_skew_symmetric_inv(out, self.block_size) + + # Copied from https://github.com/Zeju1997/oft/blob/84cebb965df69781e3d9c3c875f5980b421eaf24/oft-control/oft.py#L155 + def _block_diagonal(self, oft_R: torch.Tensor, rank: int) -> torch.Tensor: + if oft_R.shape[0] == 1: + # block share + blocks = [oft_R[0, ...] for i in range(rank)] + else: + blocks = [oft_R[i, ...] for i in range(rank)] + + # Use torch.block_diag to create the block diagonal matrix + A = torch.block_diag(*blocks) + + return A + + def _unfold(self, x): + """ + Unfold with stride=1, padding=0 to preserve spatial dimensions. Only use kernel_size from base layer to define + patch size. + """ + batch_size, in_channels, in_height, in_width = x.shape + + if isinstance(self.kernel_size, int): + kernel_height, kernel_width = self.kernel_size, self.kernel_size + else: + kernel_height, kernel_width = self.kernel_size + + stride_h = stride_w = 1 + pad_h = pad_w = 0 + + # output dimensions + out_height = (in_height + 2 * pad_h - kernel_height) // stride_h + 1 + out_width = (in_width + 2 * pad_w - kernel_width) // stride_w + 1 + + # Reshape input from [B, C, H, W] to [B, C, H_out, W_out, K_H, K_W] + x_unfolded = x.unfold(2, kernel_height, stride_h).unfold(3, kernel_width, stride_w) + x_unfolded = x_unfolded.permute(0, 2, 3, 1, 4, 5).contiguous() + x_unfolded = x_unfolded.view(batch_size * out_height * out_width, -1) + + return x_unfolded + + def _fold(self, x_unfolded, orig_shape): + """ + Fold back to preserve spatial dimensions. + """ + batch_size, in_channels, in_height, in_width = orig_shape + + if isinstance(self.kernel_size, int): + kernel_height, kernel_width = self.kernel_size, self.kernel_size + else: + kernel_height, kernel_width = self.kernel_size + + # With stride=1, padding=0: + out_height = in_height - kernel_height + 1 + out_width = in_width - kernel_width + 1 + + # Reshape: [B*H_out*W_out, C*K_H*K_W] -> [B, H_out, W_out, C, K_H, K_W] + x_reshaped = x_unfolded.view(batch_size, out_height, out_width, in_channels, kernel_height, kernel_width) + + # Permute to: [B, C, H_out, W_out, K_H, K_W] + x_reshaped = x_reshaped.permute(0, 3, 1, 2, 4, 5).contiguous() + + # Use F.fold to reconstruct 4D tensor + x_folded = F.fold( + x_reshaped.view(batch_size, in_channels * kernel_height * kernel_width, out_height * out_width), + output_size=(in_height, in_width), + kernel_size=(kernel_height, kernel_width), + stride=(1, 1), + ) + + return x_folded + + def forward(self, x): + # This module doesn't need to implement the orthogonal transform + # It's primarily a container for the parameter + # The actual transformation logic stays in your OFTLayer + + required_dtype = x.dtype + if required_dtype != self.weight.dtype: + x = x.to(self.weight.dtype) + + orig_shape = x.shape + + if self.coft: + with torch.no_grad(): + self.weight.copy_(self._project_batch(self.weight, eps=self.eps)) + + orth_rotate = self._cayley_batch( + self.weight, self.block_size, self.use_cayley_neumann, self.num_cayley_neumann_terms + ) + + # Unfold the input for Conv2d layer + if len(orig_shape) == 4: + x = self._unfold(x) + + folded_shape = x.shape + rank = self.in_features // self.block_size if self.block_share else self.r + batch_dims = x.shape[:-1] + x_reshaped = x.reshape(*batch_dims, rank, self.block_size) + + if self.block_share: + orth_rotate = orth_rotate.repeat(rank, 1, 1) + x_rotated_reshaped = torch.einsum("...rk,rkc->...rc", x_reshaped, orth_rotate) + else: + x_rotated_reshaped = torch.einsum("...rk,rkc->...rc", x_reshaped, orth_rotate) + + x_rotated = x_rotated_reshaped.reshape(*folded_shape) + + if len(orig_shape) == 4: + x_rotated = self._fold(x_rotated, orig_shape) + + return x_rotated.to(required_dtype) + + def get_weight(self): + """ + Compute the delta weight for the given adapter. + + Args: + adapter (str): + The name of the adapter for which the delta weight should be computed. + """ + weight = self.weight + + if self.coft: + with torch.no_grad(): + weight = self._project_batch(weight, eps=self.eps) + self.weight.copy_(weight) + + orth_rotate = self._cayley_batch( + weight, self.block_size, self.use_cayley_neumann, self.num_cayley_neumann_terms + ) + + rank = self.r if not self.block_share else self.in_features // self.block_size + return self._block_diagonal(orth_rotate, rank) + + +class OFTLayer(BaseTunerLayer): + """ + Implements the OFT layer. + """ + + # All names of layers that may contain (trainable) adapter weights + adapter_layer_names: tuple[str, ...] = ("oft_R", "oft_embedding_R") + # All names of other parameters that may contain adapter-related parameters + other_param_names: tuple[str, ...] = ("r", "oft_block_size", "oft_dropout") + + def __init__(self, base_layer: nn.Module, **kwargs) -> None: + """ + Initializes the OFT layer. + + Note, currently only support linear layer and convolutional layer, with further support for other layers to be + added soon. + + Parameters: + base_layer: the pretrained model layer + """ + self.base_layer = base_layer + self.oft_R = nn.ModuleDict({}) + # For Embedding layer + self.oft_embedding_R = nn.ModuleDict({}) + self.oft_block_size = {} + self.r = {} + self.oft_block_size = {} + self.oft_dropout = nn.ModuleDict({}) + # Mark the weight as unmerged + self._disable_adapters = False + self.merged_adapters = [] + # flag to enable/disable casting of input to weight dtype during forward call + self.cast_input_dtype_enabled = True + self.kwargs = kwargs + + base_layer = self.get_base_layer() + if isinstance(base_layer, nn.Linear): + in_features, out_features = base_layer.in_features, base_layer.out_features + elif isinstance(base_layer, nn.Conv2d): + in_features, out_features = base_layer.in_channels, base_layer.out_channels + elif isinstance(base_layer, nn.Embedding): + in_features, out_features = base_layer.embedding_dim, base_layer.num_embeddings + elif hasattr(base_layer, "infeatures") and hasattr(base_layer, "outfeatures"): + # QuantLinear + in_features, out_features = base_layer.infeatures, base_layer.outfeatures + elif hasattr(base_layer, "input_size") and hasattr(base_layer, "output_size"): + # Megatron ColumnParallelLinear,RowParallelLinear + in_features, out_features = base_layer.input_size, base_layer.output_size + elif hasattr(base_layer, "codebooks") and base_layer.__class__.__name__ == "QuantizedLinear": + # AQLM QuantLinear + in_features, out_features = base_layer.in_features, base_layer.out_features + elif hasattr(base_layer, "bits") and base_layer.__class__.__name__ == "AwqGEMMQuantLinear": + # Awq layers + in_features, out_features = base_layer.in_features, base_layer.out_features + elif base_layer.__class__.__name__ == "EetqLinear": + # Eetq layers + in_features, out_features = base_layer.in_features, base_layer.out_features + elif hasattr(base_layer, "W_q") and base_layer.__class__.__name__ == "HQQLinear": + # HQQ layers + in_features, out_features = base_layer.in_features, base_layer.out_features + else: + # possibly support user provided custom layer types using dynamic dispatch + if hasattr(base_layer, "in_features") and hasattr(base_layer, "out_features"): + in_features, out_features = base_layer.in_features, base_layer.out_features + else: + in_features, out_features = None, None + warnings.warn( + f"Unsupported layer type '{type(base_layer)}' encountered, proceed at your own risk.", UserWarning + ) + + self.in_features = in_features + self.out_features = out_features + + def set_scale(self, adapter, scale): + if adapter not in self.scaling: + # Ignore the case where the adapter is not in the layer + return + + warnings.warn("Scaling operation for OFT not supported! Automatically set scale to 1.") + + def scale_layer(self, scale: float) -> None: + if scale == 1: + return + + for active_adapter in self.active_adapters: + if active_adapter not in self.oft_R.keys(): + continue + + warnings.warn("Scaling operation for OFT not supported! Automatically set scale to 1.") + + def unscale_layer(self, scale=None) -> None: + for active_adapter in self.active_adapters: + if active_adapter not in self.oft_R.keys(): + continue + + warnings.warn("Unscaling operation for OFT not supported! Keeping scale to 1.") + + def update_layer( + self, + adapter_name, + r, + oft_block_size, + module_dropout, + coft, + eps, + block_share, + init_weights, + use_cayley_neumann, + num_cayley_neumann_terms, + inference_mode: bool = False, + **kwargs, + ): + """ + Update the linear layer with trainable OFT weights. Override for other layer types. + """ + """Internal function to create oft adapter + + Args: + adapter_name (`str`): Name for the adapter to add. + r (`int`): Rank for the added adapter. + oft_block_size (`int`): The block size for added adapter. + module_dropout (`float`): + The multiplicative dropout probability for disabling adapter blocks during training. + coft (`bool`): Whether to use the constrained variant of OFT or not. + eps (`float`): + The control strength of COFT. The freedom of rotation. Only has an effect if `coft` is set to True. + block_share (`bool`): Whether to share the OFT parameters between blocks or not. + init_weights (`bool`): Whether to initialize weights. + """ + # Initialize the MultiplicativeDropoutLayer for module_dropout > 0.0. + if module_dropout > 0.0: + oft_dropout_layer = MultiplicativeDropoutLayer(p=module_dropout) + else: + oft_dropout_layer = nn.Identity() + self.oft_dropout.update(nn.ModuleDict({adapter_name: oft_dropout_layer})) + + if r == 0 and oft_block_size != 0: + if self.in_features % oft_block_size != 0 or oft_block_size > self.in_features: + old_oft_block_size = oft_block_size + oft_block_size = self.adjust_oft_parameters(self.in_features, oft_block_size) + warnings.warn( + f"Invalid `oft_block_size` ({old_oft_block_size})! Adjusted `oft_block_size` to ({oft_block_size})." + ) + r = int(self.in_features // oft_block_size) + elif r != 0 and oft_block_size == 0: + if self.in_features % r != 0 or r > self.in_features: + old_r = r + r = self.adjust_oft_parameters(self.in_features, r) + warnings.warn(f"Invalid `r` ({old_r})! Adjusted `r` to ({r}).") + oft_block_size = int(self.in_features // r) + else: + raise ValueError( + "Something went wrong, please report this error: https://github.com/huggingface/peft/issues" + ) + + # Create weights with provided shape + n_elements = oft_block_size * (oft_block_size - 1) // 2 + self.oft_R[adapter_name] = OFTRotationModule( + r if not block_share else 1, + n_elements, + oft_block_size, + self.in_features, + coft=coft, + eps=eps, + block_share=block_share, + use_cayley_neumann=use_cayley_neumann, + num_cayley_neumann_terms=num_cayley_neumann_terms, + ) + + # Initialize weights + self.reset_oft_parameters(adapter_name, init_weights) + + # set oft r and block size + self.r[adapter_name] = r + self.oft_block_size[adapter_name] = oft_block_size + + # Move new weights to device + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def reset_oft_parameters(self, adapter_name, init_weights): + """ + Reset the OFT parameters. + """ + if init_weights is False: + if adapter_name in self.oft_R.keys(): + nn.init.normal_(self.oft_R[adapter_name].weight, mean=0.0, std=0.1) + return + if adapter_name in self.oft_embedding_R.keys(): + nn.init.normal_(self.oft_embedding_R[adapter_name].weight, mean=0.0, std=0.1) + return + + if adapter_name in self.oft_R.keys(): + if init_weights is True: + # initialize oft_R to zero + nn.init.zeros_(self.oft_R[adapter_name].weight) + else: + raise ValueError(f"Unknown initialization {init_weights=}") + if adapter_name in self.oft_embedding_R.keys(): + if init_weights is True: + # initialize oft_embedding_R to zero + nn.init.zeros_(self.oft_embedding_R[adapter_name].weight) + else: + raise ValueError(f"Unknown initialization {init_weights=}") + + def adjust_oft_parameters(self, in_features, params): + """ + Adjust the OFT parameters to be divisible by the in_features dimension. + """ + if params < in_features: + higher_params = params + while higher_params <= in_features and in_features % higher_params != 0: + higher_params += 1 + else: + return in_features + + lower_params = params + while lower_params > 1 and in_features % lower_params != 0: + lower_params -= 1 + + if (params - lower_params) <= (higher_params - params): + return lower_params + else: + return higher_params + + +class Linear(nn.Module, OFTLayer): + """OFT implemented in Linear layer""" + + def __init__( + self, + base_layer, + adapter_name: str, + r: int = 8, + oft_block_size: int = 0, + module_dropout: float = 0.0, + coft: bool = False, + eps: float = 6e-5, + block_share: bool = False, + use_cayley_neumann: bool = False, + num_cayley_neumann_terms: int = 5, + fan_in_fan_out: bool = False, # Set this to True if the layer to replace stores weight like (fan_in, fan_out) + init_weights: Union[bool, str] = True, + is_target_conv_1d_layer: bool = False, + **kwargs, + ) -> None: + super().__init__() + OFTLayer.__init__(self, base_layer, **kwargs) + self.fan_in_fan_out = fan_in_fan_out + + self._active_adapter = adapter_name + + self.update_layer( + adapter_name, + r, + oft_block_size=oft_block_size, + module_dropout=module_dropout, + coft=coft, + eps=eps, + block_share=block_share, + init_weights=init_weights, + use_cayley_neumann=use_cayley_neumann, + num_cayley_neumann_terms=num_cayley_neumann_terms, + ) + self.is_target_conv_1d_layer = is_target_conv_1d_layer + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If `True`, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`List[str]`, *optional*): + The list of adapter names that should be merged. If `None`, all active adapters will be merged. + Defaults to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter in self.oft_R.keys(): + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.dtype + if safe_merge: + # Note that safe_merge will be slower than the normal merge + orig_weights = base_layer.weight.data + oft_mat = self.get_delta_weight(active_adapter) + orig_weights = torch.transpose(orig_weights, 0, 1) + orig_weights = torch.mm(oft_mat, orig_weights.to(oft_mat.dtype)) + orig_weights = torch.transpose(orig_weights, 0, 1) + + if not torch.isfinite(orig_weights).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = orig_weights.contiguous().to(orig_dtype) + else: + orig_weights = base_layer.weight.data + oft_mat = self.get_delta_weight(active_adapter) + orig_weights = torch.transpose(orig_weights, 0, 1) + orig_weights = torch.mm(oft_mat, orig_weights.to(oft_mat.dtype)) + orig_weights = torch.transpose(orig_weights, 0, 1) + + base_layer.weight.data = orig_weights.contiguous().to(orig_dtype) + + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.dtype + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter in self.oft_R.keys(): + oft_mat = self.get_delta_weight(active_adapter) + + previous_dtype = oft_mat.dtype + if previous_dtype != torch.float32: + oft_mat = oft_mat.to(torch.float32) + + orig_weights = self.get_base_layer().weight.data + orig_weights = torch.transpose(orig_weights, 0, 1) + orig_weights = torch.mm(torch.linalg.inv(oft_mat).to(previous_dtype), orig_weights.to(previous_dtype)) + orig_weights = torch.transpose(orig_weights, 0, 1) + + base_layer.weight.data = orig_weights.to(orig_dtype) + + def get_delta_weight(self, adapter) -> torch.Tensor: + """ + Compute the delta weight for the given adapter. + + Args: + adapter (str): + The name of the adapter for which the delta weight should be computed. + """ + device = self.oft_R[adapter].weight.device + dtype = self.oft_R[adapter].weight.dtype + + # In case users wants to merge the adapter weights that are in + # (b)float16 while being on CPU, we need to cast the weights to float32, perform the merge and then cast back to + # (b)float16 because some CPUs have slow bf16/fp16 matmuls. + cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16) + + oft_R_module = self.oft_R[adapter] + + if cast_to_fp32: + # Temporarily work in fp32 for faster CPU matmul + original_weight = oft_R_module.weight.data + oft_R_module.weight.data = oft_R_module.weight.data.float() + oft_mat = oft_R_module.get_weight() + oft_R_module.weight.data = original_weight # restore + return oft_mat.to(dtype) + else: + return oft_R_module.get_weight() + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + previous_dtype = x.dtype + + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + for active_adapter in self.active_adapters: + if active_adapter not in self.oft_R.keys(): + continue + oft_R = self.oft_R[active_adapter] + + x = self._cast_input_dtype(x, oft_R.weight.dtype) + x = oft_R(x) + + result = self.base_layer(x.to(previous_dtype), *args, **kwargs) + + result = result.to(previous_dtype) + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "oft." + rep + + +class Conv2d(nn.Module, OFTLayer): + """OFT implemented in Conv2d layer""" + + def __init__( + self, + base_layer: nn.Module, + adapter_name: str, + r: int = 8, + oft_block_size: int = 0, + fan_in_fan_out: bool = False, # Set this to True if the layer to replace stores weight like (fan_in, fan_out) + module_dropout: float = 0.0, + coft: bool = False, + eps: float = 6e-5, + block_share: bool = False, + init_weights: Union[bool, str] = True, + use_cayley_neumann: bool = False, + num_cayley_neumann_terms: int = 5, + **kwargs, + ) -> None: + super().__init__() + OFTLayer.__init__(self, base_layer) + self.fan_in_fan_out = fan_in_fan_out + + self._active_adapter = adapter_name + + # Create adapter and set it active + self.update_layer( + adapter_name, + r, + oft_block_size=oft_block_size, + module_dropout=module_dropout, + coft=coft, + eps=eps, + block_share=block_share, + init_weights=init_weights, + use_cayley_neumann=use_cayley_neumann, + num_cayley_neumann_terms=num_cayley_neumann_terms, + ) + + def update_layer( + self, + adapter_name, + r, + oft_block_size, + module_dropout, + coft, + eps, + block_share, + init_weights, + use_cayley_neumann, + num_cayley_neumann_terms, + inference_mode: bool = False, + **kwargs, + ): + """ + Update the conv2d layer with trainable OFT weights. + """ + # Initialize the MultiplicativeDropoutLayer for module_dropout > 0.0. + if module_dropout > 0.0: + oft_dropout_layer = MultiplicativeDropoutLayer(p=module_dropout) + else: + oft_dropout_layer = nn.Identity() + self.oft_dropout.update(nn.ModuleDict({adapter_name: oft_dropout_layer})) + + # layer information from the base layer + base_layer = self.get_base_layer() + if base_layer.dilation[0] > 1: + raise ValueError("Conv2d with dilation > 1 is not supported by OFT.") + + conv_filter_dim = self.in_features * base_layer.kernel_size[0] * base_layer.kernel_size[0] + + if r == 0 and oft_block_size != 0: + if conv_filter_dim % oft_block_size != 0 or oft_block_size > conv_filter_dim: + old_oft_block_size = oft_block_size + oft_block_size = self.adjust_oft_parameters(conv_filter_dim, oft_block_size) + warnings.warn( + f"Invalid `oft_block_size` ({old_oft_block_size})! Adjusted `oft_block_size` to ({oft_block_size})." + ) + r = int(conv_filter_dim // oft_block_size) + elif r != 0 and oft_block_size == 0: + if conv_filter_dim % r != 0 or r > conv_filter_dim: + old_r = r + r = self.adjust_oft_parameters(conv_filter_dim, r) + warnings.warn(f"Invalid `r` ({old_r})! Adjusted `r` to ({r}).") + oft_block_size = int(conv_filter_dim // r) + else: + raise ValueError( + "Something went wrong, please report this error: https://github.com/huggingface/peft/issues" + ) + + # Create weights with provided shape + n_elements = oft_block_size * (oft_block_size - 1) // 2 + self.oft_R[adapter_name] = OFTRotationModule( + r if not block_share else 1, + n_elements, + oft_block_size, + conv_filter_dim, + coft=coft, + eps=eps, + block_share=block_share, + kernel_size=base_layer.kernel_size, + use_cayley_neumann=use_cayley_neumann, + num_cayley_neumann_terms=num_cayley_neumann_terms, + ) + + # Initialize weights + self.reset_oft_parameters(adapter_name, init_weights) + + # set oft r and block size + self.r[adapter_name] = r + self.oft_block_size[adapter_name] = oft_block_size + + # Move new weights to device + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`List[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults + to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter in self.oft_R.keys(): + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.dtype + if safe_merge: + # Note that safe_merge will be slower than the normal merge + # because of the copy operation. + orig_weights = base_layer.weight.data.clone() + oft_mat = self.get_delta_weight(active_adapter) + + orig_weights = orig_weights.view( + self.out_features, self.in_features * base_layer.kernel_size[0] * base_layer.kernel_size[0] + ) + orig_weights = torch.transpose(orig_weights, 0, 1) + orig_weights = torch.mm(oft_mat, orig_weights.to(oft_mat.dtype)) + orig_weights = torch.transpose(orig_weights, 0, 1) + orig_weights = orig_weights.view( + self.out_features, self.in_features, base_layer.kernel_size[0], base_layer.kernel_size[0] + ) + + base_layer.weight.data = orig_weights.contiguous().to(orig_dtype) + else: + oft_mat = self.get_delta_weight(active_adapter) + + orig_weights = base_layer.weight.data.clone() + orig_weights = orig_weights.view( + self.out_features, self.in_features * base_layer.kernel_size[0] * base_layer.kernel_size[0] + ) + orig_weights = torch.transpose(orig_weights, 0, 1) + orig_weights = torch.mm(oft_mat, orig_weights.to(oft_mat.dtype)) + orig_weights = torch.transpose(orig_weights, 0, 1) + orig_weights = orig_weights.view( + self.out_features, self.in_features, base_layer.kernel_size[0], base_layer.kernel_size[0] + ) + + base_layer.weight.data = orig_weights.contiguous().to(orig_dtype) + + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.dtype + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter in self.oft_R.keys(): + oft_mat = self.get_delta_weight(active_adapter) + + previous_dtype = oft_mat.dtype + if previous_dtype != torch.float32: + oft_mat = oft_mat.to(torch.float32) + + orig_weights = self.get_base_layer().weight.data.clone() + orig_weights = orig_weights.view( + self.out_features, + self.in_features * self.get_base_layer().kernel_size[0] * self.get_base_layer().kernel_size[0], + ) + orig_weights = torch.transpose(orig_weights, 0, 1) + orig_weights = torch.mm(torch.linalg.inv(oft_mat).to(previous_dtype), orig_weights.to(previous_dtype)) + orig_weights = torch.transpose(orig_weights, 0, 1) + orig_weights = orig_weights.view( + self.out_features, + self.in_features, + self.get_base_layer().kernel_size[0], + self.get_base_layer().kernel_size[0], + ) + + base_layer.weight.data = orig_weights.to(orig_dtype) + + def get_delta_weight(self, adapter) -> torch.Tensor: + """ + Compute the delta weight for the given adapter. + + Args: + adapter (str): + The name of the adapter for which the delta weight should be computed. + """ + device = self.oft_R[adapter].weight.device + dtype = self.oft_R[adapter].weight.dtype + + # In case users wants to merge the adapter weights that are in + # (b)float16 while being on CPU, we need to cast the weights to float32, perform the merge and then cast back to + # (b)float16 because some CPUs have slow bf16/fp16 matmuls. + cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16) + + oft_R_module = self.oft_R[adapter] + + if cast_to_fp32: + # Temporarily work in fp32 for faster CPU matmul + original_weight = oft_R_module.weight.data + oft_R_module.weight.data = oft_R_module.weight.data.float() + oft_mat = oft_R_module.get_weight() + oft_R_module.weight.data = original_weight # restore + return oft_mat.to(dtype) + else: + return oft_R_module.get_weight() + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + previous_dtype = x.dtype + + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + for active_adapter in self.active_adapters: + if active_adapter not in self.oft_R.keys(): + continue + + oft_R = self.oft_R[active_adapter] + x = self._cast_input_dtype(x, oft_R.weight.dtype) + x = oft_R(x) + + result = self.base_layer(x.to(previous_dtype), *args, **kwargs) + + result = result.to(previous_dtype) + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "oft." + rep + + +class Embedding(nn.Module, OFTLayer): + # OFT implemented in a Embedding layer + def __init__( + self, + base_layer: nn.Module, + adapter_name: str, + r: int = 8, + oft_block_size: int = 0, + module_dropout: float = 0.0, + coft: bool = False, + eps: float = 6e-5, + block_share: bool = False, + use_cayley_neumann: bool = False, + num_cayley_neumann_terms: int = 5, + fan_in_fan_out: bool = False, # unused for embedding, kept for API parity + init_weights: Union[bool, str] = True, + **kwargs, + ) -> None: + super().__init__() + OFTLayer.__init__(self, base_layer) + self.fan_in_fan_out = fan_in_fan_out + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + r, + oft_block_size=oft_block_size, + module_dropout=module_dropout, + coft=coft, + eps=eps, + block_share=block_share, + init_weights=init_weights, + use_cayley_neumann=use_cayley_neumann, + num_cayley_neumann_terms=num_cayley_neumann_terms, + ) + + def update_layer( + self, + adapter_name, + r, + oft_block_size, + module_dropout, + coft, + eps, + block_share, + init_weights, + use_cayley_neumann, + num_cayley_neumann_terms, + inference_mode: bool = False, + **kwargs, + ): + # collect the kwargs + kwargs = locals().copy() + del kwargs["self"] + + if r == 0 and oft_block_size != 0: + if self.in_features % oft_block_size != 0 or oft_block_size > self.in_features: + old_oft_block_size = oft_block_size + oft_block_size = self.adjust_oft_parameters(self.in_features, oft_block_size) + warnings.warn( + f"Invalid `oft_block_size` ({old_oft_block_size})! Adjusted `oft_block_size` to ({oft_block_size})." + ) + r = int(self.in_features // oft_block_size) + elif r != 0 and oft_block_size == 0: + if self.in_features % r != 0 or r > self.in_features: + old_r = r + r = self.adjust_oft_parameters(self.in_features, r) + warnings.warn(f"Invalid `r` ({old_r})! Adjusted `r` to ({r}).") + oft_block_size = int(self.in_features // r) + else: + raise ValueError( + "Something went wrong, please report this error: https://github.com/huggingface/peft/issues" + ) + + # Create weights with provided shape + n_elements = oft_block_size * (oft_block_size - 1) // 2 + self.oft_embedding_R[adapter_name] = OFTRotationModule( + r if not block_share else 1, + n_elements, + oft_block_size, + self.in_features, + coft=coft, + eps=eps, + block_share=block_share, + use_cayley_neumann=use_cayley_neumann, + num_cayley_neumann_terms=num_cayley_neumann_terms, + ) + + # Initialize weights + self.reset_oft_parameters(adapter_name, init_weights) + + # set oft r and block size + self.r[adapter_name] = r + self.oft_block_size[adapter_name] = oft_block_size + + # Move new weights to device + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`list[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults + to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter in self.oft_embedding_R.keys(): + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.dtype + if safe_merge: + # Note that safe_merge will be slower than the normal merge + orig_weights = base_layer.weight.data + oft_mat = self.get_delta_weight(active_adapter) + orig_weights = torch.mm(orig_weights.to(oft_mat.dtype), oft_mat) + + if not torch.isfinite(orig_weights).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = orig_weights.contiguous().to(orig_dtype) + else: + orig_weights = base_layer.weight.data + oft_mat = self.get_delta_weight(active_adapter) + orig_weights = torch.mm(orig_weights.to(oft_mat.dtype), oft_mat) + + base_layer.weight.data = orig_weights.contiguous().to(orig_dtype) + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.dtype + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter in self.oft_embedding_R.keys(): + oft_mat = self.get_delta_weight(active_adapter) + + previous_dtype = oft_mat.dtype + if previous_dtype != torch.float32: + oft_mat = oft_mat.to(torch.float32) + + orig_weights = self.get_base_layer().weight.data + orig_weights = torch.mm(orig_weights.to(oft_mat.dtype), torch.linalg.inv(oft_mat)) + + base_layer.weight.data = orig_weights.to(orig_dtype) + + def get_delta_weight(self, adapter) -> torch.Tensor: + """ + Compute the delta weight for the given adapter. + + Args: + adapter (str): + The name of the adapter for which the delta weight should be computed. + """ + device = self.oft_embedding_R[adapter].weight.device + dtype = self.oft_embedding_R[adapter].weight.dtype + + # In case users wants to merge the adapter weights that are in + # (b)float16 while being on CPU, we need to cast the weights to float32, perform the merge and then cast back to + # (b)float16 because some CPUs have slow bf16/fp16 matmuls. + cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16) + + oft_R_module = self.oft_embedding_R[adapter] + + if cast_to_fp32: + # Temporarily work in fp32 for faster CPU matmul + original_weight = oft_R_module.weight.data + oft_R_module.weight.data = oft_R_module.weight.data.float() + oft_mat = oft_R_module.get_weight() + oft_R_module.weight.data = original_weight # restore + return oft_mat.to(dtype) + else: + return oft_R_module.get_weight() + + def _embed(self, input: torch.Tensor, weight: torch.Tensor) -> torch.Tensor: + base_layer = self.get_base_layer() + return F.embedding( + input, + weight, + padding_idx=base_layer.padding_idx, + max_norm=base_layer.max_norm, + norm_type=base_layer.norm_type, + scale_grad_by_freq=base_layer.scale_grad_by_freq, + sparse=base_layer.sparse, + ) + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + # x is token ids (usually LongTensor); rotation is applied to embedding outputs + if self.disable_adapters: + if self.merged: + self.unmerge() + return self.base_layer(x, *args, **kwargs) + if self.merged: + return self.base_layer(x, *args, **kwargs) + + result = self.base_layer(x, *args, **kwargs) + out_dtype = result.dtype + + for active_adapter in self.active_adapters: + if active_adapter not in self.oft_embedding_R: + continue + oft_embedding_R = self.oft_embedding_R[active_adapter] + result = self._cast_input_dtype(result, oft_embedding_R.weight.dtype) + result = oft_embedding_R(result) + + return result.to(out_dtype) + + def __repr__(self) -> str: + rep = super().__repr__() + return "oft." + rep + + +def dispatch_default( + target: torch.nn.Module, + adapter_name: str, + oft_config: OFTConfig, + **kwargs, +) -> Optional[torch.nn.Module]: + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if isinstance(target_base_layer, torch.nn.Conv2d): + new_module = Conv2d(target, adapter_name, **kwargs) + elif isinstance(target_base_layer, torch.nn.Linear): + if kwargs["fan_in_fan_out"]: + warnings.warn( + "fan_in_fan_out is set to True but the target module is `torch.nn.Linear`. " + "Setting fan_in_fan_out to False." + ) + kwargs["fan_in_fan_out"] = oft_config.fan_in_fan_out = False + new_module = Linear(target, adapter_name, **kwargs) + elif isinstance(target_base_layer, torch.nn.Embedding): + embedding_kwargs = kwargs.copy() + embedding_kwargs.pop("fan_in_fan_out", None) + new_module = Embedding(target, adapter_name, **embedding_kwargs) + + return new_module diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/model.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/model.py new file mode 100644 index 0000000000000000000000000000000000000000..2b4b20f24bf13d9c8067b933714ae8d8061406ab --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/oft/model.py @@ -0,0 +1,200 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available +from peft.tuners.tuners_utils import ( + BaseTuner, + get_device_map, +) +from peft.utils import ( + TRANSFORMERS_MODELS_TO_OFT_TARGET_MODULES_MAPPING, + get_quantization_config, +) + +from .aqlm import dispatch_aqlm +from .awq import dispatch_awq +from .eetq import dispatch_eetq +from .gptq import dispatch_gptq +from .hqq import dispatch_hqq +from .inc import dispatch_inc +from .layer import OFTLayer, dispatch_default + + +class OFTModel(BaseTuner): + """ + Creates Orthogonal Finetuning model from a pretrained model. The method is described in + https://huggingface.co/papers/2306.07280 + + Args: + model (`torch.nn.Module`): The model to which the adapter tuner layers will be attached. + config ([`OFTConfig`]): The configuration of the OFT model. + adapter_name (`str`): The name of the adapter, defaults to `"default"`. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the loading process. + + Returns: + `torch.nn.Module`: The OFT model. + + Example: + ```py + >>> from diffusers import StableDiffusionPipeline + >>> from peft import OFTModel, OFTConfig + + >>> config_te = OFTConfig( + ... r=8, + ... target_modules=["k_proj", "q_proj", "v_proj", "out_proj", "fc1", "fc2"], + ... module_dropout=0.0, + ... init_weights=True, + ... ) + >>> config_unet = OFTConfig( + ... r=8, + ... target_modules=[ + ... "proj_in", + ... "proj_out", + ... "to_k", + ... "to_q", + ... "to_v", + ... "to_out.0", + ... "ff.net.0.proj", + ... "ff.net.2", + ... ], + ... module_dropout=0.0, + ... init_weights=True, + ... ) + + >>> model = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5") + >>> model.text_encoder = OFTModel(model.text_encoder, config_te, "default") + >>> model.unet = OFTModel(model.unet, config_unet, "default") + ``` + + **Attributes**: + - **model** ([`~torch.nn.Module`]) -- The model to be adapted. + - **peft_config** ([`OFTConfig`]): The configuration of the OFT model. + """ + + prefix: str = "oft_" + tuner_layer_cls = OFTLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_OFT_TARGET_MODULES_MAPPING + + def _create_and_replace( + self, + oft_config, + adapter_name, + target, + target_name, + parent, + current_key, + **optional_kwargs, + ): + if current_key is None: + raise ValueError("Current Key shouldn't be `None`") + + kwargs = { + "r": oft_config.r, + "oft_block_size": oft_config.oft_block_size, + "module_dropout": oft_config.module_dropout, + "coft": oft_config.coft, + "eps": oft_config.eps, + "block_share": oft_config.block_share, + "use_cayley_neumann": oft_config.use_cayley_neumann, + "num_cayley_neumann_terms": oft_config.num_cayley_neumann_terms, + "fan_in_fan_out": oft_config.fan_in_fan_out, + "init_weights": oft_config.init_weights, + "loaded_in_8bit": getattr(self.model, "is_loaded_in_8bit", False), + "loaded_in_4bit": getattr(self.model, "is_loaded_in_4bit", False), + } + + quant_methods = ["gptq", "aqlm", "awq"] + for quant_method in quant_methods: + quantization_config = get_quantization_config(self.model, method=quant_method) + if quantization_config is not None: + kwargs[f"{quant_method}_quantization_config"] = quantization_config + + # If it is not a OFTLayer, create a new module, else update it with new adapters + if not isinstance(target, OFTLayer): + device_map = get_device_map(self.model) + new_module = self._create_new_module(oft_config, adapter_name, target, device_map=device_map, **kwargs) + if adapter_name not in self.active_adapters: + # adding an additional adapter: it is not automatically trainable + new_module.requires_grad_(False) + self._replace_module(parent, target_name, new_module, target) + else: + target.update_layer( + adapter_name, + r=oft_config.r, + oft_block_size=oft_config.oft_block_size, + module_dropout=oft_config.module_dropout, + coft=oft_config.coft, + eps=oft_config.eps, + block_share=oft_config.block_share, + use_cayley_neumann=oft_config.use_cayley_neumann, + num_cayley_neumann_terms=oft_config.num_cayley_neumann_terms, + init_weights=oft_config.init_weights, + ) + + @staticmethod + def _create_new_module(oft_config, adapter_name, target, **kwargs): + # Collect dispatcher functions to decide what backend to use for the replaced OFT layer. The order matters, + # because the first match is always used. Therefore, the default layers should be checked last. + dispatchers = [] + + # avoid eager bnb import + if is_bnb_available(): + from .bnb import dispatch_bnb_8bit + + dispatchers.append(dispatch_bnb_8bit) + + if is_bnb_4bit_available(): + from .bnb import dispatch_bnb_4bit + + dispatchers.append(dispatch_bnb_4bit) + + dispatchers.extend( + [ + dispatch_eetq, + dispatch_aqlm, + dispatch_awq, + dispatch_gptq, + dispatch_hqq, + dispatch_inc, + dispatch_default, + ] + ) + + new_module = None + for dispatcher in dispatchers: + new_module = dispatcher(target, adapter_name, oft_config=oft_config, **kwargs) + if new_module is not None: # first match wins + break + + if new_module is None: + # no module could be matched + raise ValueError( + f"Target module {target} is not supported. Currently, only the following modules are supported: " + "`torch.nn.Linear`, `torch.nn.Conv2d`." + ) + + return new_module + + def _check_merge_allowed(self): + """Verify that the configuration supports merging. + + Currently gptq quantization and replicated layers do not support merging. + """ + super()._check_merge_allowed() + if getattr(self.model, "quantization_method", None) == "gptq": + raise ValueError("Cannot merge OFT layers when the model is gptq quantized") + if self.peft_config.get("layer_replication"): + raise ValueError("Cannot merge OFT layers when base model layers are replicated") diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..801e93fc5380e6fc2ae48798e6650a9a41cb2dcc --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/__init__.py @@ -0,0 +1,15 @@ +from peft.utils import register_peft_method + +from .config import OSFConfig +from .layer import Linear, OSFLayer +from .model import OSFModel + + +__all__ = ["Linear", "OSFConfig", "OSFLayer", "OSFModel"] + +register_peft_method( + name="osf", + config_cls=OSFConfig, + model_cls=OSFModel, + is_mixed_compatible=False, +) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24f40e1b6dd60905f5b61a616e6022f84840def9 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/__pycache__/config.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/__pycache__/config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b67ef16b0425a74f1fd6ef7964e24e08392b8429 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/__pycache__/config.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/__pycache__/layer.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/__pycache__/layer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..550ec18a0f82e24c1aebe29cc53292e16a568126 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/__pycache__/layer.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/__pycache__/model.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/__pycache__/model.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf1c363d44c6ec6775896e56fa5c069380f574e1 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/__pycache__/model.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/__pycache__/utils.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa95f62e1adb9bda4fcb238a9923023a8111eab6 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/__pycache__/utils.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/config.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/config.py new file mode 100644 index 0000000000000000000000000000000000000000..77a08964d4fce411870e088879f6a5a8b4d993c8 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/config.py @@ -0,0 +1,80 @@ +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class OSFConfig(PeftConfig): + """ + Configuration for Orthogonal Subspace Fine-tuning (OSF). + + Args: + effective_rank (`int` or `float`, *optional*): + Preserved SVD rank ("high" subspace). The top-``effective_rank`` singular directions are frozen and + retained across tasks; the remaining dimensions form the trainable low-rank subspace. If `None`, defaults + to 50% of the smaller weight dimension per target module. Note: This differs from LoRA's `r` (trainable + rank). In OSF, the trainable rank is `min(weight.shape) - effective_rank`. + target_modules (`Union[list[str], str]`, *optional*): + The names of the modules to apply OSF to. Can be a list of module names or `"all-linear"`. + rank_pattern (`dict[str, int|float]`, *optional*): + A dictionary of regex patterns to override `effective_rank` for specific modules. Values can be absolute + integers or fractions in (0, 1], interpreted as a fraction of the smaller matrix dimension per target. + """ + + effective_rank: Optional[Union[int, float]] = field( + default=None, + metadata={ + "help": ( + 'Preserved SVD rank ("high" subspace). The top-`effective_rank` singular directions are frozen ' + "and retained across tasks; the remaining dimensions form the trainable low-rank subspace. " + "Trainable rank equals min(weight.shape) - effective_rank. If None, defaults to 50% of the smaller " + "weight dimension per target module. Floats in (0, 1] are interpreted as a fraction of the smaller " + "matrix dimension per target." + ) + }, + ) + target_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={"help": "The names of the modules to apply OSF to. Can be a list of module names or 'all-linear'."}, + ) + rank_pattern: Optional[dict[str, Union[int, float]]] = field( + default=None, + metadata={ + "help": ( + "A dictionary of regex patterns to override effective_rank per module. Values can be absolute " + "integers or fractions in (0, 1], interpreted as a fraction of the smaller matrix dimension." + ) + }, + ) + + # Additional optional fields for compatibility with generic test harnesses + init_weights: Optional[bool] = field( + default=None, + metadata={ + "help": ( + "If provided, toggles custom weight initialization behavior for certain methods. OSF ignores this " + "flag but accepts it for config compatibility." + ) + }, + ) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={"help": "Optional list of module names to save separately (ignored by OSF but accepted)."}, + ) + target_svd_config: Optional[dict[str, int]] = field( + default=None, + metadata={ + "help": ( + "Optional per-parameter SVD target rank mapping (e.g., {'lin0.weight': 8}). OSF currently ignores " + "this field but accepts it for forward compatibility." + ) + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.OSF diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/layer.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..d0fe153e5c1db73da5f853c8ddaf66232f4e0488 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/layer.py @@ -0,0 +1,289 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import warnings +from functools import partial +from typing import Any, Optional + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from peft.tuners._buffer_dict import BufferDict +from peft.tuners.tuners_utils import BaseTunerLayer + +from .utils import ( + decompose_weight_matrix, + reconstruct_weight_matrix, +) + + +class OSFLayer(BaseTunerLayer): + # All names of layers that may contain (trainable) adapter weights + adapter_layer_names: tuple[str, ...] = ("osf_svd_params",) + # All names of other parameters that may contain adapter-related parameters + other_param_names: tuple[str, ...] = ("_osf_U_high", "_osf_S_high", "_osf_V_high") + + def __init__(self, base_layer: nn.Module, **kwargs) -> None: + self.base_layer = base_layer + self.effective_rank = {} + # Map adapter_name -> ParameterDict{"U_low", "S_low", "V_low"} + self.osf_svd_params = nn.ModuleDict({}) + # Store high-rank (frozen) components as buffers that track device moves + self._osf_U_high = BufferDict({}) + self._osf_S_high = BufferDict({}) + self._osf_V_high = BufferDict({}) + # Track hook handles for cleanup + self.hook_handles = [] + # Mark the weight as unmerged + self._disable_adapters = False + self.merged_adapters = [] + + # Get layer dimensions + base_layer = self.get_base_layer() + # Prefer the universally available weight shape when possible. + if ( + hasattr(base_layer, "weight") + and isinstance(base_layer.weight, torch.Tensor) + and base_layer.weight.ndim == 2 + ): + # For Linear-like modules, weight is [out_features, in_features] + out_features, in_features = base_layer.weight.shape + elif isinstance(base_layer, nn.Linear): + in_features, out_features = base_layer.in_features, base_layer.out_features + elif hasattr(base_layer, "infeatures") and hasattr(base_layer, "outfeatures"): + # QuantLinear + in_features, out_features = base_layer.infeatures, base_layer.outfeatures + elif hasattr(base_layer, "input_size") and hasattr(base_layer, "output_size"): + # Megatron ColumnParallelLinear, RowParallelLinear + in_features, out_features = base_layer.input_size, base_layer.output_size + elif hasattr(base_layer, "in_features") and hasattr(base_layer, "out_features"): + in_features, out_features = base_layer.in_features, base_layer.out_features + else: + in_features, out_features = None, None + warnings.warn( + f"Unsupported layer type '{type(base_layer)}' encountered; could not infer in/out features.", + UserWarning, + ) + + self.in_features = in_features + self.out_features = out_features + + def update_layer(self, adapter_name: str, effective_rank: int, **kwargs): + """Update layer to add a new OSF adapter.""" + if effective_rank <= 0: + raise ValueError( + f"`effective_rank` should be a positive integer value but the value passed is {effective_rank}" + ) + + # Store the rank for this adapter + self.effective_rank[adapter_name] = effective_rank + + # Perform SVD decomposition on the base layer weight + base_layer = self.get_base_layer() + weight = base_layer.weight.data + svd_dict = decompose_weight_matrix(weight, top_k=effective_rank) + + # Store high-rank (frozen) components as buffers + self._osf_U_high[adapter_name] = svd_dict["U_high"] + self._osf_S_high[adapter_name] = svd_dict["S_high"] + self._osf_V_high[adapter_name] = svd_dict["V_high"] + + # Create ParameterDict for trainable low-rank components + svd_params = nn.ParameterDict( + { + "U_low": svd_dict["U_low"], + "S_low": svd_dict["S_low"], + "V_low": svd_dict["V_low"], + } + ) + self.osf_svd_params[adapter_name] = svd_params + + # Attach gradient hooks for orthogonal projection + self._attach_hooks(adapter_name) + + # Set the adapter as active + self.set_adapter(self.active_adapters) + + def _attach_hooks(self, adapter_name: str): + """Attach gradient hooks for the given adapter.""" + if adapter_name not in self.osf_svd_params: + return + + svd_module = self.osf_svd_params[adapter_name] + + def hook(grad, name: str, adapter: str, layer: OSFLayer): + # Project gradient to be orthogonal to high-rank subspace for U_low/V_low + # Access buffers dynamically to ensure they're on the correct device + if name == "U_low": + U_high = layer._osf_U_high[adapter] + proj = U_high @ (U_high.transpose(0, 1) @ grad) + return grad - proj + elif name == "V_low": + V_high = layer._osf_V_high[adapter] + proj = (grad @ V_high.transpose(0, 1)) @ V_high + return grad - proj + return grad + + # Store hook handles for later cleanup + handle_u = svd_module["U_low"].register_hook(partial(hook, name="U_low", adapter=adapter_name, layer=self)) + handle_v = svd_module["V_low"].register_hook(partial(hook, name="V_low", adapter=adapter_name, layer=self)) + + self.hook_handles.extend([handle_u, handle_v]) + + def _detach_hooks(self): + """Remove all gradient hooks.""" + for handle in self.hook_handles: + handle.remove() + self.hook_handles.clear() + + def _reconstruct_weight(self, adapter_name: str) -> torch.Tensor: + """Reconstruct weight matrix from SVD components for given adapter.""" + if adapter_name not in self.osf_svd_params: + return self.get_base_layer().weight + + svd_module = self.osf_svd_params[adapter_name] + svd_dict = { + "U_high": self._osf_U_high[adapter_name], + "S_high": self._osf_S_high[adapter_name], + "V_high": self._osf_V_high[adapter_name], + "U_low": svd_module["U_low"], + "S_low": svd_module["S_low"], + "V_low": svd_module["V_low"], + } + return reconstruct_weight_matrix(svd_dict) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`list[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults + to `None`. + """ + if adapter_names is None: + adapter_names = self.active_adapters + + for active_adapter in adapter_names: + if active_adapter in self.osf_svd_params.keys(): + base_layer = self.get_base_layer() + if safe_merge: + # Note that safe_merge will be slower than the normal merge + # because of the copy operation. + orig_weight = base_layer.weight.data.clone() + new_weight = self._reconstruct_weight(active_adapter) + + if not torch.isfinite(new_weight).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = new_weight.to(orig_weight.dtype) + else: + new_weight = self._reconstruct_weight(active_adapter) + base_layer.weight.data = new_weight + + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + # For OSF, unmerging means restoring the original weight + # Since we modify the weight in-place, we need to store the original weight + # This is a limitation of the current OSF implementation + warnings.warn("OSF does not support unmerging. Original weights are permanently modified.") + + def __del__(self): + """Cleanup hooks on deletion.""" + self._detach_hooks() + + +class Linear(nn.Module, OSFLayer): + # OSF implemented in a dense layer + def __init__( + self, + base_layer, + adapter_name: str, + effective_rank: int = None, + **kwargs, + ) -> None: + super().__init__() + OSFLayer.__init__(self, base_layer, **kwargs) + + # Set default effective_rank if not provided + if effective_rank is None: + # Default to 50% of min dimension + effective_rank = min(self.in_features, self.out_features) // 2 + + self._active_adapter = adapter_name + self.update_layer(adapter_name, effective_rank, **kwargs) + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + if self.disable_adapters: + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + # Use reconstructed weight for forward pass + base_layer = self.get_base_layer() + bias = base_layer.bias + + # Use the active adapter's reconstructed weight + active_adapter = self.active_adapters[0] if self.active_adapters else None + if active_adapter and active_adapter in self.osf_svd_params: + weight = self._reconstruct_weight(active_adapter) + orig_dtype = x.dtype # assume that the intended dtype is that of the input + x = self._cast_input_dtype(x, weight.dtype) + if bias is not None: + bias = bias.to(weight.dtype) + result = F.linear(x, weight, bias) + result = result.to(orig_dtype) + else: + result = self.base_layer(x, *args, **kwargs) + + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "osf." + rep + + +def dispatch_default( + target: torch.nn.Module, + adapter_name: str, + osf_config, + **kwargs, +) -> Optional[torch.nn.Module]: + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if isinstance(target_base_layer, torch.nn.Linear): + new_module = Linear(target, adapter_name, **kwargs) + + return new_module diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/model.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/model.py new file mode 100644 index 0000000000000000000000000000000000000000..e38c06768cb66615666d8983def1fa4b803a00ba --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/model.py @@ -0,0 +1,124 @@ +from __future__ import annotations + +import re + +import torch +import torch.nn as nn + +from peft.tuners.tuners_utils import BaseTuner +from peft.utils.constants import TRANSFORMERS_MODELS_TO_OSF_TARGET_MODULES_MAPPING + +from .layer import OSFLayer, dispatch_default + + +class OSFModel(BaseTuner): + """A minimal tuner implementing Orthogonal Subspace Fine-tuning.""" + + prefix: str = "osf_" + tuner_layer_cls = OSFLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_OSF_TARGET_MODULES_MAPPING + + def __init__( + self, + model, + config, + adapter_name, + low_cpu_mem_usage: bool = False, + state_dict: dict[str, torch.Tensor] | None = None, + ): + # Pass state_dict through for compatibility with BaseTuner + super().__init__( + model, + config, + adapter_name, + low_cpu_mem_usage=low_cpu_mem_usage, + state_dict=state_dict, + ) + + def __getattr__(self, name: str): + """Forward missing attributes to the wrapped base model. + + This mirrors the behavior of other tuners (e.g., LoRA), ensuring attributes like `device` resolve to the + underlying transformers model. + """ + try: + return super().__getattr__(name) # defer to nn.Module's logic + except AttributeError: + if name == "model": # avoid infinite recursion during init + raise + return getattr(self.model, name) + + def _prepare_adapter_config(self, peft_config, model_config): + # If target_modules is unspecified, try mapping; else fall back to all linear layers for custom models + if peft_config.target_modules is None: + target_modules = self.target_module_mapping.get(model_config["model_type"]) + if target_modules is not None: + peft_config = super()._prepare_adapter_config(peft_config, model_config) + else: + from peft.utils.constants import INCLUDE_LINEAR_LAYERS_SHORTHAND + + peft_config.target_modules = INCLUDE_LINEAR_LAYERS_SHORTHAND + return peft_config + + def _create_and_replace( + self, + osf_config, + adapter_name: str, + target: nn.Module, + target_name: str, + parent: nn.Module, + current_key: str, + *, + parameter_name: str | None = None, + ) -> None: + # OSF only works on 2D weight matrices + if not hasattr(target, "weight") or len(target.weight.shape) != 2: + return None + + # Determine effective rank for this target (supports int or fractional in (0,1]) + def _resolve_rank(value, min_dim: int) -> int: + if value is None: + return max(min_dim // 2, 0) + # floats in (0,1] => fraction of min_dim + if isinstance(value, float) and 0 < value <= 1: + r = int(min_dim * value) + else: + r = int(value) + return max(min(min_dim, r), 0) + + min_dim = min(target.weight.shape) + effective_rank = _resolve_rank(getattr(osf_config, "effective_rank", None), min_dim) + + # Check for per-module rank overrides (allow int or fractional) + if hasattr(osf_config, "rank_pattern") and osf_config.rank_pattern: + for pattern, rank in osf_config.rank_pattern.items(): + if re.search(pattern, current_key): + effective_rank = _resolve_rank(rank, min_dim) + break + + kwargs = { + "effective_rank": effective_rank, + } + + # Create a new or update an existing OSF layer in place + if isinstance(target, OSFLayer): + target.update_layer(adapter_name, **kwargs) + else: + new_module = dispatch_default(target, adapter_name, osf_config, **kwargs) + if new_module is None: + return None + # If adding an additional adapter, keep it frozen initially + if adapter_name not in self.active_adapters: + new_module.requires_grad_(False) + self._replace_module(parent, target_name, new_module, target) + + def _mark_only_adapters_as_trainable(self, model: nn.Module) -> None: + for n, p in model.named_parameters(): + # Only OSF adapter parameters (in osf_svd_params) should be trainable + if "osf_svd_params" not in n: + p.requires_grad = False + + # Use BaseTuner's merge and merge_and_unload implementations. + # Explicitly disallow unmerging at the model level for OSF. + def unmerge_adapter(self, *args, **kwargs): + raise NotImplementedError("OSF models do not support unmerging") diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/utils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0030e22b09da586e3327a646ad91541b8b69bcb1 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/osf/utils.py @@ -0,0 +1,133 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Utilities for Orthogonal Subspace Learning with Adaptive OSF.""" + +from __future__ import annotations + +from typing import Any + +import torch +import torch.distributed as dist +from torch import nn + + +# Note: OSF now relies on OSFLayer + BaseTuner; no model-level helpers required here. + + +__all__ = [ + "decompose_weight_matrix", + "project_gradient_to_orthogonal_space", + "reconstruct_weight_matrix", +] + + +def _wait_if_async(tensor): + """Wait for AsyncCollectiveTensor if needed, otherwise return tensor as-is.""" + if hasattr(tensor, "wait"): + return tensor.wait() + return tensor + + +def decompose_weight_matrix(weight: torch.Tensor, top_k: int) -> dict[str, Any]: + """Perform an SVD of ``weight`` and split it into frozen and trainable parts.""" + device_local = weight.device + orig_dtype = weight.dtype + W = weight.to(torch.float32) + U, S, Vt = torch.linalg.svd(W, full_matrices=False) + k = min(top_k, S.shape[0]) + + svd = { + "U_high": U[:, :k].contiguous().detach().to(device=device_local, dtype=orig_dtype), + "S_high": S[:k].contiguous().detach().to(device=device_local, dtype=orig_dtype), + "V_high": Vt[:k, :].contiguous().detach().to(device=device_local, dtype=orig_dtype), + "U_low": nn.Parameter(U[:, k:].contiguous().detach().to(device=device_local, dtype=orig_dtype)), + "S_low": nn.Parameter(S[k:].contiguous().detach().to(device=device_local, dtype=orig_dtype)), + "V_low": nn.Parameter(Vt[k:, :].contiguous().detach().to(device=device_local, dtype=orig_dtype)), + "rank_high": k, + } + return svd + + +def reconstruct_weight_matrix(svd_dict: dict[str, torch.Tensor]) -> torch.Tensor: + """Reconstruct a weight matrix from its SVD components.""" + U_high = svd_dict["U_high"] + S_high = svd_dict["S_high"] + V_high = svd_dict["V_high"] + U_low = svd_dict["U_low"] + S_low = svd_dict["S_low"] + V_low = svd_dict["V_low"] + + high_part = ( + torch.mm(U_high * S_high.unsqueeze(0), V_high) + if U_high.numel() > 0 and S_high.numel() > 0 + else torch.zeros(U_low.size(0), V_low.size(1), device=U_high.device) + ) + low_part = ( + torch.mm(U_low * S_low.unsqueeze(0), V_low) + if U_low.numel() > 0 and S_low.numel() > 0 + else torch.zeros(U_high.size(0), V_high.size(1), device=U_low.device) + ) + return high_part + low_part + + +def project_gradient_to_orthogonal_space(svd_dict: dict[str, Any]) -> None: + """Project gradients of ``U_low`` and ``V_low`` to be orthogonal to the high rank space.""" + if svd_dict["U_low"].grad is None and svd_dict["S_low"].grad is None and svd_dict["V_low"].grad is None: + return + + U_high = svd_dict["U_high"] + V_high = svd_dict["V_high"] + + # Project U_low gradients to space orthogonal to U_high + if svd_dict["U_low"].grad is not None: + dU = svd_dict["U_low"].grad + # Support distributed tensors by operating on the local shard + local_U_high = getattr(U_high, "to_local", lambda: U_high)() + local_dU = getattr(dU, "to_local", lambda: dU)() + + # Perform projection computation using memory-efficient operations + # Memory-optimized projection: dU = dU - U_high @ (U_high.T @ dU) + # Use addmm_ for efficient in-place operation + # Compute local contribution to (U_high^T @ dU); all-reduce to get global projection + proj_coeff = torch.mm(local_U_high.transpose(0, 1), local_dU) + if dist.is_available() and dist.is_initialized() and dist.get_world_size() > 1: + dist.all_reduce(proj_coeff, op=dist.ReduceOp.SUM) + # Apply projection using only local rows of U_high + local_dU.addmm_(local_U_high, proj_coeff, alpha=-1.0) + + if hasattr(dU, "_local_tensor"): + dU._local_tensor.copy_(local_dU) + else: + dU.copy_(local_dU) + + # Repeat projection for V_low using V_high + if svd_dict["V_low"].grad is not None: + dV = svd_dict["V_low"].grad + local_V_high = getattr(V_high, "to_local", lambda: V_high)() + local_dV = getattr(dV, "to_local", lambda: dV)() + + # Compute Gram matrix G = V_high^T @ V_high for global projection across row-sharded V_high + # Assumes column dimension is consistent across ranks (row sharding over singular vectors) + G_local = torch.mm(local_V_high.transpose(0, 1), local_V_high) + if dist.is_available() and dist.is_initialized() and dist.get_world_size() > 1: + dist.all_reduce(G_local, op=dist.ReduceOp.SUM) + + # Apply projection: dV = dV - dV @ G (use local shard of dV) + update = torch.mm(local_dV, G_local) + local_dV.add_(update, alpha=-1.0) + + if hasattr(dV, "_local_tensor"): + dV._local_tensor.copy_(local_dV) + else: + dV.copy_(local_dV) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/poly/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/poly/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1c18933eba3fa44106ba9fa89ba34ecd12a2bed4 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/poly/__init__.py @@ -0,0 +1,24 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from peft.utils import register_peft_method + +from .config import PolyConfig +from .layer import Linear, PolyLayer +from .model import PolyModel + + +__all__ = ["Linear", "PolyConfig", "PolyLayer", "PolyModel"] + +register_peft_method(name="poly", config_cls=PolyConfig, model_cls=PolyModel) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/poly/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/poly/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5517b281d056419a4798c963c63ac64b014d7b68 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/poly/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/poly/__pycache__/config.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/poly/__pycache__/config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9963f25d8c7a10ef7f1335df98ef4eb9bbab5819 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/poly/__pycache__/config.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/poly/__pycache__/layer.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/poly/__pycache__/layer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d96761c6c78f07e0fa29e23c7f725d36c1a8b4de Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/poly/__pycache__/layer.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/poly/__pycache__/model.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/poly/__pycache__/model.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cdf22d1aa4aa951676c04809e5ed8d0eeb47eb76 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/poly/__pycache__/model.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/poly/__pycache__/router.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/poly/__pycache__/router.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..094388e9fda2ea1c35fecb4d86fcf1581705d343 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/poly/__pycache__/router.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/poly/config.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/poly/config.py new file mode 100644 index 0000000000000000000000000000000000000000..c4a77bc5db447edd4ba97c1b1c407f3cfc620cb4 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/poly/config.py @@ -0,0 +1,103 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Literal, Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class PolyConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`PolyModel`]. + - [Polytropon (Poly)](https://huggingface.co/papers/2202.13914) + - [Multi-Head Routing (MHR)](https://huggingface.co/papers/2211.03831) + + Args: + r (`int`): Attention dimension of each Lora in Poly. + target_modules (`Union[List[str],str]`): The names of the modules to apply Poly to. + exclude_modules (`Optional[Union[List[str], str]]`): + The names of the modules to not apply the adapter. When passing a string, a regex match will be performed. + When passing a list of strings, either an exact match will be performed or it is checked if the name of the + module ends with any of the passed strings. + modules_to_save (`List[str]`): List of modules apart from Poly layers to be set as trainable + and saved in the final checkpoint. + init_weights (bool): Whether to perform initialization of Poly weights. + poly_type (`Literal["poly"]`): The variant of the Poly module to use. Currently, only "poly" + is supported. + n_tasks (`int`): The number of tasks in a multitasking scenario. + n_skills (`int`): The number of skills (LoRA) in each Poly layer. + n_splits (`int`): The number of splits within each LoRA of a Poly layer. A value greater + than 1 indicates the use of Multi-Head Routing (MHR). + """ + + r: int = field(default=8, metadata={"help": "Lora attention dimension"}) + target_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": "List of module names or regex expression of the module names to replace with Poly." + "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$' " + }, + ) + exclude_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={"help": "List of module names or regex expression of the module names to exclude from Poly."}, + ) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": "List of modules apart from Poly layers to be set as trainable and saved in the final checkpoint. " + "For example, in Sequence Classification or Token Classification tasks, " + "the final layer `classifier/score` are randomly initialized and as such need to be trainable and saved." + }, + ) + init_weights: bool = field( + default=True, + metadata={ + "help": ( + "Whether to initialize the weights of the Poly layers with their default initialization. Don't change " + "this setting, except if you know exactly what you're doing." + ), + }, + ) + poly_type: Literal["poly"] = field( + default="poly", + metadata={"help": 'Type of Poly modules to be used. Currently only "poly" is supported.'}, + ) + n_tasks: int = field( + default=1, + metadata={"help": "Number of tasks in multitasking scenario."}, + ) + n_skills: int = field( + default=4, + metadata={"help": "Number of skills (LoRA) in each Poly layer."}, + ) + n_splits: int = field( + default=1, + metadata={"help": "Number of splits within each LoRA of a Poly layer."}, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.POLY + self.target_modules = ( + set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules + ) + self.exclude_modules = ( + set(self.exclude_modules) if isinstance(self.exclude_modules, list) else self.exclude_modules + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/poly/layer.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/poly/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..2f700997a54f247f4cf77172700d40b54e6c2600 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/poly/layer.py @@ -0,0 +1,165 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import math +from typing import Any + +import torch +import torch.nn as nn + +from peft.tuners.tuners_utils import BaseTunerLayer + +from .config import PolyConfig +from .router import get_router + + +class PolyLayer(BaseTunerLayer): + # All names of layers that may contain (trainable) adapter weights + adapter_layer_names = ("poly_lora_A", "poly_lora_B", "poly_router") + # All names of other parameters that may contain adapter-related parameters + other_param_names = ("r", "n_tasks", "n_skills", "n_splits") + + def __init__(self, base_layer: nn.Module, **kwargs): + self.base_layer = base_layer + self.r = {} + self.n_tasks = {} + self.n_skills = {} + self.n_splits = {} + self.poly_type = {} + self.poly_router = nn.ModuleDict() + self.poly_lora_A = nn.ParameterDict() + self.poly_lora_B = nn.ParameterDict() + self.kwargs = kwargs + + base_layer = self.get_base_layer() + if isinstance(base_layer, nn.Linear): + in_features, out_features = base_layer.in_features, base_layer.out_features + else: + raise ValueError(f"Unsupported layer type {type(base_layer)}") + + self.in_features = in_features + self.out_features = out_features + + def update_layer(self, adapter_name, poly_config, inference_mode: bool = False, **kwargs): + if poly_config.r <= 0: + raise ValueError(f"`r` should be a positive integer value but the value passed is {poly_config.r}") + + self.r[adapter_name] = poly_config.r + self.n_tasks[adapter_name] = poly_config.n_tasks + self.n_skills[adapter_name] = poly_config.n_skills + self.n_splits[adapter_name] = poly_config.n_splits + self.poly_type[adapter_name] = poly_config.poly_type + + self.poly_lora_A[adapter_name] = nn.Parameter( + torch.empty( + poly_config.n_splits, + poly_config.n_skills, + self.in_features // poly_config.n_splits, + poly_config.r, + ) + ) + self.poly_lora_B[adapter_name] = nn.Parameter( + torch.empty( + poly_config.n_splits, + poly_config.n_skills, + poly_config.r, + self.out_features // poly_config.n_splits, + ) + ) + self.poly_router[adapter_name] = get_router(poly_config) + + self.reset_poly_parameters(adapter_name, init_weights=poly_config.init_weights) + + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def reset_poly_parameters(self, adapter_name, init_weights): + if adapter_name in self.poly_lora_A.keys(): + # initialize A the same way as the default for nn.Linear + # https://github.com/microsoft/mttl/blob/ce4ca51dbca73be656feb9b3e5233633e3c5dec7/mttl/models/poly.py#L269 + n_splits, n_skills, d, r = self.poly_lora_A[adapter_name].shape + for skill in range(n_skills): + for split in range(n_splits): + param = torch.empty((r, d)) + torch.nn.init.kaiming_uniform_(param, a=math.sqrt(5)) + self.poly_lora_A[adapter_name].data[split, skill, :, :] = param.T + + if init_weights: + # initialize B to zero + torch.nn.init.zeros_(self.poly_lora_B[adapter_name]) + else: + # initialize B the same way as the default for nn.Linear + n_splits, n_skills, r, d = self.poly_lora_B[adapter_name].shape + for skill in range(n_skills): + for split in range(n_splits): + param = torch.empty((d, r)) + torch.nn.init.kaiming_uniform_(param, a=math.sqrt(5)) + self.poly_lora_B[adapter_name].data[split, skill, :, :] = param.T + + # initialized router + self.poly_router[adapter_name].reset() + + +class Linear(nn.Module, PolyLayer): + # Lora implemented in a dense layer + def __init__( + self, + base_layer, + adapter_name: str, + poly_config: PolyConfig, + **kwargs, + ) -> None: + super().__init__() + PolyLayer.__init__(self, base_layer, **kwargs) + + self._active_adapter = adapter_name + self.update_layer(adapter_name, poly_config) + + def forward(self, x: torch.Tensor, *args: Any, task_ids: torch.Tensor = None, **kwargs: Any) -> torch.Tensor: + previous_dtype = x.dtype + if self.disable_adapters: + result = self.base_layer(x, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + for active_adapter in self.active_adapters: + if active_adapter not in self.poly_lora_A.keys(): + continue + + r = self.r[active_adapter] + poly_router = self.poly_router[active_adapter] + poly_lora_A = self.poly_lora_A[active_adapter] + poly_lora_B = self.poly_lora_B[active_adapter] + + # Combine the output of LoRAs + # https://github.com/microsoft/mttl/blob/ce4ca51dbca73be656feb9b3e5233633e3c5dec7/mttl/models/poly.py#L293 + mixing_weights = poly_router(task_ids=task_ids, input_ids=x) + bs, n_splits, n_skills = mixing_weights.size() + + # A is n_splits, n_skills, D // n_splits, rank + # we want bs, n_splits, D // n_splits, rank + A = torch.einsum("bqs,qsdr->bqdr", (mixing_weights, poly_lora_A)) + B = torch.einsum("bqs,qsrd->bqrd", (mixing_weights, poly_lora_B)) + + A = A.reshape(bs, self.in_features, r) + B = B.transpose(1, 2).reshape(bs, r, self.out_features) + + x = x.to(A.dtype) + result += x.bmm(A).bmm(B) / r + + result = result.to(previous_dtype) + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "poly." + rep diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/poly/model.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/poly/model.py new file mode 100644 index 0000000000000000000000000000000000000000..bf7060026310a1f489512293b3afa216105a16cc --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/poly/model.py @@ -0,0 +1,104 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from contextlib import contextmanager +from typing import Any + +import torch +from torch import nn + +from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer +from peft.utils import TRANSFORMERS_MODELS_TO_POLY_TARGET_MODULES_MAPPING + +from .config import PolyConfig +from .layer import Linear, PolyLayer + + +class PolyModel(BaseTuner): + prefix: str = "poly_" + tuner_layer_cls = PolyLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_POLY_TARGET_MODULES_MAPPING + + def _create_and_replace( + self, + poly_config: PolyConfig, + adapter_name: str, + target: nn.Module, + target_name: str, + parent: nn.Module, + **optional_kwargs: Any, + ): + if isinstance(target, PolyLayer): + target.update_layer(adapter_name, poly_config) + else: + new_module = self._create_new_module( + poly_config, + adapter_name, + target, + ) + if adapter_name not in self.active_adapters: + # adding an additional adapter: it is not automatically trainable + new_module.requires_grad_(False) + self._replace_module(parent, target_name, new_module, target) + + @staticmethod + def _create_new_module(poly_config, adapter_name, target, **kwargs): + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if isinstance(target_base_layer, torch.nn.Linear): + return Linear(target, adapter_name, poly_config, **kwargs) + else: + raise ValueError( + f"Target module {target} is not supported. Currently, only the following modules are supported: " + "`torch.nn.Linear`." + ) + + def _register_pre_hooks(self, task_ids): + """Helper method to register pre hooks.""" + if task_ids is None: + return [] + + def pre_hook(_, args, kwargs): + kwargs["task_ids"] = task_ids + return args, kwargs + + handles = [] + + for module in self.model.modules(): + if isinstance(module, Linear): + handle = module.register_forward_pre_hook(pre_hook, with_kwargs=True) + handles.append(handle) + + return handles + + @contextmanager + def _manage_pre_hooks(self, task_ids): + """Context manager to handle the lifecycle of pre hooks.""" + handles = self._register_pre_hooks(task_ids) + try: + yield + finally: + for handle in handles: + handle.remove() + + def forward(self, *args, task_ids=None, **kwargs): + with self._manage_pre_hooks(task_ids): + return self.model(*args, **kwargs) + + def generate(self, *args, task_ids=None, **kwargs): + with self._manage_pre_hooks(task_ids): + return self.model.generate(*args, **kwargs) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/poly/router.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/poly/router.py new file mode 100644 index 0000000000000000000000000000000000000000..3dda3e75e35b6a9fbd5a2412815a0f05421f2ef4 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/poly/router.py @@ -0,0 +1,81 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from abc import ABC, abstractmethod + +import torch +from torch import nn +from torch.distributions.relaxed_bernoulli import RelaxedBernoulli + +from .config import PolyConfig + + +EPS = 1e-12 + + +def get_router(poly_config: PolyConfig) -> nn.Module: + if poly_config.poly_type == "poly": + return PolyRouter(poly_config) + else: + raise ValueError( + f"Unsupported poly_type: {poly_config.poly_type}. " + "Currently, only the following types are supported: " + "`poly`." + ) + + +class Router(nn.Module, ABC): + @abstractmethod + def reset(self): ... + + @abstractmethod + def forward(self, task_ids: torch.Tensor, input_ids: torch.Tensor): ... + + +class PolyRouter(Router): + # It's a simplified implementation of + # https://github.com/microsoft/mttl/blob/ce4ca51dbca73be656feb9b3e5233633e3c5dec7/mttl/models/poly.py#L138 + def __init__(self, poly_config: PolyConfig): + super().__init__() + + self.poly_type = poly_config.poly_type + self.n_tasks = poly_config.n_tasks + self.n_skills = poly_config.n_skills + self.n_splits = poly_config.n_splits + + self.module_logits = nn.Parameter(torch.empty((self.n_tasks, self.n_splits * self.n_skills))) + + def reset(self): + torch.nn.init.uniform_(self.module_logits, -1e-3, 1e-3) + + def forward(self, task_ids: torch.Tensor, input_ids: torch.Tensor): + if task_ids is None: + raise ValueError("task_ids should not be None.") + if task_ids.max().item() >= self.n_tasks: + raise ValueError(f"Only {self.n_tasks} tasks available. Found task id = {task_ids.max().item()}") + + # move task id to input's device + task_ids = task_ids.to(self.module_logits.device) + + module_logits = self.module_logits[task_ids] + module_logits = module_logits.view(-1, self.n_splits, self.n_skills) + + if self.training: + module_logits = RelaxedBernoulli(temperature=1.0, logits=module_logits).rsample() + else: + module_logits = torch.sigmoid(module_logits) + + module_weights = module_logits / (module_logits.sum(dim=-1, keepdim=True) + EPS) + + return module_weights diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/prefix_tuning/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/prefix_tuning/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..939f74d3f689f400dfdcb0139f4a2cf04cce52fc --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/prefix_tuning/__init__.py @@ -0,0 +1,23 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from peft.utils import register_peft_method + +from .config import PrefixTuningConfig +from .model import PrefixEncoder + + +__all__ = ["PrefixEncoder", "PrefixTuningConfig"] + +register_peft_method(name="prefix_tuning", config_cls=PrefixTuningConfig, model_cls=PrefixEncoder) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/prefix_tuning/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/prefix_tuning/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc67ff16bf4bd8100a547c7c9826e100ceacab1f Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/prefix_tuning/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/prefix_tuning/__pycache__/config.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/prefix_tuning/__pycache__/config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c15d242b52bbc378ece78cbaabf18c7b18f34ec9 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/prefix_tuning/__pycache__/config.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/prefix_tuning/__pycache__/model.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/prefix_tuning/__pycache__/model.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ee9d469d7301dbdac1a09bde5c17300c6c63ca8 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/prefix_tuning/__pycache__/model.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/prefix_tuning/config.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/prefix_tuning/config.py new file mode 100644 index 0000000000000000000000000000000000000000..37a7ac5e1de744ca0aac7464de9127502b7db97b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/prefix_tuning/config.py @@ -0,0 +1,52 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field +from typing import Literal + +from peft.config import PromptLearningConfig +from peft.utils import PeftType + + +@dataclass +class PrefixTuningConfig(PromptLearningConfig): + """ + This is the configuration class to store the configuration of a [`PrefixEncoder`]. + + Args: + init_weights (`Optional[str]`): If not set, weights are initialized at random, if set to "zero" + the weights are initialized so that the activations will be a no-op (zero). + encoder_hidden_size (`int`): The hidden size of the prompt encoder. + prefix_projection (`bool`): Whether to project the prefix embeddings. + """ + + init_weights: Literal["zero"] | None = field( + default=None, + metadata={ + "help": 'If not set, weights are initialized at random, if set to "zero" the ' + "weights are initialized so that the activations will be a no-op (zero)." + }, + ) + encoder_hidden_size: int = field( + default=None, + metadata={"help": "The hidden size of the encoder"}, + ) + prefix_projection: bool = field( + default=False, + metadata={"help": "Whether to project the prefix tokens"}, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.PREFIX_TUNING diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/prefix_tuning/model.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/prefix_tuning/model.py new file mode 100644 index 0000000000000000000000000000000000000000..5ff6dbeeb0d17fc6cc9e23d7ac66a044adf798e9 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/prefix_tuning/model.py @@ -0,0 +1,108 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Based on https://github.com/THUDM/P-tuning-v2/blob/main/model/prefix_encoder.py +# with some refactor +import torch + + +class PrefixEncoder(torch.nn.Module): + r""" + The `torch.nn` model to encode the prefix. + + Args: + config ([`PrefixTuningConfig`]): The configuration of the prefix encoder. + + Example: + + ```py + >>> from peft import PrefixEncoder, PrefixTuningConfig + + >>> config = PrefixTuningConfig( + ... peft_type="PREFIX_TUNING", + ... task_type="SEQ_2_SEQ_LM", + ... num_virtual_tokens=20, + ... token_dim=768, + ... num_transformer_submodules=1, + ... num_attention_heads=12, + ... num_layers=12, + ... encoder_hidden_size=768, + ... ) + >>> prefix_encoder = PrefixEncoder(config) + ``` + + **Attributes**: + - **embedding** (`torch.nn.Embedding`) -- The embedding layer of the prefix encoder. + - **transform** (`torch.nn.Sequential`) -- The two-layer MLP to transform the prefix embeddings if + `prefix_projection` is `True`. + - **prefix_projection** (`bool`) -- Whether to project the prefix embeddings. + + Input shape: (`batch_size`, `num_virtual_tokens`) + + Output shape: (`batch_size`, `num_virtual_tokens`, `2*layers*hidden`) + """ + + def __init__(self, config): + super().__init__() + self.prefix_projection = config.prefix_projection + token_dim = config.token_dim + num_layers = config.num_layers + encoder_hidden_size = config.encoder_hidden_size + num_virtual_tokens = config.num_virtual_tokens + init_weights = config.init_weights + if self.prefix_projection and not config.inference_mode: + # Use a two-layer MLP to encode the prefix + self.embedding = torch.nn.Embedding(num_virtual_tokens, token_dim) + self.transform = torch.nn.Sequential( + torch.nn.Linear(token_dim, encoder_hidden_size), + torch.nn.Tanh(), + torch.nn.Linear(encoder_hidden_size, num_layers * 2 * token_dim), + ) + + if init_weights == "zero": + torch.nn.init.zeros_(self.transform[-1].weight.data) + torch.nn.init.zeros_(self.transform[-1].bias.data) + else: + self.embedding = torch.nn.Embedding(num_virtual_tokens, num_layers * 2 * token_dim) + if init_weights == "zero": + torch.nn.init.zeros_(self.embedding.weight.data) + + def forward(self, prefix: torch.Tensor): + if self.prefix_projection: + prefix_tokens = self.embedding(prefix) + past_key_values = self.transform(prefix_tokens) + else: + past_key_values = self.embedding(prefix) + return past_key_values + + def load_prompt_embeddings(self, prompt_embeddings: torch.Tensor) -> None: + """ + Load the flattened prompt embeddings saved by PEFT (`prompt_embeddings`). + + For prefix tuning, this is only supported when `prefix_projection=False`, because in that case the learned + parameters are the KV prefix itself (`embedding.weight` has shape `[num_virtual_tokens, + num_layers*2*token_dim]`). + + If `prefix_projection=True`, the parameters are (virtual token embeddings + an MLP) and there is no general way + to invert the projection to recover those parameters from a flattened KV prefix. + """ + if self.prefix_projection: + raise ValueError("Cannot load flattened prompt embeddings when `prefix_projection=True`.") + if prompt_embeddings.shape != self.embedding.weight.shape: + raise ValueError( + "Invalid `prompt_embeddings` shape. Expected " + f"{tuple(self.embedding.weight.shape)}, got {tuple(prompt_embeddings.shape)}." + ) + with torch.no_grad(): + self.embedding.weight.copy_(prompt_embeddings.to(self.embedding.weight.device)) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/prompt_tuning/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/prompt_tuning/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c99ca6a26fea22e3d829c16eec378e82633e1b7b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/prompt_tuning/__init__.py @@ -0,0 +1,23 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from peft.utils import register_peft_method + +from .config import PromptTuningConfig, PromptTuningInit +from .model import PromptEmbedding + + +__all__ = ["PromptEmbedding", "PromptTuningConfig", "PromptTuningInit"] + +register_peft_method(name="prompt_tuning", config_cls=PromptTuningConfig, model_cls=PromptEmbedding) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/prompt_tuning/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/prompt_tuning/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..706290ab2f8744dc4ec5ea0cac23289a24814c19 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/prompt_tuning/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/prompt_tuning/__pycache__/config.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/prompt_tuning/__pycache__/config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cbd916166c77f039a9266dbbdd4ddbb5236af64e Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/prompt_tuning/__pycache__/config.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/prompt_tuning/__pycache__/model.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/prompt_tuning/__pycache__/model.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9e141f00919a3c4bed12f5076b973cab3cf2fb3 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/prompt_tuning/__pycache__/model.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/prompt_tuning/config.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/prompt_tuning/config.py new file mode 100644 index 0000000000000000000000000000000000000000..b41669efe898e88dfd015042e0c78258fb9b3a14 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/prompt_tuning/config.py @@ -0,0 +1,91 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import enum +from dataclasses import dataclass, field +from typing import Optional, Union + +from peft.config import PromptLearningConfig +from peft.utils import PeftType + + +class PromptTuningInit(str, enum.Enum): + TEXT = "TEXT" + SAMPLE_VOCAB = "SAMPLE_VOCAB" + RANDOM = "RANDOM" + + +@dataclass +class PromptTuningConfig(PromptLearningConfig): + """ + This is the configuration class to store the configuration of a [`PromptEmbedding`]. + + Args: + prompt_tuning_init (Union[[`PromptTuningInit`], `str`]): + The initialization of the prompt embedding. `TEXT` will initialize with your text. `SAMPLE_VOCAB` will + initialize with randomly sampled tokens from the model's vocabulary. `RANDOM` will initialize with randomly + sampled continuous, soft tokens (warning: sampled soft tokens may fall outside of embedding manifold) + prompt_tuning_init_text (`str`, *optional*): + The text to initialize the prompt embedding. Only used if `prompt_tuning_init` is `TEXT`. + tokenizer_name_or_path (`str`, *optional*): + The name or path of the tokenizer. Only used if `prompt_tuning_init` is `TEXT`. + tokenizer_kwargs (`dict`, *optional*): + The keyword arguments to pass to `AutoTokenizer.from_pretrained`. Only used if `prompt_tuning_init` is + `TEXT`. + """ + + prompt_tuning_init: Union[PromptTuningInit, str] = field( + default=PromptTuningInit.RANDOM, + metadata={"help": "How to initialize the prompt tuning parameters"}, + ) + prompt_tuning_init_text: Optional[str] = field( + default=None, + metadata={ + "help": "The text to use for prompt tuning initialization. Only used if prompt_tuning_init is `TEXT`" + }, + ) + tokenizer_name_or_path: Optional[str] = field( + default=None, + metadata={ + "help": "The tokenizer to use for prompt tuning initialization. Only used if prompt_tuning_init is `TEXT`" + }, + ) + + tokenizer_kwargs: Optional[dict] = field( + default=None, + metadata={ + "help": ( + "The keyword arguments to pass to `AutoTokenizer.from_pretrained`. Only used if prompt_tuning_init is " + "`TEXT`" + ), + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.PROMPT_TUNING + if (self.prompt_tuning_init == PromptTuningInit.TEXT) and not self.tokenizer_name_or_path: + raise ValueError( + f"When prompt_tuning_init='{PromptTuningInit.TEXT.value}', " + f"tokenizer_name_or_path can't be {self.tokenizer_name_or_path}." + ) + if (self.prompt_tuning_init == PromptTuningInit.TEXT) and self.prompt_tuning_init_text is None: + raise ValueError( + f"When prompt_tuning_init='{PromptTuningInit.TEXT.value}', " + f"prompt_tuning_init_text can't be {self.prompt_tuning_init_text}." + ) + if self.tokenizer_kwargs and (self.prompt_tuning_init != PromptTuningInit.TEXT): + raise ValueError( + f"tokenizer_kwargs only valid when using prompt_tuning_init='{PromptTuningInit.TEXT.value}'." + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/prompt_tuning/model.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/prompt_tuning/model.py new file mode 100644 index 0000000000000000000000000000000000000000..3c6fc50d156fa98d2c8ebf8f1aaaa5a6fa1b7c9e --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/prompt_tuning/model.py @@ -0,0 +1,105 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import math + +import torch + +from peft.utils.integrations import gather_params_ctx + +from .config import PromptTuningInit + + +class PromptEmbedding(torch.nn.Module): + """ + The model to encode virtual tokens into prompt embeddings. + + Args: + config ([`PromptTuningConfig`]): The configuration of the prompt embedding. + word_embeddings (`torch.nn.Module`): The word embeddings of the base transformer model. + + **Attributes**: + - **embedding** (`torch.nn.Embedding`) -- The embedding layer of the prompt embedding. + + Example: + + ```py + >>> from peft import PromptEmbedding, PromptTuningConfig + + >>> config = PromptTuningConfig( + ... peft_type="PROMPT_TUNING", + ... task_type="SEQ_2_SEQ_LM", + ... num_virtual_tokens=20, + ... token_dim=768, + ... num_transformer_submodules=1, + ... num_attention_heads=12, + ... num_layers=12, + ... prompt_tuning_init="TEXT", + ... prompt_tuning_init_text="Predict if sentiment of this review is positive, negative or neutral", + ... tokenizer_name_or_path="t5-base", + ... ) + + >>> # t5_model.shared is the word embeddings of the base model + >>> prompt_embedding = PromptEmbedding(config, t5_model.shared) + ``` + + Input Shape: (`batch_size`, `total_virtual_tokens`) + + Output Shape: (`batch_size`, `total_virtual_tokens`, `token_dim`) + """ + + def __init__(self, config, word_embeddings): + super().__init__() + + total_virtual_tokens = config.num_virtual_tokens * config.num_transformer_submodules + self.embedding = torch.nn.Embedding(total_virtual_tokens, config.token_dim) + if config.prompt_tuning_init == PromptTuningInit.SAMPLE_VOCAB and not config.inference_mode: + # Randomly sample tokens from the tokenizer's vocab + vocab_size = word_embeddings.num_embeddings + init_token_ids = torch.randint(0, vocab_size, (total_virtual_tokens,), dtype=torch.long).to( + word_embeddings.weight.device + ) + with gather_params_ctx(word_embeddings.parameters()): + word_embedding_weights = word_embeddings(init_token_ids).detach().clone() + word_embedding_weights = word_embedding_weights.to(torch.float32) + self.embedding.weight = torch.nn.Parameter(word_embedding_weights) + + elif config.prompt_tuning_init == PromptTuningInit.TEXT and not config.inference_mode: + from transformers import AutoTokenizer + + tokenizer_kwargs = config.tokenizer_kwargs or {} + # security: disallow trust_remote_code, as this could allow code execution when loading a prompt tuning + # checkpoint + tokenizer_kwargs.pop("trust_remote_code", None) + tokenizer = AutoTokenizer.from_pretrained(config.tokenizer_name_or_path, **tokenizer_kwargs) + init_text = config.prompt_tuning_init_text + init_token_ids = tokenizer(init_text)["input_ids"] + # Trim or iterate until num_text_tokens matches total_virtual_tokens + num_text_tokens = len(init_token_ids) + if num_text_tokens > total_virtual_tokens: + init_token_ids = init_token_ids[:total_virtual_tokens] + elif num_text_tokens < total_virtual_tokens: + num_reps = math.ceil(total_virtual_tokens / num_text_tokens) + init_token_ids = init_token_ids * num_reps + init_token_ids = init_token_ids[:total_virtual_tokens] + init_token_ids = torch.LongTensor(init_token_ids).to(word_embeddings.weight.device) + with gather_params_ctx(word_embeddings.parameters()): + word_embedding_weights = word_embeddings(init_token_ids).detach().clone() + word_embedding_weights = word_embedding_weights.to(torch.float32) + self.embedding.weight = torch.nn.Parameter(word_embedding_weights) + + def forward(self, indices): + # Just get embeddings + prompt_embeddings = self.embedding(indices) + return prompt_embeddings diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/randlora/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/randlora/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fbad681aeb0231254f5caae6b9bf9aa3a2c76ef0 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/randlora/__init__.py @@ -0,0 +1,40 @@ +# Copyright 2025-present the HuggingFace Inc. team. + +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available +from peft.utils import register_peft_method + +from .config import RandLoraConfig +from .layer import Linear, RandLoraLayer +from .model import RandLoraModel + + +__all__ = ["Linear", "RandLoraConfig", "RandLoraLayer", "RandLoraModel"] + +register_peft_method(name="randlora", config_cls=RandLoraConfig, model_cls=RandLoraModel, prefix="randlora_") + + +def __getattr__(name): + if (name == "Linear8bitLt") and is_bnb_available(): + from .bnb import Linear8bitLt + + return Linear8bitLt + + if (name == "Linear4bit") and is_bnb_4bit_available(): + from .bnb import Linear4bit + + return Linear4bit + + raise AttributeError(f"module {__name__} has no attribute {name}") diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/randlora/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/randlora/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42de7950e2b157fad056162b46f62e7c62adf3d7 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/randlora/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/randlora/__pycache__/bnb.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/randlora/__pycache__/bnb.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7db22bd649113d4d0ef3a8788db3d50809dbc7d5 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/randlora/__pycache__/bnb.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/randlora/__pycache__/config.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/randlora/__pycache__/config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ace29f55a6738dd0b647a3b91328e0b544a25680 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/randlora/__pycache__/config.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/randlora/__pycache__/layer.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/randlora/__pycache__/layer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f724abaa43aae0a6c0b891576eb4111c6799bf8 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/randlora/__pycache__/layer.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/randlora/__pycache__/model.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/randlora/__pycache__/model.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6bb29764307bb33ede8c09c98491624398e50cdd Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/randlora/__pycache__/model.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/randlora/bnb.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/randlora/bnb.py new file mode 100644 index 0000000000000000000000000000000000000000..353295e88aab41f4ca59669ec51e4dc479ad1e3e --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/randlora/bnb.py @@ -0,0 +1,456 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import warnings +from typing import Optional + +import bitsandbytes as bnb +import torch + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available +from peft.tuners.tuners_utils import check_adapters_to_merge +from peft.utils.integrations import dequantize_bnb_weight +from peft.utils.other import transpose + +from .layer import RandLoraLayer, UniqueBaseGrad + + +if is_bnb_available(): + + class Linear8bitLt(torch.nn.Module, RandLoraLayer): + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + randlora_A, + randlora_B, + r: int = 0, + randlora_alpha: int = 0, + randlora_dropout: float = 0.0, + fan_in_fan_out: bool = False, + init_weights: bool = True, + **kwargs, + ) -> None: + super().__init__() + RandLoraLayer.__init__(self, base_layer) + self.fan_in_fan_out = fan_in_fan_out + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + randlora_A, + randlora_B, + r, + randlora_alpha=randlora_alpha, + randlora_dropout=randlora_dropout, + init_weights=init_weights, + ) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`list[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. + Defaults to `None`. + """ + + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + return + + for active_adapter in adapter_names: + if active_adapter not in self.randlora_lambda.keys(): + continue + + warnings.warn( + "Merge RandLora module to 8-bit linear may get different generations due to rounding errors." + ) + randlora_data = self.get_delta_weight(active_adapter) + + weight = self.get_base_layer().weight + state = self.get_base_layer().state + if state.SCB is None: + state.SCB = weight.SCB + + output = dequantize_bnb_weight(weight, state) + w_data = output.to(randlora_data.dtype).to(randlora_data.device) + randlora_data + + if safe_merge and not torch.isfinite(w_data).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + self.get_base_layer().weight = bnb.nn.Int8Params( + w_data.to("cpu"), requires_grad=False, has_fp16_weights=weight.has_fp16_weights + ).to(weight.device) + state.reset_grads() + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do") + return + + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter not in self.randlora_lambda.keys(): + continue + warnings.warn( + "Unmerge randlora module to 8-bit linear may get different generations due to rounding errors." + ) + randlora_data = self.get_delta_weight(active_adapter) + + weight = self.get_base_layer().weight + state = self.get_base_layer().state + if state.SCB is None: + state.SCB = weight.SCB + output = dequantize_bnb_weight(weight, state=state) + + w_data = output.to(randlora_data.dtype).to(randlora_data.device) - randlora_data + + self.get_base_layer().weight = bnb.nn.Int8Params( + w_data.to("cpu"), requires_grad=False, has_fp16_weights=weight.has_fp16_weights + ).to(weight.device) + state.reset_grads() + + def get_scaled_bases(self, adapter, device=None) -> list[torch.Tensor, torch.Tensor]: + """ + Performs scaling on the smallest random base (randlora_A) and returns randlora_A and randlora_B in the + correct order to fit the target layers' dimensions + + Args: + adapter (str): + The name of the adapter for which the delta weight should be computed. + """ + + randlora_A = self.randlora_A[adapter] + randlora_B = self.randlora_B[adapter] + + if device is None: + device = randlora_B.device + dtype = randlora_B.dtype + + # In case users wants to merge the adapter weights that are in + # (b)float16 while being on CPU, we need to cast the weights to float32, perform the merge and then cast back to + # (b)float16 because some CPUs have slow bf16/fp16 matmuls. + cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16) + + randlora_lambda = self.randlora_lambda[adapter].to(device) + randlora_gamma = self.randlora_gamma[adapter].to(device) + + if cast_to_fp32: + randlora_A = randlora_A.float() + randlora_B = randlora_B.float() + randlora_lambda = randlora_lambda.float() + randlora_gamma = randlora_gamma.float() + + # The trainable parameters are always applied to randlora_A, the smallest basis. + min_dim, max_dim = min(self.out_features, self.in_features), max(self.out_features, self.in_features) + + # As adapted layers may have different shapes and RandLora contains a single shared pair of A and B matrices, + # we initialize these matrices with the largest required size for each dimension. + # During the forward pass, required submatrices are sliced out from the shared randlora_A and randlora_B. + sliced_A = randlora_A[:, : self.num_bases, :min_dim].to(device) + sliced_B = randlora_B[:max_dim, : self.num_bases, :].to(device) + + # Flattening the matrices over the rank and number of bases dimensions is more memory efficient + update_B = sliced_B.flatten(start_dim=1) + update_A = UniqueBaseGrad.apply(sliced_A, randlora_lambda, randlora_gamma).flatten(end_dim=1) + if min_dim == self.in_features: + return update_A, update_B + + return update_B.T, update_A.T + + def get_delta_weight(self, adapter) -> torch.Tensor: + """ + Compute the delta weight for the given adapter. + + Args: + adapter (str): + The name of the adapter for which the delta weight should be computed. + """ + + update_B, update_A = self.get_scaled_bases(adapter) + + update = update_B @ update_A + output_tensor = transpose(update, self.fan_in_fan_out) + + scaling = self.scaling[adapter] + + return output_tensor * scaling + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + """ + Perform the forward pass using the RandLora adapter. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + torch.Tensor: Output tensor after applying the RandLora adaptation. + + Note: + This method implements the RandLora-specific forward pass. It applies the shared projections + (randlora_A and randlora_B) along with the per-layer trainable parameters (lambda and gamma) to compute + the adapter output. + """ + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + for active_adapter in self.active_adapters: + if active_adapter not in self.randlora_lambda.keys(): + continue + + update_B, update_A = self.get_scaled_bases(active_adapter, device=x.device) + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + compute_dtype = update_A.dtype + if x.dtype != compute_dtype: + x = x.to(compute_dtype) + + dropout = self.randlora_dropout[active_adapter] + x_temp = dropout(x.to(update_A.dtype)) + + adapter_output = torch.nn.functional.linear(torch.nn.functional.linear(x_temp, update_B), update_A) + + if requires_conversion: + adapter_output = adapter_output.to(expected_dtype) + + scaling = self.scaling[active_adapter] + result = result + adapter_output * scaling + + # Ensure the output tensor has the same dtype as the input tensor + return result.to(x.dtype) + + def __repr__(self) -> str: + rep = super().__repr__() + return "randlora." + rep + + +if is_bnb_4bit_available(): + + class Linear4bit(torch.nn.Module, RandLoraLayer): + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + randlora_A, + randlora_B, + r: int = 0, + randlora_alpha: int = 0, + randlora_dropout: float = 0.0, + fan_in_fan_out: bool = False, + init_weights: bool = True, + **kwargs, + ) -> None: + super().__init__() + RandLoraLayer.__init__(self, base_layer) + self.fan_in_fan_out = fan_in_fan_out + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + randlora_A, + randlora_B, + r, + randlora_alpha=randlora_alpha, + randlora_dropout=randlora_dropout, + init_weights=init_weights, + ) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`list[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. + Defaults to `None`. + """ + + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + return + + for active_adapter in adapter_names: + if active_adapter not in self.randlora_lambda.keys(): + continue + + warnings.warn( + "Merge RandLora module to 4-bit linear may get different generations due to rounding errors." + ) + randlora_data = self.get_delta_weight(active_adapter) + + weight = self.get_base_layer().weight + kwargs = weight.__dict__ + w_data = bnb.functional.dequantize_4bit(weight.data, weight.quant_state) + randlora_data + + if safe_merge and not torch.isfinite(w_data).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + self.get_base_layer().weight = bnb.nn.Params4bit(w_data.to("cpu"), requires_grad=False, **kwargs).to( + weight.device + ) + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do") + return + + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter not in self.randlora_lambda.keys(): + continue + warnings.warn( + "Unmerge RandLora module to 4-bit linear may get different generations due to rounding errors." + ) + randlora_data = self.get_delta_weight(active_adapter) + + weight = self.get_base_layer().weight + kwargs = weight.__dict__ + w_data = bnb.functional.dequantize_4bit(weight.data, weight.quant_state) - randlora_data + + self.get_base_layer().weight = bnb.nn.Params4bit(w_data.to("cpu"), requires_grad=False, **kwargs).to( + weight.device + ) + + def get_scaled_bases(self, adapter, device=None) -> list[torch.Tensor, torch.Tensor]: + """ + Performs scaling on the smallest random base (randlora_A) and returns randlora_A and randlora_B in the + correct order to fit the target layers' dimensions + + Args: + adapter (str): + The name of the adapter for which the delta weight should be computed. + """ + + randlora_A = self.randlora_A[adapter] + randlora_B = self.randlora_B[adapter] + if device is None: + device = randlora_B.device + dtype = randlora_B.dtype + + # In case users wants to merge the adapter weights that are in + # (b)float16 while being on CPU, we need to cast the weights to float32, perform the merge and then cast back to + # (b)float16 because some CPUs have slow bf16/fp16 matmuls. + cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16) + + randlora_lambda = self.randlora_lambda[adapter].to(device) + randlora_gamma = self.randlora_gamma[adapter].to(device) + + if cast_to_fp32: + randlora_A = randlora_A.float() + randlora_B = randlora_B.float() + randlora_lambda = randlora_lambda.float() + randlora_gamma = randlora_gamma.float() + + # The trainable parameters are always applied to randlora_A, the smallest basis. + min_dim, max_dim = min(self.out_features, self.in_features), max(self.out_features, self.in_features) + + # As adapted layers may have different shapes and RandLora contains a single shared pair of A and B matrices, + # we initialize these matrices with the largest required size for each dimension. + # During the forward pass, required submatrices are sliced out from the shared randlora_A and randlora_B. + sliced_A = randlora_A[:, : self.num_bases, :min_dim].to(device) + sliced_B = randlora_B[:max_dim, : self.num_bases, :].to(device) + # Flattening the matrices over the rank and number of bases dimensions is more memory efficient + update_B = sliced_B.flatten(start_dim=1) + update_A = UniqueBaseGrad.apply(sliced_A, randlora_lambda, randlora_gamma).flatten(end_dim=1) + if min_dim == self.in_features: + return update_A, update_B + + return update_B.T, update_A.T + + def get_delta_weight(self, adapter) -> torch.Tensor: + """ + Compute the delta weight for the given adapter. + + Args: + adapter (str): + The name of the adapter for which the delta weight should be computed. + """ + update_B, update_A = self.get_scaled_bases(adapter) + + update = update_B @ update_A + output_tensor = transpose(update, self.fan_in_fan_out) + + scaling = self.scaling[adapter] + + return output_tensor * scaling + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + result = result.clone() + for active_adapter in self.active_adapters: + if active_adapter not in self.randlora_lambda.keys(): + continue + + update_B, update_A = self.get_scaled_bases(active_adapter, device=x.device) + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + compute_dtype = update_A.dtype + if x.dtype != compute_dtype: + x = x.to(compute_dtype) + + dropout = self.randlora_dropout[active_adapter] + x_temp = dropout(x.to(update_A.dtype)) + + adapter_output = torch.nn.functional.linear(torch.nn.functional.linear(x_temp, update_B), update_A) + + if requires_conversion: + adapter_output = adapter_output.to(expected_dtype) + + scaling = self.scaling[active_adapter] + result = result + adapter_output * scaling + + # Ensure the output tensor has the same dtype as the input tensor + return result.to(x.dtype) + + def __repr__(self) -> str: + rep = super().__repr__() + return "randlora." + rep diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/randlora/config.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/randlora/config.py new file mode 100644 index 0000000000000000000000000000000000000000..b194b974331dd9abcb5777295ae4e79d8b81da56 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/randlora/config.py @@ -0,0 +1,199 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from dataclasses import dataclass, field +from typing import Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class RandLoraConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`RandLoraModel`]. + + Paper: https://huggingface.co/papers/2502.00987. + + Args: + r (`int`, *optional*, defaults to `32`): + RandLora's random basis rank dimension. Contrary to Lora, this parameter is inversely proportional to the + amount of trainable parameters as reducing it increases trainable parameters. + target_modules (`Union[list[str], str]`): + The names of the modules to apply RandLora to. Only linear layers are supported. + projection_prng_key (`int`): + RandLora PRNG init key. Used for initialising basis_A and basis_B for new models or when loading a + checkpoint that did not include these projections. Defaults to `0`. + save_projection (`bool`): + Whether to save the global basis_A / basis_B random basis in the state dict alongside per layer lambda / + gamma diagonal matrices. This will increase the size of the checkpoint, but guarantee that we can reload + the checkpoint on all system configurations. Defaults to `True`. + sparse (`bool`): + Whether to use sparse random bases as described in the RandLora paper. The bases are ternary sparse bases + (only containing -1, 0 and 1) where the attribution probability is 1/6 for -1 and 1 and 2/3 for 0. These + sparse matrices aim to be used for matmul free computation in the future, see + https://huggingface.co/papers/2406.02528v1 The current implementation is a proof of concept however where + the sparseness is not used to improve speed or memory usage. Using sparse matrices typically does not + reduce performance and can even help reduce overfitting. Defaults to `False`. + very_sparse (`bool`): + Whether to use highly sparse random bases as described in the RandLora paper. The very sparse bases are + ternary sparse bases (only containing -1, 0 and 1) given a matrix with smallest dimension d, the + attribution probability is 1/√D for -1 and 1 and 1- 2/√D for 0. Using these sparse matrices can further + reduce overfitting over the `sparse` alternatives but will most likely decrease performance as a results. + Use carefully. Defaults to `False`. + randlora_dropout (`float`): + The dropout probability for RandLora layers. + randlora_alpha (`float`): + The scaling coefficient for RandLora layers, this would typically be 20 times the rank. Because the + `randlora_alpha` coefficient is large by default, it can lead to numerical instabilities especially when + learning rates are high. If training is unstable, consider reducing the learning rate or the + `randlora_alpha` coefficient. + fan_in_fan_out (`bool`): + Set this to True if the layer to replace stores weight like (fan_in, fan_out). For example, gpt-2 uses + `Conv1D` which stores weights like (fan_in, fan_out) and hence this should be set to `True`. + bias (`str`): + Bias type. Can be 'none', 'all' or 'randlora_only'. If 'all' or 'randlora_only', the corresponding biases + will be updated during training. Be aware that this means that, even when disabling the adapters, the model + will not produce the same output as the base model would have without adaptation. + modules_to_save (`list[str]`): + list of modules apart from RandLora layers to be set as trainable and saved in the final checkpoint. + init_weights (`bool`): + Whether to initialize the weights of the RandLora layers with their default initialization. Don't change + this setting, except if you know exactly what you're doing. + layers_to_transform (`Union[list[int],int]`): + The layer indexes to transform, if this argument is specified, it will apply the RandLora transformations + on the layer indexes that are specified in this list. If a single integer is passed, it will apply the + RandLora transformations on the layer at this index. + layers_pattern (`str`): + The layer pattern name, used only if `layers_to_transform` is different from `None` and if the layer + pattern is not in the common layers pattern. + """ + + r: int = field(default=32, metadata={"help": "RandLora random basis rank"}) + + target_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": ( + "list of module names or regex expression of the module names to replace with RandLora." + "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'. " + "Only linear layers are supported." + ) + }, + ) + projection_prng_key: int = field( + default=0, + metadata={ + "help": ( + "RandLora PRNG init key. Used for initialising basis_A and basis_B for new models or when loading a " + "checkpoint that did not include these projections." + ) + }, + ) + save_projection: bool = field( + default=True, + metadata={ + "help": ( + "Whether to save the basis_A / basis_B projections in the state dict alongside per layer lambda / " + "gamma weights. This will increase the size of the checkpoint, but guarantee that we can reload " + "the checkpoint on all system configurations." + ) + }, + ) + sparse: bool = field( + default=False, + metadata={ + "help": ( + "Whether to use sparse random bases as described in the RandLora paper." + "The current implementation is a proof of concept where the sparseness" + "is not used to improve speed or memory usage." + ) + }, + ) + very_sparse: bool = field( + default=False, + metadata={ + "help": ( + "Whether to use very sparse random bases." + "The current implementation is a proof of concept where the sparseness" + "is not used to improve speed or memory usage." + ) + }, + ) + randlora_dropout: float = field(default=0.0, metadata={"help": "Dropout in the adapter layers"}) + fan_in_fan_out: bool = field( + default=False, + metadata={"help": "Set this to True if the layer to replace stores weight like (fan_in, fan_out)"}, + ) + randlora_alpha: int = field( + default=640, + metadata={ + "help": "Scaling coefficient in the adapter layers, typically 20 times the rank of the random bases." + }, + ) + bias: str = field( + default="none", metadata={"help": "Bias type for RandLora. Can be 'none', 'all' or 'randlora_only'"} + ) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": ( + "list of modules apart from RandLora layers to be set as trainable and saved in the final checkpoint. For" + " example, in Sequence Classification or Token Classification tasks, the final layer" + " `classifier/score` are randomly initialized and as such need to be trainable and saved." + ) + }, + ) + init_weights: bool = field( + default=True, + metadata={ + "help": ( + "Whether to initialize the weights of the RandLora layers with their default initialization. Don't change " + "this setting, except if you know exactly what you're doing." + ), + }, + ) + layers_to_transform: Optional[Union[list[int], int]] = field( + default=None, + metadata={ + "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." + ) + }, + ) + layers_pattern: Optional[str] = field( + default=None, + metadata={ + "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." + ) + }, + ) + + def __post_init__(self): + self.peft_type = PeftType.RANDLORA + self.target_modules = ( + set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules + ) + + if not self.save_projection: + warnings.warn( + "Specified to not save basis_A and basis_B within the state dictionary, instead they will be restored " + "using the PRNG key store in `config.projection_prng_key`. Consider setting `config.save_projection` " + "to `True` to guarantee restoring the checkpoint correctly on all system configurations." + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/randlora/layer.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/randlora/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..679a417439a9f1b9c4b16697903e2064f92bed51 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/randlora/layer.py @@ -0,0 +1,353 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from typing import Optional + +import torch +import torch.nn as nn +import torch.nn.functional as F +from transformers.pytorch_utils import Conv1D + +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge +from peft.utils.other import transpose + +from .._buffer_dict import BufferDict + + +class UniqueBaseGrad(torch.autograd.Function): + # Memory efficent for a unique base + @staticmethod + def forward(ctx, randlora_A, randlora_lambda, randlora_gamma): + out = randlora_lambda[:, :, None] * randlora_A * randlora_gamma[None,] + ctx.save_for_backward(randlora_A, randlora_lambda, randlora_gamma) + return out + + @staticmethod + def backward(ctx, grad_output): + randlora_A, randlora_lambda, randlora_gamma = ctx.saved_tensors + randlora_A, randlora_lambda, randlora_gamma = ( + randlora_A.to(grad_output.dtype), + randlora_lambda.to(grad_output.dtype), + randlora_gamma.to(grad_output.dtype), + ) + grad_randlora_lambda = torch.einsum("kbj,kvj,bj->kb", grad_output, randlora_A, randlora_gamma) + grad_randlora_gamma = torch.einsum("kbj,kvj,kb->bj", grad_output, randlora_A, randlora_lambda) + return None, grad_randlora_lambda, grad_randlora_gamma + + +class RandLoraLayer(BaseTunerLayer): + # List all names of layers that may contain adapter weights + adapter_layer_names = ("randlora_lambda", "randlora_gamma") + other_param_names = ("randlora_A", "randlora_B") + + def __init__(self, base_layer: nn.Module, **kwargs): + self.base_layer = base_layer + self.r = {} + self.scaling = {} + self.randlora_dropout = nn.ModuleDict({}) + + # For storing vector scale + self.randlora_lambda = nn.ParameterDict({}) + self.randlora_gamma = nn.ParameterDict({}) + + # Stores a reference to the randlora_A/B BufferDict. + # Set to `None` otherwise to avoid computation with random weights + self.randlora_A: Optional[BufferDict] = None + self.randlora_B: Optional[BufferDict] = None + + # Mark the weight as unmerged + self._disable_adapters = False + self.merged_adapters = [] + + # flag to enable/disable casting of input to weight dtype during forward call + self.cast_input_dtype_enabled = True + + base_layer = self.get_base_layer() + if isinstance(base_layer, nn.Linear): + in_features, out_features = base_layer.in_features, base_layer.out_features + elif isinstance(base_layer, Conv1D): + in_features, out_features = ( + base_layer.weight.ds_shape if hasattr(base_layer.weight, "ds_shape") else base_layer.weight.shape + ) + + self.in_features = in_features + self.out_features = out_features + self.kwargs = kwargs + + @property + def merged(self) -> bool: + return bool(self.merged_adapters) + + def update_layer( + self, + adapter_name, + randlora_A: BufferDict, + randlora_B: BufferDict, + r, + randlora_alpha, + randlora_dropout, + init_weights, + inference_mode: bool = False, + **kwargs, + ): + if r <= 0: + raise ValueError(f"`r` should be a positive integer value but the value passed is {r}") + self.r[adapter_name] = r + if randlora_dropout > 0.0: + randlora_dropout_layer = nn.Dropout(p=randlora_dropout) + else: + randlora_dropout_layer = nn.Identity() + + self.randlora_dropout.update(nn.ModuleDict({adapter_name: randlora_dropout_layer})) + + # Actual trainable parameters + num_bases = min(self.in_features, self.out_features) / r + self.num_bases = int(num_bases) if num_bases.is_integer() else int(num_bases) + 1 # Full rank + self.randlora_lambda[adapter_name] = nn.Parameter(torch.randn(r, self.num_bases), requires_grad=True) + self.randlora_gamma[adapter_name] = nn.Parameter( + torch.ones(self.num_bases, min(self.out_features, self.in_features)) + / max(self.out_features, self.in_features), + requires_grad=True, + ) + + self.scaling[adapter_name] = randlora_alpha / r + + # non trainable references to randlora_A/B buffers + self.randlora_A = randlora_A + self.randlora_B = randlora_B + if adapter_name not in randlora_A: + # This means that this is not the first RandLora adapter. We have to add an entry in the dict for this adapter. + if len(self.randlora_A) < 1: + raise ValueError( + "The `randlora_A` and `randlora_B` buffers are empty. This should not happen. Please report this issue." + ) + # we can take any of the existing adapter's parameters, as they should all be identical + randlora_A_param = list(self.randlora_A.values())[0] + randlora_B_param = list(self.randlora_B.values())[0] + + error_tmpl = ( + "{} has a size of {} but {} or greater is required; this probably happened because an additional RandLora " + "adapter was added after the first one with incompatible shapes." + ) + max_dim, min_dim = max(self.in_features, self.out_features), min(self.in_features, self.out_features) + # check input size + if randlora_B_param.shape[0] < max_dim: + raise ValueError(error_tmpl.format("randlora_B", randlora_B_param.shape[0], max_dim)) + # check output size + if randlora_A_param.shape[-1] < min_dim: + raise ValueError(error_tmpl.format("randlora_A", randlora_A_param.shape[1], min_dim)) + + # check r + error_tmpl = ( + "{} has a size of {} but {} or greater is required; this probably happened because an additional RandLora " + "adapter with a lower rank was added after the first one; loading the adapters " + "in reverse order may solve this." + ) + if randlora_A_param.shape[0] < self.r[adapter_name]: + raise ValueError(error_tmpl.format("randlora_A", randlora_A_param.shape[0], self.r[adapter_name])) + + if randlora_B_param.shape[-1] < self.r[adapter_name]: + raise ValueError(error_tmpl.format("randlora_B", randlora_B_param.shape[-1], self.r[adapter_name])) + + self.randlora_A[adapter_name] = randlora_A_param + self.randlora_B[adapter_name] = randlora_B_param + + if init_weights: + self.reset_randlora_parameters(adapter_name) + + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def reset_randlora_parameters(self, adapter_name): + if adapter_name in self.randlora_lambda.keys(): + with torch.no_grad(): + nn.init.zeros_(self.randlora_lambda[adapter_name]) + nn.init.constant_(self.randlora_gamma[adapter_name], 1 / max(self.randlora_gamma[adapter_name].shape)) + + +class Linear(nn.Linear, RandLoraLayer): + # RandLora implemented in a dense layer + def __init__( + self, + base_layer, + randlora_A: BufferDict, + randlora_B: BufferDict, + adapter_name: str, + r: int = 0, + randlora_alpha: int = 0, + randlora_dropout: float = 0.0, + fan_in_fan_out: bool = False, # Set this to True if the layer to replace stores weight like (fan_in, fan_out) + is_target_conv_1d_layer: bool = False, + init_weights: bool = True, + **kwargs, + ) -> None: + # this gets the init from nn.Linear's super perspective, i.e. nn.Module.__init__, which should always be called + super(nn.Linear, self).__init__() + RandLoraLayer.__init__(self, base_layer, **kwargs) + self.fan_in_fan_out = fan_in_fan_out + self._active_adapter = adapter_name + self.update_layer(adapter_name, randlora_A, randlora_B, r, randlora_alpha, randlora_dropout, init_weights) + self.is_target_conv_1d_layer = is_target_conv_1d_layer + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`list[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults + to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter in self.randlora_lambda.keys(): + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.dtype + + if safe_merge: + # Note that safe_merge will be slower than the normal merge + # because of the copy operation. + orig_weights = base_layer.weight.data.clone() + + orig_weights += self.get_delta_weight(active_adapter) + + if not torch.isfinite(orig_weights).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = orig_weights.to(orig_dtype) + else: + delta_weight = self.get_delta_weight(active_adapter) + base_layer.weight.data += delta_weight.to(orig_dtype) + + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + while len(self.merged_adapters) > 0: + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.dtype + active_adapter = self.merged_adapters.pop() + if active_adapter in self.randlora_lambda.keys(): + delta_weight = self.get_delta_weight(active_adapter) + base_layer.weight.data -= delta_weight.to(orig_dtype) + + def get_scaled_bases(self, adapter, device=None) -> tuple[torch.Tensor, torch.Tensor]: + """ + Performs scaling on the smallest random base (randlora_A) and returns randlora_A and randlora_B in the correct + order to fit the target layers' dimensions + + Args: + adapter (str): + The name of the adapter for which the delta weight should be computed. + """ + + randlora_A = self.randlora_A[adapter] + randlora_B = self.randlora_B[adapter] + if device is None: + device = randlora_B.device + dtype = randlora_B.dtype + + # In case users wants to merge the adapter weights that are in + # (b)float16 while being on CPU, we need to cast the weights to float32, perform the merge and then cast back to + # (b)float16 because some CPUs have slow bf16/fp16 matmuls. + cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16) + + randlora_lambda = self.randlora_lambda[adapter].to(device) + randlora_gamma = self.randlora_gamma[adapter].to(device) + + if cast_to_fp32: + randlora_A = randlora_A.float() + randlora_B = randlora_B.float() + randlora_lambda = randlora_lambda.float() + randlora_gamma = randlora_gamma.float() + + # The trainable parameters are always applied to randlora_A, the smallest basis. + min_dim, max_dim = min(self.out_features, self.in_features), max(self.out_features, self.in_features) + + # As adapted layers may have different shapes and RandLora contains a single shared pair of A and B matrices, + # we initialize these matrices with the largest required size for each dimension. + # During the forward pass, required submatrices are sliced out from the shared randlora_A and randlora_B. + sliced_A = randlora_A[:, : self.num_bases, :min_dim].to(device) + sliced_B = randlora_B[:max_dim, : self.num_bases, :].to(device) + + # Flattening the matrices over the rank and number of bases dimensions is more memory efficient + update_B = sliced_B.flatten(start_dim=1) + update_A = UniqueBaseGrad.apply(sliced_A, randlora_lambda, randlora_gamma).flatten(end_dim=1) + + # 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. + if min_dim == self.in_features: + return update_A, update_B + return update_B.T, update_A.T + + def get_delta_weight(self, adapter) -> torch.Tensor: + """ + Compute the delta weight for the given adapter. + + Args: + adapter (str): + The name of the adapter for which the delta weight should be computed. + """ + + update_B, update_A = self.get_scaled_bases(adapter) + + update = (update_B.T @ update_A.T).T + output_tensor = transpose(update, self.fan_in_fan_out) + + scaling = self.scaling[adapter] + return output_tensor * scaling + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + previous_dtype = x.dtype + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + for active_adapter in self.active_adapters: + if active_adapter not in self.randlora_lambda.keys(): + continue + dropout = self.randlora_dropout[active_adapter] + update_B, update_A = self.get_scaled_bases(active_adapter, device=x.device) + x = x.to(update_A.dtype) + scaling = self.scaling[active_adapter] + result = result + F.linear(F.linear(dropout(x), update_B), update_A) * scaling + result = result.to(previous_dtype) + return result + + def supports_lora_conversion(self, adapter_name: str = "default") -> bool: + return True + + def __repr__(self) -> str: + rep = super().__repr__() + return "randlora." + rep diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/randlora/model.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/randlora/model.py new file mode 100644 index 0000000000000000000000000000000000000000..3146438f3821aba61ac94c8e31243b00eb748011 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/randlora/model.py @@ -0,0 +1,356 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import math +import warnings +from typing import Union + +import torch +import torch.nn as nn +from accelerate.utils.imports import is_bf16_available +from transformers.pytorch_utils import Conv1D + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available +from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer +from peft.utils import ( + TRANSFORMERS_MODELS_TO_RANDLORA_TARGET_MODULES_MAPPING, +) + +from .._buffer_dict import BufferDict +from ..tuners_utils import _maybe_include_all_linear_layers +from .config import RandLoraConfig +from .layer import Linear, RandLoraLayer + + +def _kaiming_init( + tensor_or_shape: Union[torch.Tensor, tuple[int, ...]], + generator: torch.Generator, +) -> torch.Tensor: + """ + Kaiming Uniform Initialisation adapted to accept a `torch.Generator` object for PRNG. + + Args: + tensor_or_shape (`Union[torch.Tensor, tuple[int, ...]]`): + Tensor to initialise, or shape of new tensor to create and then initialise. + generator: (`torch.Generator`): + Generator object that manages the state of the PRNG algorithm in use. + + Returns: + `torch.Tensor`: The initialised tensor. + """ + if isinstance(tensor_or_shape, tuple): + tensor = torch.empty( + tensor_or_shape, + dtype=torch.bfloat16 if is_bf16_available() else torch.float16, + ) + else: + tensor = tensor_or_shape + + with torch.no_grad(): + basis = torch.nn.init.kaiming_uniform_(tensor, a=math.sqrt(5), generator=generator) + return basis + + +class RandLoraModel(BaseTuner): + """ + Creates a RandLoRA model from a pretrained transformers model. + + Args: + model ([`~transformers.PreTrainedModel`]): The model to be adapted. + config ([`RandLoraConfig`]): The configuration of the RandLora model. + adapter_name (`str`): The name of the adapter, defaults to `"default"`. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the loading process. + + Returns: + `torch.nn.Module`: The RandLora model. + + Example: + + ```py + >>> from transformers import AutoModelForCausalLM + >>> from peft import RandLoraConfig, get_peft_model + + >>> base_model = AutoModelForCausalLM.from_pretrained("facebook/opt-125m") + >>> config = RandLoraConfig(r=32) + >>> model = get_peft_model(base_model, config) + ``` + + **Attributes**: + - **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted. + - **peft_config** ([`RandLoraConfig`]): The configuration of the RandLora model. + """ + + prefix: str = "randlora_" + tuner_layer_cls = RandLoraLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_RANDLORA_TARGET_MODULES_MAPPING + + def _find_dim(self, config) -> tuple[int, int]: + """ + Finds the largest input and output dimensions across linear layers that have been wrapped with RandLora. + + This will be used for determining the size of the shared randlora_A and randlora_B matrices. + """ + model_config = self.get_model_config(self.model) + + peft_config = self._prepare_adapter_config(config, model_config) + peft_config = _maybe_include_all_linear_layers(peft_config, self.model) + + largest_shape = None + for key, module in self.model.named_modules(): + if not self._check_target_module_exists(peft_config, key): + continue + + if isinstance(module, nn.Linear): + module_shape = module.out_features, module.in_features + elif isinstance(module, Conv1D): + module_shape = module.weight.ds_shape if hasattr(module.weight, "ds_shape") else module.weight.shape + module_shape = module_shape[::-1] + else: + continue + + if largest_shape is None: + largest_shape = module_shape + continue + + if module_shape != largest_shape: + largest_shape = tuple(max(a, b) for a, b in zip(largest_shape, module_shape)) + + if largest_shape is None: + msg = "No layers types compatible with RandLora were found. Please check `peft_config.target_modules`." + raise ValueError(msg) + + return largest_shape + + def _init_randlora_A_randlora_B_sparse(self, config: RandLoraConfig, adapter_name: str, sparsity: int = 3) -> None: + """ + Sparse random projections as described in https://cs-people.bu.edu/evimaria/cs565/kdd-rp.pdf + """ + + linear_out_dim, linear_in_dim = self._find_dim(config) + max_dim, min_dim = max(linear_out_dim, linear_in_dim), min(linear_out_dim, linear_in_dim) + + # use of persistent to exclude randlora_A and randlora_B from the state dict if we choose not to save them. + self.randlora_A = BufferDict({}, persistent=config.save_projection) + self.randlora_B = BufferDict({}, persistent=config.save_projection) + + # deterministic init of randlora_A and randlora_B if we know the key + generator = torch.Generator(device="cpu").manual_seed(config.projection_prng_key) + + # The gamma matrix is applied on A meaning it can be unique (shared) across the n scaling matrices. + # We also set randlora_A as the smallest matrix to reduce trainable parameters. + randlora_A = torch.rand((config.r, 1, min_dim), generator=generator) + + # Number of bases to ensure full rank + num_bases = min_dim / config.r + num_bases = int(num_bases) if num_bases.is_integer() else int(num_bases) + 1 # Ensure full rank + randlora_B = torch.rand((max_dim, num_bases, config.r), generator=generator) + + # The current implementation is a proof of concept and does take into consideration + # the sparsity to reduce memory usage or speed up compute + randlora_B_sparse = torch.zeros(randlora_B.shape) + randlora_A_sparse = torch.zeros(randlora_A.shape) + randlora_B_sparse[randlora_B < 1 / (2 * sparsity)] = -1 + randlora_B_sparse[randlora_B > 1 - 1 / (2 * sparsity)] = 1 + randlora_A_sparse[randlora_A < 1 / (2 * sparsity)] = -1 + randlora_A_sparse[randlora_A > 1 - 1 / (2 * sparsity)] = 1 + + # Std normalization is empirically found to be the best + randlora_A, randlora_B = ( + randlora_A_sparse / randlora_A_sparse.std(), + randlora_B_sparse / randlora_B_sparse.std(), + ) + self.randlora_A[adapter_name] = randlora_A + self.randlora_B[adapter_name] = randlora_B + + def _init_randlora_A_randlora_B(self, config: RandLoraConfig, adapter_name: str) -> None: + linear_out_dim, linear_in_dim = self._find_dim(config) + max_dim, min_dim = max(linear_out_dim, linear_in_dim), min(linear_out_dim, linear_in_dim) + + # use of persistent to exclude randlora_A and randlora_B from the state dict if we choose not to save them. + self.randlora_A = BufferDict({}, persistent=config.save_projection) + self.randlora_B = BufferDict({}, persistent=config.save_projection) + + # deterministic init of randlora_A and randlora_B if we know the key + generator = torch.Generator(device="cpu").manual_seed(config.projection_prng_key) + + # The gamma matrix is applied on A meaning it can be unique (shared) across the n scaling matrices. + # We also set randlora_A as the smallest matrix to reduce trainable parameters. + randlora_A = _kaiming_init((config.r, 1, min_dim), generator=generator) + + # Ensure full rank + num_bases = min(linear_out_dim, linear_in_dim) / config.r + num_bases = int(num_bases) if num_bases.is_integer() else int(num_bases) + 1 + randlora_B = torch.cat( + [_kaiming_init((max_dim, 1, config.r), generator=generator) for _ in range(num_bases)], dim=1 + ) + + # Std normalization is empirically found to be the best + randlora_A, randlora_B = randlora_A / randlora_A.std(), randlora_B / randlora_B.std() + self.randlora_A[adapter_name] = randlora_A + self.randlora_B[adapter_name] = randlora_B + + def _pre_injection_hook(self, model: nn.Module, config: RandLoraConfig, adapter_name: str) -> None: + if config.very_sparse: + linear_out_dim, linear_in_dim = self._find_dim(config) + self._init_randlora_A_randlora_B_sparse( + config, adapter_name, sparsity=math.sqrt(min(linear_out_dim, linear_in_dim)) + ) + elif config.sparse: + self._init_randlora_A_randlora_B_sparse(config, adapter_name, sparsity=3) + else: + self._init_randlora_A_randlora_B(config, adapter_name) + + def _check_new_adapter_config(self, config: RandLoraConfig) -> None: + """ + A helper method to check the config when a new adapter is being added. + + Raise a ValueError if there is something wrong with the config or if it conflicts with existing adapters. + + """ + super()._check_new_adapter_config(config) + + for existing_config in self.peft_config.values(): + if existing_config is config: + # skip the current config + continue + + if existing_config.projection_prng_key != config.projection_prng_key: + raise ValueError( + f"RandLora PRNG initialisation key must be the same for all adapters. Got {config.projection_prng_key=} but " + f"previous config had {existing_config.projection_prng_key}." + ) + + save_project_unique_values = sorted({config.save_projection for config in self.peft_config.values()}) + if len(save_project_unique_values) > 1: + raise ValueError( + "RandLora projection weights must be saved for all adapters or none, but got multiple different values: " + f"{save_project_unique_values}" + ) + + def _create_and_replace( + self, + randlora_config, + adapter_name, + target, + target_name, + parent, + current_key, + **optional_kwargs, + ): + if current_key is None: + raise ValueError("Current Key shouldn't be `None`") + + r = randlora_config.r + bias = hasattr(target, "bias") and target.bias is not None + kwargs = { + "r": r, + "randlora_alpha": randlora_config.randlora_alpha, + "randlora_dropout": randlora_config.randlora_dropout, + "fan_in_fan_out": randlora_config.fan_in_fan_out, + "init_weights": randlora_config.init_weights, + "loaded_in_8bit": getattr(self.model, "is_loaded_in_8bit", False), + "loaded_in_4bit": getattr(self.model, "is_loaded_in_4bit", False), + } + kwargs["bias"] = bias + if isinstance(target, Linear): + target.update_layer( + adapter_name, + self.randlora_A, + self.randlora_B, + r, + randlora_config.randlora_alpha, + randlora_config.randlora_dropout, + randlora_config.init_weights, + ) + else: + new_module = self._create_new_module( + randlora_config, self.randlora_A, self.randlora_B, adapter_name, target, **kwargs + ) + if adapter_name not in self.active_adapter: + # adding an additional adapter: it is not automatically trainable + new_module.requires_grad_(False) + self._replace_module(parent, target_name, new_module, target) + + @staticmethod + def _create_new_module(randlora_config, randlora_A, randlora_B, adapter_name, target, **kwargs): + # avoid eager bnb import + if is_bnb_available(): + import bitsandbytes as bnb + + from .bnb import Linear8bitLt + + if is_bnb_4bit_available(): + from .bnb import Linear4bit + + bias = kwargs.pop("bias", False) + loaded_in_8bit = kwargs.get("loaded_in_8bit", False) + loaded_in_4bit = kwargs.get("loaded_in_4bit", False) + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if loaded_in_8bit and isinstance(target_base_layer, bnb.nn.Linear8bitLt): + eightbit_kwargs = kwargs.copy() + eightbit_kwargs.update( + { + "has_fp16_weights": target_base_layer.state.has_fp16_weights, + "threshold": target_base_layer.state.threshold, + "index": target_base_layer.index, + } + ) + return Linear8bitLt(target, adapter_name, randlora_A, randlora_B, **eightbit_kwargs) + elif loaded_in_4bit and isinstance(target_base_layer, bnb.nn.Linear4bit): + fourbit_kwargs = kwargs.copy() + fourbit_kwargs.update( + { + "compute_dtype": target_base_layer.compute_dtype, + "compress_statistics": target_base_layer.weight.compress_statistics, + "quant_type": target_base_layer.weight.quant_type, + } + ) + return Linear4bit(target, adapter_name, randlora_A, randlora_B, **fourbit_kwargs) + elif isinstance(target_base_layer, torch.nn.Linear): + if kwargs["fan_in_fan_out"]: + warnings.warn( + "fan_in_fan_out is set to True but the target module is `torch.nn.Linear`. " + "Setting fan_in_fan_out to False." + ) + kwargs["fan_in_fan_out"] = randlora_config.fan_in_fan_out = False + elif isinstance(target_base_layer, Conv1D): + kwargs["is_target_conv_1d_layer"] = True + if not kwargs["fan_in_fan_out"]: + warnings.warn( + "fan_in_fan_out is set to False but the target module is `Conv1D`. Setting fan_in_fan_out to True." + ) + kwargs["fan_in_fan_out"] = randlora_config.fan_in_fan_out = True + else: + raise ValueError( + f"Target module {target} is not supported. Currently, only the following modules are supported: " + "`torch.nn.Linear`, `transformers.pytorch_utils.Conv1D`." + ) + new_module = Linear( + target, + randlora_A, + randlora_B, + adapter_name, + bias=bias, + **kwargs, + ) + + return new_module diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/shira/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/shira/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d5391b96059fc08580a12adb8b216b3a8bfd8024 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/shira/__init__.py @@ -0,0 +1,27 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from peft.utils import register_peft_method + +from .config import ShiraConfig +from .layer import Linear, ShiraLayer +from .model import ShiraModel + + +__all__ = ["Linear", "ShiraConfig", "ShiraLayer", "ShiraModel"] + + +register_peft_method( + name="shira", config_cls=ShiraConfig, model_cls=ShiraModel, prefix="shira_", is_mixed_compatible=True +) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/shira/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/shira/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3802384bb46a092108841589084a45e7b17f9230 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/shira/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/shira/__pycache__/config.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/shira/__pycache__/config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..108a83488749427fcf044aaf3521a88f383668d9 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/shira/__pycache__/config.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/shira/__pycache__/layer.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/shira/__pycache__/layer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e943d1fdbdf43d929cdd8ed5e6b4ed43bd7f0d6e Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/shira/__pycache__/layer.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/shira/__pycache__/mask_functions.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/shira/__pycache__/mask_functions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6ceba83c956c413aaed13c9ebfa39edd18d0e7a Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/shira/__pycache__/mask_functions.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/shira/__pycache__/model.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/shira/__pycache__/model.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1676fc76e7271962beabb7940e7cdd398a18441f Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/shira/__pycache__/model.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/shira/config.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/shira/config.py new file mode 100644 index 0000000000000000000000000000000000000000..d868e51490637c47c13b3c0ae2cb1f5c88cb7ebc --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/shira/config.py @@ -0,0 +1,129 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import warnings +from dataclasses import dataclass, field +from typing import Literal, Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + +from .mask_functions import random_mask + + +@dataclass +class ShiraConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`ShiraModel`]. + + Args: + r (`int`, *optional*, defaults to `32`): + For a given target module, the number of SHiRA parameters is computed as r(m+n), where the original tensor + dimensions are m x n. This means the number of SHiRA parameters is the same as that for a LoRA adapter. + SHiRA is a high rank adapter. Setting this r parameter does not restrict the rank to this value. + mask_type (`str`, defaults to `random`): + Type of mask function. Defaults to a random sparse mask. An optional user-defined mask_fn to compute the + mask value can also be supplied by instantiating `config = ShiraConfig(...)` and then setting + `config.mask_fn = `. For a pretrained weight with shape m x n, the custom mask + function must return only one mask (shape: m x n) which must be binary 0 or 1 with num_shira_parameters = + r(m + n) for linear layers. Device and dtype of mask must be same as base layer's weight's device and + dtype. Please see mask_functions.py for more details and to see the default random sparse mask + implementation. + random_seed (`int`, *optional*, defaults to `None`): + random seed for the torch generator for random_mask. + target_modules (`Union[List[str], str]`): + List of module names or regex expression of the module names to replace with SHiRA. For example, ['q', 'v'] + or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'. Only linear layers are supported. + fan_in_fan_out (`bool`): + Set this to True if the layer to replace stores weight like (fan_in, fan_out). For example, gpt-2 uses + `Conv1D` which stores weights like (fan_in, fan_out) and hence this should be set to `True`. + init_weights (`bool`, defaults to `True`): + 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. + modules_to_save (`List[str]`): + List of modules apart from SHiRA layers to be set as trainable and saved in the final checkpoint. + """ + + r: int = field( + default=32, + metadata={ + "help": ( + "For a given target module, the number of SHiRA parameters is computed as r(m+n), where the original " + "tensor dimensions are m x n. This means the number of SHiRA parameters is the same as that for a LoRA adapter. " + "SHiRA is a high rank adapter. Setting this r parameter does not restrict the rank to this value." + ) + }, + ) + mask_type: Literal["random"] = field( + default="random", + metadata={ + "help": ( + "Type of mask function. Defaults to a random sparse mask. " + "An optional user-defined mask_fn to compute the mask value can also be supplied by instantiating `config = ShiraConfig(...)` and then setting " + "`config.mask_fn = `. For a pretrained weight with shape m x n, the custom mask function must return only one mask (shape: m x n) " + "which must be binary 0 or 1 with num_shira_parameters = r(m + n) for linear layers. Device and dtype of mask must be same as base layer's weight's device and dtype. " + "Please see mask_functions.py for more details and to see the default random sparse mask implementation." + ) + }, + ) + random_seed: Optional[int] = field( + default=None, metadata={"help": "random seed for the torch generator for random_mask"} + ) + target_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": ( + "List of module names or regex expression of the module names to replace with SHiRA." + "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'. " + "Only linear layers are supported." + ) + }, + ) + fan_in_fan_out: bool = field( + default=False, + metadata={"help": "Set this to True if the layer to replace stores weight like (fan_in, fan_out)"}, + ) + init_weights: bool = field( + default=True, + metadata={ + "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." + }, + ) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": ( + "List of modules apart from SHiRA layers to be set as trainable and saved in the final checkpoint. For" + " example, in Sequence Classification or Token Classification tasks, the final layer" + " `classifier/score` are randomly initialized and as such need to be trainable and saved." + ) + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.SHIRA + self.target_modules = ( + set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules + ) + if self.mask_type == "random": + self.mask_fn = random_mask + else: + if not self.inference_mode: + warnings.warn( + f"Argument {self.mask_type=} is not recognized, please supply your own masking function by calling `config.mask_fn = my_mask_fn`." + ) + self.mask_fn = None diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/shira/layer.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/shira/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..ff5626ccdcd8c367a009bc55d6c2efc6c6d1ea30 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/shira/layer.py @@ -0,0 +1,221 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import copy +import warnings +from typing import Optional + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge + + +class ShiraLayer(BaseTunerLayer): + # List all names of layers that may contain trainable adapter weights + adapter_layer_names = ("shira_weight",) + # All names of other adapter-related parameters + other_param_names = ("r", "scaling", "shira_indices") + + def __init__(self, base_layer: nn.Module, **kwargs): + self.base_layer = base_layer + self.r = {} + self.scaling = {} + self.shira_weight = nn.ParameterDict({}) + self.shira_indices = {} + self.weight_shape = base_layer.weight.shape # Assumes SHiRA is on some layer with "weight" parameter + + # Mark the weight as unmerged + self._disable_adapters = False + self.merged_adapters = [] + + base_layer = self.get_base_layer() + if isinstance(base_layer, nn.Linear): + in_features, out_features = base_layer.in_features, base_layer.out_features + else: + raise NotImplementedError("Only nn.Linear layers supported currently") + + self.in_features = in_features + self.out_features = out_features + self.kwargs = kwargs + + def update_layer( + self, + adapter_name, + mask, + r, + init_weights: bool = True, + inference_mode: bool = False, + **kwargs, + ): + if r <= 0: + raise ValueError(f"`r` should be a positive integer value but the value passed is {r}") + self.r[adapter_name] = r + self.scaling[adapter_name] = ( + 1.0 # Default scale during training. Can be set to any (non-negative) value during inference. + ) + # 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) + num_shira_weight = r * (self.in_features + self.out_features) + if num_shira_weight > self.in_features * self.out_features: + raise ValueError( + 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." + ) + + # Actual trainable parameters + # We have used a vector parameter with fixed indices that we use inside a torch.sparse_coo_tensor in get_delta_weight function. + # Directly using a torch.sparse_coo_tensor as a parameter could have been possible but we ran into some issues similar to: + # https://github.com/pytorch/pytorch/issues/79542. + shira_init_weight = torch.zeros(num_shira_weight) if init_weights else torch.randn(num_shira_weight) + self.shira_weight[adapter_name] = nn.Parameter( + shira_init_weight.to(self.base_layer.weight.dtype).to(self.base_layer.weight.device), + requires_grad=True, + ) + + if mask is not None: + # 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. + mask_indices = torch.where(mask == 1.0) + self.shira_indices[adapter_name] = torch.cat( + [mask_indices[0].unsqueeze(0), mask_indices[1].unsqueeze(0)], 0 + ).to(torch.int) + self.shira_indices[adapter_name] = self.shira_indices[adapter_name].to(self.base_layer.weight.device) + + if self.shira_indices[adapter_name].shape[1] != self.shira_weight[adapter_name].shape[0]: + raise ValueError( + f"The SHiRA indices and weights are not the same dimensions for adapter {adapter_name} in layer {self.base_layer}" + ) + + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def reset_shira_parameters(self, adapter_name): + nn.init.zeros_(self.shira_weight[adapter_name]) + + def set_scale(self, adapter, scale): + if adapter not in self.scaling: + # Ignore the case where the adapter is not in the layer + return + self.scaling[adapter] = scale + + +class Linear(nn.Module, ShiraLayer): + # SHiRA implemented in a dense layer + def __init__( + self, + base_layer, + mask, + adapter_name: str, + r: int = 0, + fan_in_fan_out: bool = False, # Set this to True if the layer to replace stored weight like (fan_in, fan_out) + init_weights: bool = True, + **kwargs, + ) -> None: + super().__init__() + ShiraLayer.__init__(self, base_layer, **kwargs) + self.fan_in_fan_out = fan_in_fan_out + if self.base_layer is not self.get_base_layer(): + raise ValueError("SHiRA does not support nested base layers") + + self._active_adapter = adapter_name + self.update_layer(adapter_name, mask, r, init_weights=init_weights) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`List[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults + to `None`. + """ + + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter in self.shira_weight.keys(): + base_layer = self.get_base_layer() + if safe_merge: + # Note that safe_merge will be slower than the normal merge + # because of the copy operation. + orig_weights = base_layer.weight.data.clone() + + orig_weights += self.get_delta_weight(active_adapter) + + if not torch.isfinite(orig_weights).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = orig_weights + else: + base_layer.weight.data += self.get_delta_weight(active_adapter) + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter in self.shira_weight.keys(): + self.get_base_layer().weight.data -= self.get_delta_weight(active_adapter) + + def get_delta_weight(self, adapter) -> torch.Tensor: + """ + Compute the delta weight for the given adapter. + + Args: + adapter (str): + The name of the adapter for which the delta weight should be computed. + """ + + # In multi-gpu environment, the indices are at the wrong gpu. This is needed to correct this. + self.shira_indices[adapter] = self.shira_indices[adapter].to(self.shira_weight[adapter].device) + return torch.sparse_coo_tensor( + self.shira_indices[adapter], self.shira_weight[adapter] * self.scaling[adapter], self.weight_shape + ) + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + new_weight = copy.deepcopy(self.base_layer.weight.data) + for active_adapter in self.active_adapters: + if active_adapter not in self.shira_weight.keys(): + continue + new_weight += self.get_delta_weight(active_adapter) + + result = F.linear(x, new_weight, bias=self.base_layer.bias) + + return result + + def supports_lora_conversion(self, adapter_name: str = "default") -> bool: + # delta weight is sparse, which does not work with SVD + return False + + def __repr__(self) -> str: + rep = super().__repr__() + return "shira." + rep diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/shira/mask_functions.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/shira/mask_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..d8afbfa8ed23589c74306b0d6e2da071e2f64a11 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/shira/mask_functions.py @@ -0,0 +1,72 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +This module is intended to store mask functions for use inside SHiRA construction. The mask functions are required to +have a specific signature as shown below. + +Required positional arguments: + base_layer - This is the linear layer where the shira adapter will be attached. r - This parameter is used to + determine the number of parameters in the + shira adapter in a way that is consistent with LoRA sizing. SHiRA is a high rank adapter. Setting this + parameter does not restrict the adapter rank. +Keyword arguments can be provided as needed by the particular mask function implementation. + +Return: + mask - this is a torch.tensor of the same shape as base_layer.weight that contains 0s and 1s with the same + dtype and device as base_layer.weight + +If you would like to attach SHiRA adapters to a model using PEFT methods (such as get_peft_model()), using more +arguments than the provided positional arguments, you can create the mask function reference like the following: + +``` + def create_mask_function_reference(**my_kwargs): + def mask_fn(base_layer, r): + ... your implementation here that might use my_kwargs ... + return mask + return mask_fn +``` +Then, you can create your peft model with custom SHiRA mask as follows: +``` + model = ... + my_kwargs = ... + mask_fn = create_mask_function_reference(**my_kwargs) + peft_config = ShiraConfig(r=4, mask_type='my_custom_mask') + peft_config.mask_fn = mask_fn + peft_model = get_peft_model(model, peft_config) +``` + +Complete training examples are provided in the examples/shira/ directory. +""" + +from typing import Optional + +import torch +import torch.nn as nn + + +def random_mask(base_layer: nn.Module, r: int, random_seed: Optional[int] = None, **kwargs) -> torch.tensor: + shape = base_layer.weight.shape + num_shira_weights = r * (shape[0] + shape[1]) + random_generator = torch.Generator() + if random_seed is not None: + random_generator.manual_seed(random_seed) + idx = (torch.randperm(base_layer.weight.numel(), generator=random_generator)[:num_shira_weights]).to( + base_layer.weight.device + ) + val = torch.ones_like(idx.type(base_layer.weight.dtype)) + mask = torch.zeros_like(base_layer.weight.view(1, -1)) + mask = mask.scatter_(1, idx.unsqueeze(0), val.unsqueeze(0)).view(shape) + + return mask diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/shira/model.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/shira/model.py new file mode 100644 index 0000000000000000000000000000000000000000..c212a9bf2c110bba5a180eaf2cac0bda9a93ee6e --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/shira/model.py @@ -0,0 +1,142 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import warnings + +import torch + +from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer +from peft.utils import ( + TRANSFORMERS_MODELS_TO_SHIRA_TARGET_MODULES_MAPPING, +) + +from .layer import Linear, ShiraLayer + + +class ShiraModel(BaseTuner): + """ + Creates a Sparse High Rank Adapter (SHiRA) Model from a pretrained model. + + Args: + model ([`~transformers.PreTrainedModel`]): The model to be adapted. + config ([`ShiraConfig`]): The configuration of the SHiRA model. + adapter_name (`str`): The name of the adapter, defaults to `"default"`. + + Returns: + `torch.nn.Module`: The SHiRA model. + + Example: + + ```py + >>> from transformers import AutoModelForCausalLM + >>> from peft import ShiraConfig, get_peft_model + + >>> base_model = AutoModelForCausalLM.from_pretrained("facebook/opt-125m") + >>> config = ShiraConfig(r=32) + >>> model = get_peft_model(base_model, config) + ``` + + **Attributes**: + - **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted. + - **peft_config** ([`ShiraConfig`]): The configuration of the SHiRA model. + """ + + prefix: str = "shira_" + tuner_layer_cls = ShiraLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_SHIRA_TARGET_MODULES_MAPPING + + def _create_and_replace( + self, + shira_config, + adapter_name, + target, + target_name, + parent, + current_key, + **optional_kwargs, + ): + if current_key is None: + raise ValueError("Current Key shouldn't be `None`") + + bias = hasattr(target, "bias") and target.bias is not None + kwargs = {} + kwargs["bias"] = bias + if shira_config.mask_type == "random": + kwargs["random_seed"] = shira_config.random_seed + + for k, v in optional_kwargs.items(): + kwargs[k] = v + + if isinstance(target, Linear): + mask = ( + shira_config.mask_fn(target.base_layer, shira_config.r, **kwargs) + if shira_config.mask_fn is not None + else None + ) + target.update_layer( + adapter_name, + mask, + shira_config.r, + init_weights=shira_config.init_weights, + ) + else: + new_module = self._create_new_module(shira_config, adapter_name, target, **kwargs) + if adapter_name not in self.active_adapter: + # adding an additional adapter: it is not automatically trainable + new_module.requires_grad_(False) + self._replace_module(parent, target_name, new_module, target) + + @staticmethod + def _create_new_module(shira_config, adapter_name, target, **kwargs): + fan_in_fan_out = shira_config.fan_in_fan_out + + _ = kwargs.pop("bias", False) + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if isinstance(target_base_layer, torch.nn.Linear): + if fan_in_fan_out: + warnings.warn( + "fan_in_fan_out is set to True but the target module is `torch.nn.Linear`. " + "Setting fan_in_fan_out to False." + ) + fan_in_fan_out = shira_config.fan_in_fan_out = False + else: + raise ValueError( + f"Target module {target} is not supported. Currently, only the following modules are supported: " + "`torch.nn.Linear`." + ) + + mask = ( + shira_config.mask_fn(target_base_layer, shira_config.r, **kwargs) + if shira_config.mask_fn is not None + else None + ) + + new_module = Linear( + target, + mask, + adapter_name, + shira_config.r, + fan_in_fan_out, + init_weights=shira_config.init_weights, + **kwargs, + ) + + return new_module diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/trainable_tokens/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/trainable_tokens/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4aa7bf8e5fc4705cb7b190cee0de53ac8db89573 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/trainable_tokens/__init__.py @@ -0,0 +1,33 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from peft.utils import register_peft_method + +from .config import TrainableTokensConfig +from .layer import TrainableTokensLayer +from .model import TrainableTokensModel + + +__all__ = [ + "TrainableTokensConfig", + "TrainableTokensLayer", + "TrainableTokensModel", +] + +register_peft_method( + name="trainable_tokens", + config_cls=TrainableTokensConfig, + model_cls=TrainableTokensModel, + is_mixed_compatible=False, +) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/trainable_tokens/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/trainable_tokens/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..326f99f481bda213a593c33362f644f8e0a5b437 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/trainable_tokens/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/trainable_tokens/__pycache__/config.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/trainable_tokens/__pycache__/config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a78da9a7ccedbebe96e751775684f033c9cf0d9 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/trainable_tokens/__pycache__/config.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/trainable_tokens/__pycache__/layer.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/trainable_tokens/__pycache__/layer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9a3c629a5bb6f68ae97b8ccf4ae11f77ab55c77 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/trainable_tokens/__pycache__/layer.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/trainable_tokens/__pycache__/model.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/trainable_tokens/__pycache__/model.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a9fa8d3549aafbcf75675d64496b250f91e38dd7 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/trainable_tokens/__pycache__/model.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/trainable_tokens/config.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/trainable_tokens/config.py new file mode 100644 index 0000000000000000000000000000000000000000..7412d7f06474c510679e0f3004ae10c20910b00f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/trainable_tokens/config.py @@ -0,0 +1,89 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class TrainableTokensConfig(PeftConfig): + """ + Configuration for the `TrainableTokens` method. + + Allows for training new tokens (and re-training existing ones) without training the full embedding matrix. By + marking a few select tokens (identified by their indices) trainable and leaving the rest untouched, this method can + be used to add new tokens or changing the embedding of existing tokens while saving on memory. Both storage as well + as working memory usage are reduced in contrast to training the embedding matrix fully. + + Note that training with FSDP/DeepSpeed might not yet be fully supported. + + Args: + token_indices (`list[int]`): + List of integers, signifying the indices of the tokens you want to be trainable. To find the index of a + token with a tokenizer, you can tokenize the string and look at the returned `input_ids`. The closer the + amount of indices is to the total amount of tokens, the less efficient this method gets. + target_modules (`Optional[Union[list[str], str]]`): + List of module names or regex expression of the module names to replace with our `TrainableTokensLayer`. If + not defined, it will attempt to get the model's input embedding layer if the model has a + `get_input_embeddings` method (transformer models usually do), if that fails the default is 'embed_tokens'. + Other example targets are `embedding`, `encoder.embeddings` or `decoder.embeddings`. + init_weights (`bool`): + By default the new token weights are initialized to be the same as the respective token embeddings. This + makes TrainableTokens a no-op when not trained. If set to `False` the weights will be random values. Do not + change this setting unless you know exactly what you're doing. + """ + + token_indices: list[int] = field( + default_factory=list, + metadata={ + "help": ( + "List of integers, signifying the indices of the tokens you want to be trainable. " + "To find the index of a token with a tokenizer, you can tokenize the string and " + "look at the returned `input_ids`. The closer the amount of indices is to the total amount of " + "tokens, the less efficient this method gets." + ) + }, + ) + target_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": ( + "List of module names or regex expression of the module names to replace with our " + "`TrainableTokensLayer`. If not defined, it will default to the model's input embedding layer if " + "the model has a `get_input_embeddings` method (transformer models usually do), if that fails the " + "default is 'embed_tokens'. Other example targets could be `embedding`, `encoder.embeddings` or " + "`decoder.embeddings`." + ), + }, + ) + + init_weights: bool = field( + default=True, + metadata={ + "help": ( + "By default the new token weights are initialized to be the same as the respective token embeddings. " + "This makes TrainableTokens a no-op when not trained. If set to `False` the weights will be random " + "values. Do not change this setting unless you know exactly what you're doing. " + ) + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.TRAINABLE_TOKENS diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/trainable_tokens/layer.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/trainable_tokens/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..78c8df40912f66369d245679658076492843cb4e --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/trainable_tokens/layer.py @@ -0,0 +1,262 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import warnings +from typing import Optional + +import torch +import torch.distributed as dist +import torch.nn as nn +import torch.nn.functional as F + +from peft.tuners._buffer_dict import BufferDict +from peft.tuners.tuners_utils import BaseTunerLayer, _get_in_out_features, check_adapters_to_merge +from peft.utils.integrations import check_deepspeed_zero3_enabled, gather_params_ctx + + +class TrainableTokensLayer(nn.Module, BaseTunerLayer): + # All names of layers that may contain (trainable) adapter weights + adapter_layer_names = ("trainable_tokens_delta",) + + # All names of other parameters that may contain adapter-related parameters + other_param_names = ("token_indices", "trainable_tokens_original") + + def __init__( + self, + base_layer: nn.Module, + adapter_name: str, + token_indices: list[int], + tied_adapter: Optional[TrainableTokensLayer] = None, + **kwargs, + ) -> None: + super().__init__() + + self.base_layer = base_layer + self._active_adapter = adapter_name + self.kwargs = kwargs + + # wrap the tied adapter in a list so that it is excluded from .(named_)modules() and, therefore, + # not included in the state dict since it would be a copy of the tied adapter anyway. + self._tied_adapter = [tied_adapter] if tied_adapter else [] + + # we store the updated weights of particular tokens and their originals. we assume + # that the count of new tokens is far smaller than the number of total tokens. + # + # In case we have weight tying with another token adapter, we'll have no actual + # references on our own but use everything from the tied adapter. + if not self.tied_adapter: + self.trainable_tokens_delta = nn.ParameterDict({}) + self.trainable_tokens_original = BufferDict({}) + self.token_indices = {} + else: + self.trainable_tokens_delta = self.tied_adapter.trainable_tokens_delta + self.trainable_tokens_original = self.tied_adapter.trainable_tokens_original + self.token_indices = self.tied_adapter.token_indices + + # Mark the weight as unmerged + self.merged_adapters = [] + + in_features, out_features = _get_in_out_features(self.get_base_layer()) + self.in_features = in_features + self.out_features = out_features + + @property + def tied_adapter(self): + if self._tied_adapter: + return self._tied_adapter[0] + return None + + def _collect_token_weights(self, weight: torch.Tensor, rows: torch.Tensor, embed_dim: int) -> torch.Tensor: + """DeepSpeed zero3 specific code to initialize trainable tokens. + + Ensures that only the necessary weights are collected to a single rank, initialized, and then shared with all + ranks. + """ + src_rank = 0 + # right now, only CUDA is implemented + device = torch.device("cuda", torch.cuda.current_device()) + + with gather_params_ctx([weight], modifier_rank=None): + if dist.is_available() and dist.is_initialized() and dist.get_rank() == src_rank: + token_weights = weight[rows].clone() + else: + # build an empty tensor with correct shape/type/device + token_weights = torch.empty( + (len(rows), embed_dim), + dtype=weight.dtype, + device=device, + ) + + # share the weights with all ranks + dist.broadcast(token_weights, src=src_rank) + return token_weights + + def update_layer(self, adapter_name, **kwargs): + if kwargs.get("tied_adapter", None): + # as a tied adapter, we're just following whatever the adpater we're tied to does, we don't update anything. + return + + self.token_indices[adapter_name] = kwargs["token_indices"] + init_weights = kwargs.get("init_weights", True) + + # we initialize the delta embedding weights from the base embedding matrix and replace values instead of + # adding/subtracting deltas. we do it this way and use `embedding.weight.index_copy()` to write the updated + # values during `forward()` to avoid that the user resizing the embedding matrix, effectively filling the new + # token space with random values, training the model with TrainableTokensLayer, initializing the model anew - + # thus re-initializing the new embeddings again with new random variables. If we would add/subtract deltas + # onto the new values, we would get undefined behavior. By replacing the specific token values we always + # get defined behavior. + weight = self.get_base_layer().weight + + if hasattr(self.get_base_layer(), "embedding_dim"): + embed_dim = self.get_base_layer().embedding_dim + else: + # lm_head doesn't have embedding_dim attribute + embed_dim = self.get_base_layer().in_features + + if init_weights: + if check_deepspeed_zero3_enabled(): + values = self._collect_token_weights(weight, self.token_indices[adapter_name], embed_dim) + else: + values = self.weight[self.token_indices[adapter_name]] + else: + # random init with matching dtype/device + values = torch.randn( + (len(self.token_indices[adapter_name]), embed_dim), + dtype=weight.dtype, + device=weight.device, + ) + + self.trainable_tokens_delta[adapter_name] = nn.Parameter(values.clone(), requires_grad=True) + self.trainable_tokens_original[adapter_name] = values.clone() + + self._move_adapter_to_device_of_base_layer(adapter_name) + + def _check_overlapping_tokens(self, adapter_names): + """Raises an error if the token indices of the given adapter names are overlapping. + This is currently not supported and can lead to undefined behavior of the model if no specific merging between + the overlapping indices' values is applied. + """ + if len(adapter_names) <= 1: + return + + indices = set() + + # we take already merged adapters into account as well since they can be overridden by new adapters as well. + for adapter_name in set(adapter_names + self.merged_adapters): + index_set = set(self.token_indices[adapter_name]) + if len(indices.intersection(index_set)): + raise ValueError( + f"Token indices of adapter {adapter_name} are already defined and would result in " + "undefined merging behavior. Only disjunct token indices are currently supported." + ) + indices.update(index_set) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + adapter_names = check_adapters_to_merge(self, adapter_names) + + if not adapter_names: + # no adapter to merge + return + + self._check_overlapping_tokens(adapter_names) + + merged = self.base_layer.weight.data + + for adapter_name in adapter_names: + index = torch.tensor(self.token_indices[adapter_name]).to(merged.device) + deltas = self.trainable_tokens_delta[adapter_name].to(merged) + merged = merged.index_copy(dim=0, index=index, source=deltas) + + if safe_merge and not torch.isfinite(merged).all(): + raise ValueError(f"NaNs detected in the merged weights. The adapter {adapter_name} seems to be broken") + + self.base_layer.weight.data = merged + self.merged_adapters.extend(adapter_names) + + def unmerge(self) -> None: + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + while len(self.merged_adapters) > 0: + adapter_name = self.merged_adapters.pop() + + index = torch.tensor(self.token_indices[adapter_name]).to(self.base_layer.weight.device) + originals = self.trainable_tokens_original[adapter_name].to(self.base_layer.weight) + self.base_layer.weight.data.index_copy_(dim=0, index=index, source=originals) + + def get_merged_weights(self, active_adapters) -> torch.Tensor: + W = self.base_layer.weight + + for adapter_name in active_adapters: + index = torch.tensor(self.token_indices[adapter_name]).to(W.device) + deltas = self.trainable_tokens_delta[adapter_name].to(W) + W = W.index_copy(dim=0, index=index, source=deltas) + + # Note: the return type is a Tensor, not an nn.Parameter. This can lead to some errors, e.g. torch's + # model.get_parameter fails as it does a type check. But we cannot return an nn.Parameter here, as it can lead + # to other failures, as this is not a true nn.Parameter of the model. + return W + + def forward_adapters(self, x: torch.Tensor, active_adapters, *args, **kwargs) -> torch.Tensor: + if self.disable_adapters or not active_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + self._check_overlapping_tokens(active_adapters) + + W = self.get_merged_weights(active_adapters) + + # Normally it should be very clear that we're wrapping Embedding layers but there are cases, such as + # tying weights with an LM head where the layer we wrap is a Linear layer. Therefore we must choose + # accordingly. + # + # TODO: the isinstance checks, especially the one for nn.Linear, may not hold for quantized layers; + # TODO: we may need to find a better way to detect quantized layers. + if isinstance(self.base_layer, torch.nn.Embedding): + result = F.embedding( + input=x, + weight=W, + padding_idx=self.base_layer.padding_idx, + max_norm=self.base_layer.max_norm, + norm_type=self.base_layer.norm_type, + scale_grad_by_freq=self.base_layer.scale_grad_by_freq, + sparse=self.base_layer.sparse, + ) + # Some embedding layers (e.g., Gemma3TextScaledWordEmbedding) apply scaling in their forward method. + # Since we're using F.embedding directly, we need to apply this scaling manually. + embed_scale = self._get_embed_scale() + if embed_scale is not None: + result = result * embed_scale.to(result.dtype) + elif isinstance(self.base_layer, torch.nn.Linear): + # Probably a tied adapter that wraps an LM head. + result = F.linear( + input=x, + weight=W, + ) + else: + raise ValueError( + "TrainableTokensLayer wraps an unknown layer type, maybe you are targeting the wrong layer?" + ) + + return result + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + return self.forward_adapters(x, self.active_adapters, *args, **kwargs) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/trainable_tokens/model.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/trainable_tokens/model.py new file mode 100644 index 0000000000000000000000000000000000000000..a3a7c7ae520eab045a2dd1449fa1bb9785578f51 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/peft/tuners/trainable_tokens/model.py @@ -0,0 +1,153 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import torch.nn as nn + +from peft.config import PeftConfig +from peft.tuners.tuners_utils import BaseTuner +from peft.utils import _get_input_embeddings_name, _get_submodules + +from .layer import TrainableTokensLayer + + +class TrainableTokensModel(BaseTuner): + prefix: str = "trainable_tokens_" + tuner_layer_cls = TrainableTokensLayer + + def _prepare_adapter_config(self, peft_config, model_config): + # target_modules can be none which prompts us to infer the embedding layer name ourselves. + if peft_config.target_modules is None: + peft_config.target_modules = _get_input_embeddings_name(self.model, "embed_tokens") + + return peft_config + + def inject_adapter( + self, + model: nn.Module, + adapter_name: str, + autocast_adapter_dtype: bool = True, + low_cpu_mem_usage: bool = False, + **kwargs, + ) -> None: + super().inject_adapter( + model=model, + adapter_name=adapter_name, + autocast_adapter_dtype=autocast_adapter_dtype, + low_cpu_mem_usage=low_cpu_mem_usage, + **kwargs, + ) + + model_config = self.get_model_config(self) + + # In case of weight-tying we need to adapt the tied weights as well and use tie the embedding adapter. + # + # The TrainableTokensLayer supports being tied to another TrainableTokensLayer meaning that the layer will + # not do any changes on its own but solely rely on the weights from the tied adapter. We will search for the + # tied weights and put tied TrainableTokensLayer adapters on them, all tied to the adapter of the embedding + # matrix. + tied_weights_module_names = self._get_module_names_tied_with_embedding() + + if ( + tied_weights_module_names + and model_config.get("tie_word_embeddings", False) + and isinstance(self.model.get_input_embeddings(), TrainableTokensLayer) + ): + # disable removing of duplicates since we're essentially only dealing with duplicates (i.e. tied weights) + for name, module in self.model.named_modules(remove_duplicate=False): + matched_keys = [target_key for target_key in tied_weights_module_names if name.endswith(target_key)] + if matched_keys: + parent, target, target_name = _get_submodules(model, name) + + # If the module is already a TrainableTokensLayer, we need to replace it with a tied version + # instead of just updating it. This handles the case where the user explicitly targeted + # both the embedding and tied layers in target_modules. + if isinstance(target, TrainableTokensLayer): + # Replace the existing layer with a new one that's tied to the embedding + peft_config = self.peft_config[adapter_name].to_dict() + peft_config["tied_adapter"] = self.model.get_input_embeddings() + + new_module = self._create_new_module( + peft_config, adapter_name, target.base_layer, **peft_config + ) + self._replace_module(parent, target_name, new_module, target.base_layer) + else: + # Module hasn't been wrapped yet, create and replace normally + peft_config = self.peft_config[adapter_name].to_dict() + peft_config["tied_adapter"] = self.model.get_input_embeddings() + + self._create_and_replace_dict( + peft_config, + adapter_name, + target, + target_name, + parent, + matched_keys[0], + ) + + def _get_tied_target_modules(self, *args, **kwargs): + # Normally this method would return the layers that target tied layers. + # + # We override this method since we explicitly support tied weights tied to the embedding layer. + # Therefore, we don't need the warning issued by returning the modules here. + return [] + + def _create_and_replace_dict( + self, + peft_config: dict, + adapter_name: str, + target: nn.Module, + target_name: str, + parent: nn.Module, + current_key: str, + ) -> None: + """ + The same as `_create_and_replace` but takes a dictionary instead of a peft config so that we can add keys that + are not present in the config, such as `tied_adapter`. + """ + kwargs = peft_config + + if isinstance(target, TrainableTokensLayer): + target.update_layer(adapter_name, **kwargs) + else: + new_module = self._create_new_module(peft_config, adapter_name, target, **kwargs) + self._replace_module(parent, target_name, new_module, target) + + def _create_and_replace( + self, + peft_config: PeftConfig, + adapter_name: str, + target: nn.Module, + target_name: str, + parent: nn.Module, + current_key: str, + ) -> None: + """ + A private method to create and replace the target module with the adapter module. + """ + kwargs = peft_config.to_dict() + self._create_and_replace_dict(kwargs, adapter_name, target, target_name, parent, current_key) + + @staticmethod + def _create_new_module(peft_config, adapter_name, target, **kwargs): + new_module = TrainableTokensLayer(target, adapter_name, **kwargs) + new_module.update_layer( + adapter_name, + init_weights=kwargs["init_weights"], + token_indices=kwargs["token_indices"], + tied_adapter=kwargs.get("tied_adapter", None), + ) + + return new_module