diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/method_comparison/text_generation_benchmark/temporary_results/.gitkeep b/tasks/tasksmith-749ff8d440e1/environment/source/method_comparison/text_generation_benchmark/temporary_results/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/method_comparison/text_generation_benchmark/utils.py b/tasks/tasksmith-749ff8d440e1/environment/source/method_comparison/text_generation_benchmark/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a84a33ef4480b9ed2897e12af08d98cae0f2769b --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/method_comparison/text_generation_benchmark/utils.py @@ -0,0 +1,458 @@ +# 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 PEFT benchmarking. +""" + +import datetime +import json +import os +import platform +import subprocess +from collections.abc import Callable +from dataclasses import asdict, dataclass, field +from enum import Enum +from typing import Any, Optional + +import psutil +import torch + +from peft.utils import infer_device + + +FILE_NAME_BENCHMARK_PARAMS = "benchmark_params.json" +FILE_NAME_DEFAULT_CONFIG = "default_benchmark_params.json" + +RESULT_PATH = os.path.join(os.path.dirname(__file__), "results") +RESULT_PATH_TEMP = os.path.join(os.path.dirname(__file__), "temporary_results") +RESULT_PATH_CANCELLED = os.path.join(os.path.dirname(__file__), "cancelled_results") + + +class BenchmarkStatus(Enum): + """Status of a benchmark run.""" + + SUCCESS = "success" + FAILED = "failed" + CANCELLED = "cancelled" + RUNNING = "running" + + +@dataclass +class BenchmarkResult: + """Container for benchmark results.""" + + experiment_name: str + status: BenchmarkStatus + + model_id: str + + run_info: dict = field(default_factory=dict) + generation_info: dict = field(default_factory=dict) + meta_info: dict = field(default_factory=dict) + + def __post_init__(self): + """Initialize structured data format.""" + device = infer_device() + torch_accelerator_module = getattr(torch, device, torch.cuda) + self.run_info = { + "timestamp": datetime.datetime.now(tz=datetime.timezone.utc).isoformat(), + "duration": 0.0, + "status": self.status.value, + "hardware": { + "num_accelerators": torch_accelerator_module.device_count() if torch_accelerator_module.is_available() else 0, + "accelerator_type": torch_accelerator_module.get_device_name(0) if torch_accelerator_module.is_available() else "N/A", + "cuda_version": torch.version.cuda if torch.cuda.is_available() else "N/A", + "pytorch_version": torch.__version__, + }, + } + + self.meta_info = { + "model_id": self.model_id, + "parameters": { + "base_params": 0, + "trainable_params": 0, + "total_params": 0, + "param_ratio": 0.0, + }, + "model_size": { + "base_model_size_mb": 0.0, + "adapter_size_mb": 0.0, + }, + "package_info": { + "transformers-version": None, + "transformers-commit-hash": None, + "peft-version": None, + "peft-commit-hash": None, + "datasets-version": None, + "datasets-commit-hash": None, + "bitsandbytes-version": None, + "bitsandbytes-commit-hash": None, + "torch-version": torch.__version__, + "torch-commit-hash": None, + }, + "system_info": { + "system": platform.system(), + "release": platform.release(), + "version": platform.version(), + "machine": platform.machine(), + "processor": platform.processor(), + "accelerator": torch_accelerator_module.get_device_name(0) if torch_accelerator_module.is_available() else "N/A", + }, + } + + self.generation_info = { + "memory": { + "peak_accelerator_memory_mb": 0.0, + "peak_ram_memory_mb": 0.0, + "memory_logs": [], + }, + "by_category": {}, + "overall": {}, + } + + def update_meta_info(self, param_counts: dict, size_info: dict, package_info: Optional[dict] = None): + """Update model metadata information.""" + self.meta_info["parameters"].update(param_counts) + self.meta_info["model_size"].update(size_info) + if package_info: + self.meta_info["package_info"].update(package_info) + + def update_generation_info(self, memory_data: Optional[dict] = None, performance_metrics: Optional[dict] = None): + """Update generation performance information, primarily for memory and high-level performance.""" + if memory_data: + self.generation_info["memory"].update(memory_data) + if performance_metrics: # For things like overall tokens/sec if calculated + self.generation_info.update(performance_metrics) + + def add_memory_log(self, stage: str, ram_mb: float, accelerator_allocated_mb: float, accelerator_reserved_mb: float): + """Add a memory usage log entry to generation_info.""" + self.generation_info["memory"]["memory_logs"].append( + { + "stage": stage, + "ram_mb": ram_mb, + "accelerator_allocated_mb": accelerator_allocated_mb, + "accelerator_reserved_mb": accelerator_reserved_mb, + } + ) + + def add_metrics_for_category(self, category: str, metrics: dict, individual_samples: Optional[list] = None): + """Add metrics for a specific prompt category under generation_info.""" + category_data = {"metrics": metrics, "samples": individual_samples if individual_samples is not None else []} + self.generation_info["by_category"][category] = category_data + + def update_run_info( + self, + duration: float, + status: BenchmarkStatus, + error: Optional[str] = None, + peft_config: Optional[dict] = None, + benchmark_config: Optional[dict] = None, + ): + """Update run information.""" + self.run_info["duration"] = duration + self.run_info["status"] = status.value + if error: + self.run_info["error"] = error + if peft_config: + self.run_info["peft_config"] = peft_config + if benchmark_config: + self.run_info["benchmark_config"] = benchmark_config + + def compute_overall_metrics(self): + """Compute overall metrics across all categories within generation_info.""" + if not self.generation_info["by_category"]: + return + + categories = self.generation_info["by_category"] + key_metrics = [ + "inference_time", + "base_inference_time", + "inference_overhead_pct", + "time_per_token", + "generated_tokens", + ] + + for metric in key_metrics: + values = [] + for category_data in categories.values(): + if "metrics" in category_data and metric in category_data["metrics"]: + values.append(category_data["metrics"][metric]) + + if values: + self.generation_info["overall"][metric] = sum(values) / len(values) + + def to_dict(self) -> dict[str, Any]: + """Convert result to dictionary.""" + self.compute_overall_metrics() + return { + "run_info": self.run_info, + "generation_info": self.generation_info, + "meta_info": self.meta_info, + } + + def save(self, path: Optional[str] = None): + """Save result to JSON file.""" + if path is None: + peft_branch = get_peft_branch() + if self.status == BenchmarkStatus.CANCELLED: + base_path = RESULT_PATH_CANCELLED + elif peft_branch != "main": + base_path = RESULT_PATH_TEMP + elif self.status == BenchmarkStatus.SUCCESS: + base_path = RESULT_PATH + elif self.status == BenchmarkStatus.FAILED: + base_path = RESULT_PATH_CANCELLED + else: + base_path = RESULT_PATH_TEMP + + filename = f"{self.experiment_name}.json" + path = os.path.join(base_path, filename) + + os.makedirs(os.path.dirname(path), exist_ok=True) + + with open(path, "w") as f: + json.dump(self.to_dict(), f, indent=2) + + return path + + +@dataclass +class BenchmarkConfig: + """Configuration for benchmarking PEFT methods.""" + + model_id: str + + seed: int + num_inference_runs: int + max_new_tokens: int + + dtype: str = "float16" + use_4bit: bool = False + use_8bit: bool = False + + category_generation_params: Optional[dict] = None + + def __post_init__(self) -> None: + """Validate configuration.""" + if not isinstance(self.model_id, str): + raise TypeError(f"Invalid model_id: {self.model_id}") + + if self.seed < 0: + raise ValueError(f"Invalid seed: {self.seed}") + + if self.num_inference_runs <= 0: + raise ValueError(f"Invalid num_inference_runs: {self.num_inference_runs}") + + if self.max_new_tokens <= 0: + raise ValueError(f"Invalid max_new_tokens: {self.max_new_tokens}") + + @classmethod + def from_dict(cls, config_dict: dict) -> "BenchmarkConfig": + """Create config from dictionary.""" + valid_keys = set(cls.__dataclass_fields__.keys()) + filtered_dict = {k: v for k, v in config_dict.items() if k in valid_keys} + + return cls(**filtered_dict) + + @classmethod + def from_json(cls, json_path: str) -> "BenchmarkConfig": + """Load config from JSON file.""" + with open(json_path) as f: + config_dict = json.load(f) + return cls.from_dict(config_dict) + + def to_dict(self) -> dict[str, Any]: + """Convert config to dictionary.""" + result = asdict(self) + return result + + def save(self, path: str) -> None: + """Save config to JSON file.""" + with open(path, "w") as f: + json.dump(self.to_dict(), f, indent=2) + + def merge_from_dict(self, config_dict: dict) -> None: + """Merge settings from a dictionary into this config object. + Keys in config_dict will override existing attributes. + """ + for key, value in config_dict.items(): + if hasattr(self, key): + setattr(self, key, value) + + +def validate_experiment_path(path: str) -> tuple[str, "BenchmarkConfig"]: + """Validate experiment path, load and merge configs, and return them.""" + if not os.path.exists(path): + raise FileNotFoundError(f"Experiment path not found: {path}") + + path_parts = os.path.normpath(path).split(os.sep) + + try: + experiments_idx = path_parts.index("experiments") + except ValueError: + experiment_name = os.path.basename(path.rstrip(os.sep)) + else: + if experiments_idx + 1 < len(path_parts): + method_name = path_parts[experiments_idx + 1] + remaining_parts = path_parts[experiments_idx + 2 :] + if remaining_parts: + remaining_name = "-".join(remaining_parts) + experiment_name = f"{method_name}--{remaining_name}" + else: + experiment_name = method_name + else: + experiment_name = os.path.basename(path.rstrip(os.sep)) + + default_config_path = os.path.join(os.path.dirname(__file__), FILE_NAME_DEFAULT_CONFIG) + experiment_benchmark_params_path = os.path.join(path, FILE_NAME_BENCHMARK_PARAMS) + + if not os.path.exists(default_config_path): + raise FileNotFoundError(f"Default configuration file not found: {default_config_path}. This is required.") + benchmark_config = BenchmarkConfig.from_json(default_config_path) + print(f"Loaded default configuration from {default_config_path}") + + if os.path.exists(experiment_benchmark_params_path): + with open(experiment_benchmark_params_path) as f: + experiment_specific_params = json.load(f) + + benchmark_config.merge_from_dict(experiment_specific_params) + print(f"Loaded and merged experiment-specific parameters from {experiment_benchmark_params_path}") + else: + print(f"No {FILE_NAME_BENCHMARK_PARAMS} found in {path}. Using only default configuration.") + + return experiment_name, benchmark_config + + +def get_memory_usage() -> tuple[float, float, float]: + """Get current memory usage (RAM and accelerator).""" + process = psutil.Process(os.getpid()) + ram_usage_bytes = process.memory_info().rss + ram_usage_mb = ram_usage_bytes / (1024 * 1024) + + if torch.cuda.is_available(): + accelerator_allocated = torch.cuda.memory_allocated() + accelerator_reserved = torch.cuda.memory_reserved() + accelerator_allocated_mb = accelerator_allocated / (1024 * 1024) + accelerator_reserved_mb = accelerator_reserved / (1024 * 1024) + elif torch.xpu.is_available(): + accelerator_allocated = torch.xpu.memory_allocated() + accelerator_reserved = torch.xpu.memory_reserved() + accelerator_allocated_mb = accelerator_allocated / (1024 * 1024) + accelerator_reserved_mb = accelerator_reserved / (1024 * 1024) + else: + accelerator_allocated_mb = 0.0 + accelerator_reserved_mb = 0.0 + + return ram_usage_mb, accelerator_allocated_mb, accelerator_reserved_mb + + +def init_accelerator() -> tuple[float, float]: + """Initialize accelerator and return initial memory usage.""" + if torch.cuda.is_available(): + torch.cuda.init() + torch.cuda.empty_cache() + _, accelerator_allocated, accelerator_reserved = get_memory_usage() + elif torch.xpu.is_available(): + torch.xpu.init() + torch.xpu.empty_cache() + _, accelerator_allocated, accelerator_reserved = get_memory_usage() + else: + accelerator_allocated = 0.0 + accelerator_reserved = 0.0 + return accelerator_allocated, accelerator_reserved + + +def get_model_size_mb(model: torch.nn.Module, dtype_bytes: int = 4) -> float: + """Calculate model size in MB.""" + return sum(p.numel() * dtype_bytes for p in model.parameters()) / (1024 * 1024) + + +def get_peft_branch() -> str: + repo_root = os.path.dirname(__file__) + return subprocess.check_output(["git", "rev-parse", "--abbrev-ref", "HEAD"], cwd=repo_root).decode().strip() + + +def log_results( + experiment_name: str, + benchmark_result: BenchmarkResult, + print_fn: Callable = print, +) -> None: + """Log benchmark results to console.""" + print_fn("\n" + "=" * 50) + print_fn(f"Benchmark Results: {experiment_name}") + print_fn("=" * 50) + + print_fn(f"Status: {benchmark_result.run_info.get('status', 'N/A')}") + print_fn(f"Duration: {benchmark_result.run_info.get('duration', 0):.2f} seconds") + + if benchmark_result.run_info.get("status") != BenchmarkStatus.SUCCESS.value: + print_fn(f"Error: {benchmark_result.run_info.get('error', 'Unknown error')}") + print_fn("=" * 50) + return + + print_fn("\nModel Information:") + print_fn(f" Base Model: {benchmark_result.meta_info.get('model_id', 'N/A')}") + + print_fn("\nParameter Counts:") + params = benchmark_result.meta_info.get("parameters", {}) + print_fn(f" Base Parameters: {params.get('base_params', 0):,}") + print_fn(f" Trainable Parameters: {params.get('trainable_params', 0):,}") + print_fn(f" Parameter Ratio: {params.get('param_ratio', 0):.5%}") + + print_fn("\nModel Size:") + size_info = benchmark_result.meta_info.get("model_size", {}) + print_fn(f" Base Model: {size_info.get('base_model_size_mb', 0):.2f} MB") + print_fn(f" Adapter: {size_info.get('adapter_size_mb', 0):.2f} MB") + + print_fn("\nMemory Usage (from generation_info):") + memory_data = benchmark_result.generation_info.get("memory", {}) + print_fn(f" Peak Accelerator Memory: {memory_data.get('peak_accelerator_memory_mb', 0):.2f} MB") + print_fn(f" Peak RAM Memory: {memory_data.get('peak_ram_memory_mb', 0):.2f} MB") + + print_fn("\nDetailed Metrics (from generation_info.by_category):") + if benchmark_result.generation_info.get("by_category"): + for category, cat_data in benchmark_result.generation_info["by_category"].items(): + print_fn(f" Category: {category}") + metrics = cat_data.get("metrics", {}) + print_fn(f" Inference Time: {metrics.get('inference_time', 0):.4f} seconds") + print_fn(f" Base Inference Time: {metrics.get('base_inference_time', 0):.4f} seconds") + print_fn(f" Inference Overhead: {metrics.get('inference_overhead_pct', 0):.2f}%") + print_fn(f" Time Per Token: {metrics.get('time_per_token', 0):.6f} seconds/token") + print_fn(f" Generated Tokens: {metrics.get('generated_tokens', 0):.1f}") + + samples = cat_data.get("samples", []) + if samples: + print_fn(f" Number of Samples: {len(samples)}") + print_fn( + f" Average Generated Tokens: {sum(s.get('generated_tokens', 0) for s in samples) / len(samples):.1f}" + ) + else: + print_fn(" No per-category metrics available.") + + benchmark_result.compute_overall_metrics() + + print_fn("\nOverall Metrics (from generation_info.overall):") + overall = benchmark_result.generation_info.get("overall") + if overall: + print_fn(f" Inference Time: {overall.get('inference_time', 0):.4f} seconds") + print_fn(f" Base Inference Time: {overall.get('base_inference_time', 0):.4f} seconds") + print_fn(f" Inference Overhead: {overall.get('inference_overhead_pct', 0):.2f}%") + print_fn(f" Time Per Token: {overall.get('time_per_token', 0):.6f} seconds/token") + print_fn(f" Generated Tokens: {overall.get('generated_tokens', 0):.1f}") + else: + print_fn(" No overall metrics computed.") + + print_fn("\nSaved results to:", benchmark_result.save()) + print_fn("=" * 50) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/pyproject.toml b/tasks/tasksmith-749ff8d440e1/environment/source/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..2be1aebdfb13e704c099f64d47c1d300ffc513fb --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/pyproject.toml @@ -0,0 +1,67 @@ +[tool.black] +# Only used by `hf-doc-builder´. +line-length = 119 +target-version = ['py310'] + +[tool.ruff] +target-version = "py310" +line-length = 119 +extend-exclude = ["*.ipynb"] +required-version = "~=0.15.12" + +[tool.ruff.lint] +preview = true +explicit-preview-rules = true +extend-select = [ + "C", # Complexity + "E", # PEP8 errors + "F", # PEP8 formatting + "I", # Import sorting + "UP", # Pyupgrade upgrades + "W", # PEP8 warnings + "PT009", # Pytest assertions + "RUF022", # Sorting of __all__ +] +ignore = [ + "C901", # Function too complex + "E501", # Line length (handled by ruff-format) + "F841", # unused variable + "UP007", # X | Y style Unions + "C420", # dict.fromkeys + "UP045", # don't force replacing Optional[X] with X | None + "SIM118", # `for key in dct.keys()` is allowed + "PLC0206", # allow iterating over dict keys and pulling values later, can be more consistent + "RUF012", # allow mutable default values, contrary to popular belief, not always evil + "B018", # a "useless expression" is not useless when it tests for an AttributeError + "SIM117", # allow nesting of `with` statements: can be *more* readable of they are long + "BLE001", # allow catching bare `Exception` + "SIM102", # collapse multiple `if` statements: nice to have but requires too many changes + "PYI041", # considers type annotations like int|float as redundant and wants float only, but type can carry semantic meaning (e.g. total number vs fraction) +] + +[tool.ruff.lint.isort] +lines-after-imports = 2 +known-first-party = ["peft"] + +[tool.pytest] +doctest_optionflags = [ + "NORMALIZE_WHITESPACE", + "ELLIPSIS", + "NUMBER", +] + +addopts = ["--cov=src/peft", "--cov-report=term-missing", "--durations=10"] + +markers = [ + "single_gpu_tests: tests that run on a single GPU", + "multi_gpu_tests: tests that run on multiple GPUs", + "regression: whether to run regression suite test", + "bitsandbytes: select bitsandbytes integration tests", +] + +filterwarnings = [ + "error::DeprecationWarning:transformers", + # in sync with tests/conftest.py regarding BPE deprecation + "ignore:.*BPE.__init__ will not create from files anymore.*:DeprecationWarning:transformers", + "error::FutureWarning:transformers", +] diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/requirements.txt b/tasks/tasksmith-749ff8d440e1/environment/source/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..dca857de3249b60ea3786b49156d14166cd57ac0 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/requirements.txt @@ -0,0 +1,15 @@ +accelerate +torch +safetensors +bitsandbytes +scipy +peft +transformers +tqdm +packaging +pytest +numpy +pyyaml +datasets +psutil +setuptools \ No newline at end of file diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/scripts/ci_clean_cache.py b/tasks/tasksmith-749ff8d440e1/environment/source/scripts/ci_clean_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..ccedc6887e400523839ce3a749efa2fa0d1061c4 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/scripts/ci_clean_cache.py @@ -0,0 +1,68 @@ +""" +Utility to clean cache files that exceed a specific time in days according to their +last access time recorded in the cache. + +Exit code: +- 1 if no candidates are found +- 0 if candidates are found + +Deletion can be enabled by passing `-d` parameter, otherwise it will only list the candidates. +""" + +import sys +from datetime import datetime as dt +from datetime import timezone + +from huggingface_hub import scan_cache_dir + + +def find_old_revisions(scan_results, max_age_days=30): + """Find commit hashes of objects in the cache. These objects need a last access time that + is above the passed `max_age_days` parameter. Returns an empty list if no objects are found. + Time measurement is based of the current time and the recorded last access tiem in the cache. + """ + now = dt.now(timezone.utc) + revisions = [(i.revisions, i.last_accessed) for i in scan_results.repos] + revisions_ages = [(rev, (now - dt.fromtimestamp(ts_access, timezone.utc)).days) for rev, ts_access in revisions] + delete_candidates = [rev for rev, age in revisions_ages if age > max_age_days] + hashes = [n.commit_hash for rev in delete_candidates for n in rev] + + return hashes + + +def delete_old_revisions(scan_results, delete_candidates, do_delete=False): + delete_operation = scan_results.delete_revisions(*delete_candidates) + print(f"Would free {delete_operation.expected_freed_size_str}") + print(f"Candidates: {delete_candidates}") + + if do_delete: + print("Deleting now.") + delete_operation.execute() + else: + print("Not deleting, pass the -d flag.") + + +if __name__ == "__main__": + from argparse import ArgumentParser + + parser = ArgumentParser() + parser.add_argument("-a", "--max-age", type=int, default=30, help="Max. age in days items in the cache may have.") + parser.add_argument( + "-d", + "--delete", + action="store_true", + help=( + "Delete mode; Really delete items if there are candidates. Exit code = 0 when we found something to delete, 1 " + "otherwise." + ), + ) + args = parser.parse_args() + + scan_results = scan_cache_dir() + + delete_candidates = find_old_revisions(scan_results, args.max_age) + if not delete_candidates: + print("No delete candidates found, not deleting anything.") + sys.exit(1) + + delete_old_revisions(scan_results, delete_candidates, do_delete=args.delete) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/scripts/convert-bone-to-miss.py b/tasks/tasksmith-749ff8d440e1/environment/source/scripts/convert-bone-to-miss.py new file mode 100644 index 0000000000000000000000000000000000000000..4be799f9b26e6e051c2ddcb662c85bd5ff73dcb6 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/scripts/convert-bone-to-miss.py @@ -0,0 +1,69 @@ +# Copyright (c) 2025 Your Organization/Project. All rights reserved. +# +# 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. + +"""Convert Bone checkpoint to MiSS format.""" + +import argparse +import json +import os +from pathlib import Path + +from safetensors import safe_open +from safetensors.torch import save_file + +from peft.utils import CONFIG_NAME, SAFETENSORS_WEIGHTS_NAME + + +def convert_bone_to_miss(bone_dir: Path, miss_dir: Path) -> None: + """Convert Bone checkpoint files to MiSS format.""" + bone_config_path = bone_dir / CONFIG_NAME + miss_config_path = miss_dir / CONFIG_NAME + if not os.path.exists(miss_dir): + os.makedirs(miss_dir, exist_ok=True) + with open(bone_config_path, encoding="utf-8") as f: + config = json.load(f) + + config["peft_type"] = "MISS" + + with open(miss_config_path, "w", encoding="utf-8") as f: + json.dump(config, f, indent=2, ensure_ascii=False) + + bone_weight_path = bone_dir / SAFETENSORS_WEIGHTS_NAME + miss_weight_path = miss_dir / SAFETENSORS_WEIGHTS_NAME + + new_data = {} + + with safe_open(bone_weight_path, framework="pt") as f: + for old_key in f.keys(): + tensor = f.get_tensor(old_key) + new_key = old_key.replace(".bone_", ".miss_") + new_data[new_key] = tensor + + save_file(new_data, miss_weight_path) + + print(f"Converted checkpoint saved at {miss_weight_path}") + + +def main() -> None: + parser = argparse.ArgumentParser(description="Convert Bone checkpoint to MiSS format.") + parser.add_argument("bone_dir", type=Path, help="Directory containing Bone checkpoint files") + parser.add_argument("miss_dir", type=Path, help="Directory to save MiSS checkpoint files") + args = parser.parse_args() + + args.miss_dir.mkdir(parents=True, exist_ok=True) + convert_bone_to_miss(args.bone_dir, args.miss_dir) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/scripts/evaluate-lora-conversion.py b/tasks/tasksmith-749ff8d440e1/environment/source/scripts/evaluate-lora-conversion.py new file mode 100644 index 0000000000000000000000000000000000000000..a94cedde6e22661dac10741664f79e1f10541b98 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/scripts/evaluate-lora-conversion.py @@ -0,0 +1,156 @@ +# 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. + +"""Script to evaluate a PEFT checkpoint converted into a LoRA on GSM8K + +To run this script, first train a PEFT model on MetaMathQA as described here: + +https://github.com/huggingface/peft/tree/main/method_comparison/MetaMathQA + +Call the script with the `-v` (verbose) option. When that run finishes, it will save a checkpoint of that model and +print a message like this: "Saved PEFT checkpoint to ...". Use this path as the `--path` argument to this script. + +Example usage: + +```bash +# Convert to LoRA with rank 8 and evaluate it +python evaluate-lora-conversion.py --path /path/to/peft/checkpoint --rank 8 +# Convert to LoRA with dynamic rank (50% singular value threshold) and evaluate it +python evaluate-lora-conversion.py --path /path/to/peft/checkpoint --rank 0.5 +# Evaluate the original PEFT model without LoRA conversion +python evaluate-lora-conversion.py --path /path/to/peft/checkpoint +``` + +The script will report the evaluation accuracy, maximum CUDA memory reserved, and evaluation time for the converted LoRA +model. + +""" + +import argparse +import importlib.util +import os +import sys +import time + +import torch +from transformers import AutoModelForCausalLM + +from peft import PeftModel, convert_to_lora, get_peft_model, set_peft_model_state_dict + + +root = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) + +spec = importlib.util.spec_from_file_location("data", os.path.join(root, "method_comparison", "MetaMathQA", "data.py")) +mm_data = importlib.util.module_from_spec(spec) +spec.loader.exec_module(mm_data) +sys.modules["data"] = mm_data + +spec = importlib.util.spec_from_file_location( + "utils", os.path.join(root, "method_comparison", "MetaMathQA", "utils.py") +) +mm_utils = importlib.util.module_from_spec(spec) +spec.loader.exec_module(mm_utils) +sys.modules["utils"] = mm_utils + +spec = importlib.util.spec_from_file_location("run", os.path.join(root, "method_comparison", "MetaMathQA", "run.py")) +mm_run = importlib.util.module_from_spec(spec) +spec.loader.exec_module(mm_run) + + +def noop(*args, **kwargs): + pass + + +def evaluate_model(model, tokenizer, ds_test): + torch.cuda.empty_cache() + torch.cuda.reset_peak_memory_stats() + tic = time.perf_counter() + predictions, responses = mm_run.evaluate( + model=model, + tokenizer=tokenizer, + ds=ds_test, + batch_size=50, + generate_kwargs={"max_length": 800, "max_new_tokens": 300, "pad_token_id": tokenizer.eos_token_id}, + use_tqdm=True, + ) + toc = time.perf_counter() + accuracy_peft = mm_utils.get_accuracy(predictions=predictions, responses=responses) + cuda_mem_reserved_max = torch.cuda.memory_reserved(0) + print(f"Evaluation Accuracy: {100 * accuracy_peft:.2f}%") + print(f"Max CUDA Memory Reserved: {cuda_mem_reserved_max / (1024**3):.2f} GB") + print(f"Evaluation Time: {toc - tic:.0f} seconds".format(toc - tic)) + + +def main(path_peft_model: str, rank: float | None) -> None: + model_id = "meta-llama/Llama-3.2-3B" + tokenizer = mm_utils.get_tokenizer(model_id=model_id, max_seq_length=768) + _, _, ds_test = mm_data.get_train_valid_test_datasets( + tokenizer=tokenizer, query_template="Question: {query} Think step by step.\nAnswer:", print_fn=noop + ) + + model = AutoModelForCausalLM.from_pretrained(model_id, dtype=torch.bfloat16).to(0) + model = PeftModel.from_pretrained(model, path_peft_model) + if rank is None: + print("Evaluating the original PEFT model without LoRA conversion...") + model.set_adapter("default") + model.print_trainable_parameters() + model.eval() + evaluate_model(model, tokenizer, ds_test) + return + + print(f"Converting PEFT model to LoRA with rank={rank}...") + tic = time.perf_counter() + lora_config, lora_state_dict = convert_to_lora(model, rank=rank, progressbar=True) + toc = time.perf_counter() + print(f"Conversion completed in {toc - tic:.0f} seconds.".format(toc - tic)) + + del model + torch.cuda.empty_cache() + model = AutoModelForCausalLM.from_pretrained(model_id, dtype=torch.bfloat16).to(0) + + model = get_peft_model(model, lora_config) + model.print_trainable_parameters() + + load_result = set_peft_model_state_dict(model, lora_state_dict) + assert not load_result.unexpected_keys, ( + f"Unexpected keys when loading LoRA state dict: {load_result.unexpected_keys}" + ) + + del lora_state_dict + model.eval() + evaluate_model(model, tokenizer, ds_test) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Evaluate a PEFT checkpoint converted into a LoRA on GSM8K") + parser.add_argument( + "--path", + type=str, + required=True, + help="Path to the input PEFT checkpoint", + ) + parser.add_argument( + "--rank", + required=False, + default=None, + help="Rank for the LoRA decomposition (int, float, or None for no conversion)", + ) + + args = parser.parse_args() + if args.rank is not None: + if "." in str(args.rank): + args.rank = float(args.rank) + else: + args.rank = int(args.rank) + main(args.path, args.rank) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/scripts/launch_notebook_mp.py b/tasks/tasksmith-749ff8d440e1/environment/source/scripts/launch_notebook_mp.py new file mode 100644 index 0000000000000000000000000000000000000000..ce5439afa82a4220cdecbd73e545c58cd14f8442 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/scripts/launch_notebook_mp.py @@ -0,0 +1,47 @@ +# 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. + +# This is a minimal example of launching PEFT with Accelerate. This used to cause issues because PEFT would eagerly +# import bitsandbytes, which initializes CUDA, resulting in: +# > RuntimeError: Cannot re-initialize CUDA in forked subprocess. To use CUDA with multiprocessing, you must use the +# > 'spawn' start method +# This script exists to ensure that this issue does not reoccur. + +import torch +from accelerate import notebook_launcher + +import peft +from peft.utils import infer_device + + +def init(): + class MyModule(torch.nn.Module): + def __init__(self): + super().__init__() + self.linear = torch.nn.Linear(1, 2) + + def forward(self, x): + return self.linear(x) + + device = infer_device() + model = MyModule().to(device) + peft.get_peft_model(model, peft.LoraConfig(target_modules=["linear"])) + + +def main(): + notebook_launcher(init, (), num_processes=2) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/scripts/log_reports.py b/tasks/tasksmith-749ff8d440e1/environment/source/scripts/log_reports.py new file mode 100644 index 0000000000000000000000000000000000000000..2a61db8b60d3622a67f8eaad45af14e9a89f436c --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/scripts/log_reports.py @@ -0,0 +1,144 @@ +import argparse +import json +import os +from datetime import UTC, datetime +from pathlib import Path + +from tabulate import tabulate + + +MAX_LEN_MESSAGE = 2900 # slack endpoint has a limit of 3001 characters + +parser = argparse.ArgumentParser() +parser.add_argument( + "--slack_channel_name", + default="peft-ci-daily", +) + + +def main(slack_channel_name=None): + failed = [] + passed = [] + + group_info = [] + + total_num_failed = 0 + empty_file = False or len(list(Path().glob("*.log"))) == 0 + + total_empty_files = [] + + for log in Path().glob("*.log"): + section_num_failed = 0 + i = 0 + with open(log) as f: + for line in f: + line = json.loads(line) + i += 1 + if line.get("nodeid", "") != "": + test = line["nodeid"] + if line.get("duration", None) is not None: + duration = f"{line['duration']:.4f}" + if line.get("outcome", "") == "failed": + section_num_failed += 1 + failed.append([test, duration, log.name.split("_")[0]]) + total_num_failed += 1 + else: + passed.append([test, duration, log.name.split("_")[0]]) + empty_file = i == 0 + group_info.append([str(log), section_num_failed, failed]) + total_empty_files.append(empty_file) + os.remove(log) + failed = [] + text = ( + "🌞 There were no failures!" + if not any(total_empty_files) + else "Something went wrong there is at least one empty file - please check GH action results." + ) + no_error_payload = { + "type": "section", + "text": { + "type": "plain_text", + "text": text, + "emoji": True, + }, + } + + message = "" + payload = [ + { + "type": "header", + "text": { + "type": "plain_text", + "text": "🤗 Results of the {} PEFT scheduled tests.".format(os.environ.get("TEST_TYPE", "")), + }, + }, + ] + if total_num_failed > 0: + for i, (name, num_failed, failed_tests) in enumerate(group_info): + if num_failed > 0: + if num_failed == 1: + message += f"*{name}: {num_failed} failed test*\n" + else: + message += f"*{name}: {num_failed} failed tests*\n" + failed_table = [] + for test in failed_tests: + failed_table.append(test[0].split("::")) + failed_table = tabulate( + failed_table, + headers=["Test Location", "Test Case", "Test Name"], + showindex="always", + tablefmt="grid", + maxcolwidths=[12, 12, 12], + ) + message += "\n```\n" + failed_table + "\n```" + + if total_empty_files[i]: + message += f"\n*{name}: Warning! Empty file - please check the GitHub action job *\n" + print(f"### {message}") + else: + payload.append(no_error_payload) + + if os.environ.get("TEST_TYPE", "") != "": + from slack_sdk import WebClient + + if len(message) > MAX_LEN_MESSAGE: + print(f"Truncating long message from {len(message)} to {MAX_LEN_MESSAGE}") + message = message[:MAX_LEN_MESSAGE] + "..." + + if len(message) != 0: + md_report = { + "type": "section", + "text": {"type": "mrkdwn", "text": message}, + } + payload.append(md_report) + action_button = { + "type": "section", + "text": {"type": "mrkdwn", "text": "*For more details:*"}, + "accessory": { + "type": "button", + "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, + "url": f"https://github.com/huggingface/peft/actions/runs/{os.environ['GITHUB_RUN_ID']}", + }, + } + payload.append(action_button) + + date_report = { + "type": "context", + "elements": [ + { + "type": "plain_text", + "text": f"Nightly {os.environ.get('TEST_TYPE')} test results for {datetime.now(UTC).date()}", + }, + ], + } + payload.append(date_report) + + print(payload) + + client = WebClient(token=os.environ.get("SLACK_API_TOKEN")) + client.chat_postMessage(channel=f"#{slack_channel_name}", text=message, blocks=payload) + + +if __name__ == "__main__": + args = parser.parse_args() + main(args.slack_channel_name) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/scripts/stale.py b/tasks/tasksmith-749ff8d440e1/environment/source/scripts/stale.py new file mode 100644 index 0000000000000000000000000000000000000000..794ec8451282c69ae9cff18c15329b14816d707a --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/scripts/stale.py @@ -0,0 +1,65 @@ +# Copyright 2023 The HuggingFace Team, the AllenNLP library authors. All rights reserved. +# +# 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. +""" +Script to close stale issue. Taken in part from the AllenNLP repository. +https://github.com/allenai/allennlp. +""" + +import os +from datetime import datetime as dt +from datetime import timezone + +from github import Github + + +LABELS_TO_EXEMPT = [ + "good first issue", + "good second issue", + "good difficult issue", + "feature request", + "new model", + "wip", + "PRs welcome to address this", +] + + +def main(): + g = Github(os.environ["GITHUB_TOKEN"]) + repo = g.get_repo("huggingface/peft") + open_issues = repo.get_issues(state="open") + + for issue in open_issues: + comments = sorted(issue.get_comments(), key=lambda i: i.created_at, reverse=True) + last_comment = comments[0] if len(comments) > 0 else None + if ( + (last_comment is not None and last_comment.user.login == "github-actions[bot]") + and (dt.now(timezone.utc) - issue.updated_at).days > 7 + and (dt.now(timezone.utc) - issue.created_at).days >= 30 + and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels()) + ): + issue.edit(state="closed") + elif ( + (dt.now(timezone.utc) - issue.updated_at).days > 23 + and (dt.now(timezone.utc) - issue.created_at).days >= 30 + and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels()) + ): + issue.create_comment( + "This issue has been automatically marked as stale because it has not had " + "recent activity. If you think this still needs to be addressed " + "please comment on this thread.\n\n" + ) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/scripts/train_memory.py b/tasks/tasksmith-749ff8d440e1/environment/source/scripts/train_memory.py new file mode 100644 index 0000000000000000000000000000000000000000..e743bdaf7db3b84cc3767dee525ed7eab5adfbc9 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/scripts/train_memory.py @@ -0,0 +1,276 @@ +# 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 script trains a model on a small text dataset and measures the memory consumption, as well as a few other +useful metrics. + +Example: + +Get help: + +```bash +python train_memory.py --help +``` + +Train the google/gemma-2-2b model with a LoRA config json at the indicated location. + +```bash +python train_memory.py "google/gemma-2-2b" --max_seq_length 256 --batch_size 1 --rank 32 --dtype bfloat16 --path_config +``` + +Fully fine-tune the model (i.e. without LoRA) by setting the rank to 0: + +```bash +python train_memory.py "google/gemma-2-2b" --rank 0 +``` + +Get an estimate of the size of the hidden states by passing `--monitor_tensors`. This trains just for a single epoch. For realistic estimates, the batch size for this: + +```bash +python train_memory.py "google/gemma-2-2b" --max_seq_length 256 --batch_size 32 --rank 32 --dtype bfloat16 --path_config configs/lora_rank-32_embedding-lora/ --monitor_tensors +``` + +""" + +import argparse +import gc +import os +import sys +import tempfile +import time +import warnings +from collections import Counter +from contextlib import nullcontext +from functools import partial + +import torch +from datasets import load_dataset +from torch import nn +from transformers import ( + AutoModelForCausalLM, + AutoTokenizer, + BitsAndBytesConfig, +) + +from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training +from peft.utils import CONFIG_NAME, SAFETENSORS_WEIGHTS_NAME + + +# suppress all warnings +warnings.filterwarnings("ignore") + +device = torch.accelerator.current_accelerator().type if hasattr(torch, "accelerator") else "cuda" +dtype_to_bytes_linear = {"float32": 4, "float16": 2, "bfloat16": 2, "int8": 1, "int4": 0.5} + + +def init_accelerator(): + torch.manual_seed(0) + if device == "cpu": + return + + device_module = getattr(torch, device, torch.cuda) + device_module.reset_peak_memory_stats() + device_module.manual_seed_all(0) + # might not be necessary, but just to be sure + nn.Linear(1, 1).to(device) + + +def get_data(tokenizer): + def tokenize(samples): + # For some reason, the max sequence length is not honored by the tokenizer, resulting in IndexErrors. Thus, + # manually ensure that sequences are not too long. + tokenized = tokenizer(samples["quote"]) + tokenized["input_ids"] = [input_ids[: tokenizer.model_max_length] for input_ids in tokenized["input_ids"]] + tokenized["attention_mask"] = [ + input_ids[: tokenizer.model_max_length] for input_ids in tokenized["attention_mask"] + ] + return tokenized + + data = load_dataset("ybelkada/english_quotes_copy") + data = data.map(tokenize, batched=True) + # We need to manually remove unused columns. This is because we cannot use remove_unused_columns=True in the + # Trainer, as this leads to errors with torch.compile. We also cannot just leave them in, as they contain + # strings. Therefore, manually remove all unused columns. + data = data.remove_columns(["quote", "author", "tags"]) + return data + + +def train(model_id, rank, dtype, monitor_tensors, max_seq_length, batch_size, max_steps, path_config): + init_accelerator() + device_module = getattr(torch, device, torch.cuda) + accelerator_memory_init = device_module.max_memory_allocated() + accelerator_memory_log = [] + + tokenizer = AutoTokenizer.from_pretrained(model_id) + tokenizer.model_max_length = max_seq_length + if not tokenizer.pad_token: + tokenizer.pad_token = tokenizer.eos_token + data = get_data(tokenizer) + + if dtype == "int4": + quant_config = BitsAndBytesConfig(load_in_4bit=True) + model = AutoModelForCausalLM.from_pretrained(model_id, device_map=device, quantization_config=quant_config) + model = prepare_model_for_kbit_training(model) + elif dtype == "int8": + quant_config = BitsAndBytesConfig(load_in_8bit=True) + model = AutoModelForCausalLM.from_pretrained(model_id, device_map=device, quantization_config=quant_config) + model = prepare_model_for_kbit_training(model) + elif dtype == "bfloat16": + model = AutoModelForCausalLM.from_pretrained(model_id, device_map=device, torch_dtype=torch.bfloat16) + elif dtype == "float16": + model = AutoModelForCausalLM.from_pretrained(model_id, device_map=device, torch_dtype=torch.float16) + elif dtype == "float32": + model = AutoModelForCausalLM.from_pretrained(model_id, device_map=device) + else: + raise ValueError(f"Invalid dtype: {dtype}") + + if rank > 0: + if path_config is None: + raise RuntimeError("LoRA rank > 0 requires a path to a LoRA config") + if path_config.endswith(CONFIG_NAME): + path_config = path_config.removesuffix(CONFIG_NAME) + config = LoraConfig.from_pretrained(path_config) + model = get_peft_model(model, config) + model.print_trainable_parameters() + else: + print("Not using LoRA") + + model.config.use_cache = False + storage = [] + + def pack(x): + storage.append(x) + return len(storage) - 1 + + def unpack(x): + return storage[x] + + train_ctx = partial(torch.autograd.graph.saved_tensors_hooks, pack, unpack) if monitor_tensors else nullcontext + + optimizer = torch.optim.AdamW(model.parameters(), lr=1e-5) + losses = [] + sample = 0 + tic_total = time.perf_counter() + for i in range(max_steps): + storage.clear() + tic = time.perf_counter() + try: + batch = tokenizer.pad(data["train"][sample : sample + batch_size], return_tensors="pt").to(model.device) + sample += batch_size + + # add targets + batch["labels"] = batch["input_ids"].clone() + optimizer.zero_grad() + + with train_ctx(): + outputs = model(**batch) + loss = outputs.loss + loss.backward() + optimizer.step() + losses.append(loss.item()) + accelerator_memory_log.append(device_module.memory_allocated() - accelerator_memory_init) + device_module.empty_cache() + gc.collect() + toc = time.perf_counter() + print(f"step {i:3d} loss {loss.item():.6f} time {toc - tic:.2f}s", file=sys.stderr) + except KeyboardInterrupt: + print("canceled training") + break + + if monitor_tensors: + break + + toc_total = time.perf_counter() + + accelerator_memory_final = device_module.max_memory_allocated() + accelerator_memory_avg = int(sum(accelerator_memory_log) / len(accelerator_memory_log)) + print(f"{model.device.type} memory avg: {accelerator_memory_avg // 2**20}MB") + print(f"{model.device.type} memory max: {(accelerator_memory_final - accelerator_memory_init) // 2**20}MB") + print(f"total time: {toc_total - tic_total:.2f}s") + + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir) + stat = os.stat(os.path.join(tmp_dir, SAFETENSORS_WEIGHTS_NAME)) + file_size = stat.st_size + print(f"file size: {file_size / 2**20:.1f}MB") + + if monitor_tensors: + dtype_counts = Counter(t.dtype for t in storage) + shape_counts = Counter(t.shape for t in storage) + param_shape_counts = Counter(p.shape for p in model.parameters()) + param_shape_counts_copy = dict(param_shape_counts).copy() + + # shape counts includes the params, so we need to subtract them; note that they can be transposed + # this is an approximation + diff_shape_counts = {} + for shape, count in shape_counts.items(): + if shape in param_shape_counts_copy: + diff_count = count - param_shape_counts[shape] + if diff_count > 0: + diff_shape_counts[shape] = diff_count + param_shape_counts_copy[shape] = max(0, param_shape_counts_copy[shape] - diff_count) + elif shape[::-1] in param_shape_counts: + diff_count = count - param_shape_counts[shape[::-1]] + if diff_count > 0: + diff_shape_counts[shape] = diff_count + param_shape_counts_copy[shape[::-1]] = max(0, param_shape_counts_copy[shape[::-1]] - diff_count) + else: + diff_shape_counts[shape] = count + + total_size = sum(t.numel() * t.element_size() for t in storage) + total_size_mb = f"{total_size // 2**20}MB" + diff_size = 0 + for shape, count in diff_shape_counts.items(): + diff_size += count * torch.zeros(shape).numel() * dtype_to_bytes_linear[dtype] + param_size = total_size - diff_size + + diff_size_mb = f"{diff_size // 2**20}MB" + param_size_mb = f"{param_size // 2**20}MB" + + print(f"Dtype counts: {dtype_counts.most_common()}") + print(f"Total size of tensors: {total_size_mb: >12}") + print(f"Total size of activations: {diff_size_mb: >12}") + print(f"Total size of parameters: {param_size_mb: >12}") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("model_id", type=str, help="Model name on Hugging Face Hub") + parser.add_argument("--rank", type=int, default=8, help="Rank of LoRA, 0 => no LoRA, default 8") + parser.add_argument( + "--dtype", + type=str, + default="float32", + help="Data type, one of float32, float16, bfloat16, int8, int4, default float32", + ) + parser.add_argument( + "--monitor_tensors", + action="store_true", + help="Monitor tensor sizes during training for a single training step, off by default", + ) + parser.add_argument("--max_seq_length", type=int, default=128, help="Maximum sequence length, default 128") + parser.add_argument("--batch_size", type=int, default=1, help="Batch size, default 1") + parser.add_argument("--max_steps", type=int, default=50, help="Maximum number of training steps, default 50") + parser.add_argument("--path_config", type=str, default=None, help="Path to LoRA config") + args = parser.parse_args() + train( + model_id=args.model_id, + rank=args.rank, + dtype=args.dtype, + monitor_tensors=args.monitor_tensors, + max_seq_length=args.max_seq_length, + batch_size=args.batch_size, + max_steps=args.max_steps, + path_config=args.path_config, + ) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/setup.py b/tasks/tasksmith-749ff8d440e1/environment/source/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..a20c5a43c6f21d3111f42cd794b0c8259e5ec7fa --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/setup.py @@ -0,0 +1,117 @@ +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# 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 setuptools import find_packages, setup + + +VERSION = "0.19.2.dev0" + +extras = {} +extras["quality"] = [ + "black", # doc-builder has an implicit dependency on Black, see huggingface/doc-builder#434 + "hf-doc-builder", + # when upgrading this, also upgrade required version in pyproject.toml and pre-commit-config.yaml + "ruff~=0.15.12", +] +extras["docs_specific"] = [ + "black", # doc-builder has an implicit dependency on Black, see huggingface/doc-builder#434 + "requests", # doc-builder has an implicit dependency on requests (setup.py doesn't mention it, pyproject does) + "hf-doc-builder", +] +extras["dev"] = extras["quality"] + extras["docs_specific"] +extras["test"] = extras["dev"] + [ + "pytest", + "pytest-cov", + "pytest-xdist", + "parameterized", + "datasets", + "diffusers", + "scipy", + "scikit-learn", + "protobuf", + "sentencepiece", + "torchvision", +] + +with open("README.md", encoding="utf-8") as f: + long_description = f.read() + +setup( + name="peft", + version=VERSION, + description="Parameter-Efficient Fine-Tuning (PEFT)", + license_files=["LICENSE"], + long_description=long_description, + long_description_content_type="text/markdown", + keywords="deep learning", + license="Apache", + author="The HuggingFace team", + author_email="benjamin@huggingface.co", + url="https://github.com/huggingface/peft", + package_dir={"": "src"}, + packages=find_packages("src"), + package_data={"peft": ["py.typed", "tuners/boft/fbd/fbd_cuda.cpp", "tuners/boft/fbd/fbd_cuda_kernel.cu"]}, + entry_points={}, + python_requires=">=3.10.0", + install_requires=[ + "numpy>=1.17", + "packaging>=20.0", + "psutil", + "pyyaml", + "torch>=1.13.0", + "transformers", + "tqdm", + "accelerate>=0.21.0", + "safetensors", + "huggingface_hub>=0.25.0", + ], + extras_require=extras, + classifiers=[ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "Intended Audience :: Education", + "Intended Audience :: Science/Research", + "License :: OSI Approved :: Apache Software License", + "Operating System :: OS Independent", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Topic :: Scientific/Engineering :: Artificial Intelligence", + ], +) + +# Release checklist +# 1. Change the version in __init__.py and setup.py to the release version, e.g. from "0.6.1.dev0" to "0.7.0" +# 2. Check if there are any deprecations that need to be addressed for this release by searching for "# TODO" in the code +# 3. Commit these changes with the message: "Release: VERSION", create a PR and merge it. +# 4. Add a tag in git to mark the release: "git tag -a v -m 'Adds tag for pypi' " +# Push the tag to git: +# git push --tags origin main +# It is necessary to work on the original repository, not on a fork. +# 5. Run the following commands in the top-level directory: +# python setup.py bdist_wheel +# python setup.py sdist +# Ensure that you are on the clean and up-to-date main branch (git status --untracked-files=no should not list any +# files and show the main branch) +# 6. Upload the package to the pypi test server first: +# twine upload dist/* -r pypitest +# 7. Check that you can install it in a virtualenv by running: +# pip install -i https://testpypi.python.org/pypi --extra-index-url https://pypi.org/simple peft +# 8. Upload the final version to actual pypi: +# twine upload dist/* -r pypi +# 9. Add release notes to the tag on https://github.com/huggingface/peft/releases once everything is looking hunky-dory. +# Check the notes here: https://docs.google.com/document/d/1k-sOIfykuKjWcOIALqjhFKz4amFEp-myeJUJEzNgjoU/edit?usp=sharing +# 10. Update the version in __init__.py, setup.py to the bumped patch version + ".dev0" (e.g. from "0.7.0" to "0.7.1.dev0") diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ec12d525831cd42b566208d3ba3a515b85625272 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/__init__.py @@ -0,0 +1,306 @@ +# 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. + +__version__ = "0.19.2.dev0" + +from .auto import ( + MODEL_TYPE_TO_PEFT_MODEL_MAPPING, + AutoPeftModel, + AutoPeftModelForCausalLM, + AutoPeftModelForFeatureExtraction, + AutoPeftModelForQuestionAnswering, + AutoPeftModelForSeq2SeqLM, + AutoPeftModelForSequenceClassification, + AutoPeftModelForTokenClassification, +) +from .config import PeftConfig, PromptLearningConfig +from .helpers import find_kappa_target_modules +from .mapping import ( + PEFT_TYPE_TO_CONFIG_MAPPING, + PEFT_TYPE_TO_MIXED_MODEL_MAPPING, + PEFT_TYPE_TO_TUNER_MAPPING, + get_peft_config, + inject_adapter_in_model, +) +from .mapping_func import get_peft_model +from .mixed_model import PeftMixedModel +from .peft_model import ( + PeftModel, + PeftModelForCausalLM, + PeftModelForFeatureExtraction, + PeftModelForQuestionAnswering, + PeftModelForSeq2SeqLM, + PeftModelForSequenceClassification, + PeftModelForTokenClassification, + get_layer_status, + get_model_status, +) +from .tuners import ( + AdaLoraConfig, + AdaLoraModel, + AdamssConfig, + AdamssModel, + AdaptionPromptConfig, + AdaptionPromptModel, + ArrowConfig, + BdLoraConfig, + BeftConfig, + BeftModel, + BOFTConfig, + BOFTModel, + C3AConfig, + C3AModel, + CartridgeConfig, + CartridgeEncoder, + CPTConfig, + CPTEmbedding, + DeloraConfig, + DeloraModel, + EvaConfig, + FourierFTConfig, + FourierFTModel, + GraloraConfig, + GraloraModel, + HiraConfig, + HiraModel, + HRAConfig, + HRAModel, + IA3Config, + IA3Model, + LilyConfig, + LilyModel, + LNTuningConfig, + LNTuningModel, + LoftQConfig, + LoHaConfig, + LoHaModel, + LoKrConfig, + LoKrModel, + LoraConfig, + LoraGAConfig, + LoraModel, + LoraRuntimeConfig, + MissConfig, + MissModel, + MontecloraConfig, + MultitaskPromptTuningConfig, + MultitaskPromptTuningInit, + OFTConfig, + OFTModel, + OSFConfig, + OSFModel, + PeanutConfig, + PeanutModel, + PolyConfig, + PolyModel, + PrefixEncoder, + PrefixTuningConfig, + PromptEmbedding, + PromptEncoder, + PromptEncoderConfig, + PromptEncoderReparameterizationType, + PromptTuningConfig, + PromptTuningInit, + PsoftConfig, + PsoftModel, + PveraConfig, + PveraModel, + RandLoraConfig, + RandLoraModel, + RoadConfig, + RoadModel, + ShiraConfig, + ShiraModel, + TinyLoraConfig, + TinyLoraModel, + TrainableTokensConfig, + TrainableTokensModel, + VBLoRAConfig, + VBLoRAModel, + VeloraConfig, + VeraConfig, + VeraModel, + WaveFTConfig, + WaveFTModel, + XLoraConfig, + XLoraModel, + convert_to_lora, + create_arrow_model, + get_eva_state_dict, + initialize_lora_eva_weights, + preprocess_loraga, + save_as_lora, +) +from .tuners.cartridge.utils import ( + compose_cartridge_adapters, + initialize_kv_prefix_from_past_key_values, + initialize_kv_prefix_from_text, + prompt_embeddings_from_past_key_values, +) +from .utils import ( + TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING, + PeftType, + PeftWarning, + TaskType, + bloom_model_postprocess_past_key_value, + cast_mixed_precision_params, + get_peft_model_state_dict, + load_peft_weights, + prepare_model_for_kbit_training, + replace_lora_weights_loftq, + set_peft_model_state_dict, + shift_tokens_right, +) + + +__all__ = [ + "MODEL_TYPE_TO_PEFT_MODEL_MAPPING", + "PEFT_TYPE_TO_CONFIG_MAPPING", + "PEFT_TYPE_TO_MIXED_MODEL_MAPPING", + "PEFT_TYPE_TO_TUNER_MAPPING", + "TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING", + "AdaLoraConfig", + "AdaLoraModel", + "AdamssConfig", + "AdamssModel", + "AdaptionPromptConfig", + "AdaptionPromptModel", + "ArrowConfig", + "AutoPeftModel", + "AutoPeftModelForCausalLM", + "AutoPeftModelForFeatureExtraction", + "AutoPeftModelForQuestionAnswering", + "AutoPeftModelForSeq2SeqLM", + "AutoPeftModelForSequenceClassification", + "AutoPeftModelForTokenClassification", + "BOFTConfig", + "BOFTModel", + "BdLoraConfig", + "BeftConfig", + "BeftModel", + "C3AConfig", + "C3AModel", + "CPTConfig", + "CPTEmbedding", + "CartridgeConfig", + "CartridgeEncoder", + "DeloraConfig", + "DeloraModel", + "EvaConfig", + "FourierFTConfig", + "FourierFTModel", + "GraloraConfig", + "GraloraModel", + "HRAConfig", + "HRAModel", + "HiraConfig", + "HiraModel", + "IA3Config", + "IA3Model", + "LNTuningConfig", + "LNTuningModel", + "LilyConfig", + "LilyModel", + "LoHaConfig", + "LoHaModel", + "LoKrConfig", + "LoKrModel", + "LoftQConfig", + "LoraConfig", + "LoraGAConfig", + "LoraModel", + "LoraRuntimeConfig", + "MissConfig", + "MissModel", + "MontecloraConfig", + "MultitaskPromptTuningConfig", + "MultitaskPromptTuningInit", + "OFTConfig", + "OFTModel", + "OSFConfig", + "OSFModel", + "PeanutConfig", + "PeanutModel", + "PeftConfig", + "PeftMixedModel", + "PeftModel", + "PeftModelForCausalLM", + "PeftModelForFeatureExtraction", + "PeftModelForQuestionAnswering", + "PeftModelForSeq2SeqLM", + "PeftModelForSequenceClassification", + "PeftModelForTokenClassification", + "PeftType", + "PeftWarning", + "PolyConfig", + "PolyModel", + "PrefixEncoder", + "PrefixTuningConfig", + "PromptEmbedding", + "PromptEncoder", + "PromptEncoderConfig", + "PromptEncoderReparameterizationType", + "PromptLearningConfig", + "PromptTuningConfig", + "PromptTuningInit", + "PsoftConfig", + "PsoftModel", + "PveraConfig", + "PveraModel", + "RandLoraConfig", + "RandLoraModel", + "RoadConfig", + "RoadModel", + "ShiraConfig", + "ShiraModel", + "TaskType", + "TinyLoraConfig", + "TinyLoraModel", + "TrainableTokensConfig", + "TrainableTokensModel", + "VBLoRAConfig", + "VBLoRAConfig", + "VBLoRAModel", + "VeloraConfig", + "VeraConfig", + "VeraModel", + "WaveFTConfig", + "WaveFTModel", + "XLoraConfig", + "XLoraModel", + "bloom_model_postprocess_past_key_value", + "cast_mixed_precision_params", + "compose_cartridge_adapters", + "convert_to_lora", + "create_arrow_model", + "find_kappa_target_modules", + "get_eva_state_dict", + "get_layer_status", + "get_model_status", + "get_peft_config", + "get_peft_model", + "get_peft_model_state_dict", + "initialize_kv_prefix_from_past_key_values", + "initialize_kv_prefix_from_text", + "initialize_lora_eva_weights", + "inject_adapter_in_model", + "load_peft_weights", + "prepare_model_for_kbit_training", + "preprocess_loraga", + "prompt_embeddings_from_past_key_values", + "replace_lora_weights_loftq", + "save_as_lora", + "set_peft_model_state_dict", + "shift_tokens_right", +] diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/auto.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/auto.py new file mode 100644 index 0000000000000000000000000000000000000000..2cbe903be637167caa52f76287bd3c7e4074025c --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/auto.py @@ -0,0 +1,225 @@ +# 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 importlib +import os +from typing import Optional + +from transformers import ( + AutoModel, + AutoModelForCausalLM, + AutoModelForQuestionAnswering, + AutoModelForSeq2SeqLM, + AutoModelForSequenceClassification, + AutoModelForTokenClassification, + AutoTokenizer, +) + +from .config import PeftConfig +from .peft_model import ( + PeftModel, + PeftModelForCausalLM, + PeftModelForFeatureExtraction, + PeftModelForQuestionAnswering, + PeftModelForSeq2SeqLM, + PeftModelForSequenceClassification, + PeftModelForTokenClassification, +) +from .utils.constants import TOKENIZER_CONFIG_NAME +from .utils.other import check_file_exists_on_hf_hub + + +MODEL_TYPE_TO_PEFT_MODEL_MAPPING: dict[str, type[PeftModel]] = { + "SEQ_CLS": PeftModelForSequenceClassification, + "SEQ_2_SEQ_LM": PeftModelForSeq2SeqLM, + "CAUSAL_LM": PeftModelForCausalLM, + "TOKEN_CLS": PeftModelForTokenClassification, + "QUESTION_ANS": PeftModelForQuestionAnswering, + "FEATURE_EXTRACTION": PeftModelForFeatureExtraction, +} + + +def get_default_import_allowlist(): + return [ + "diffusers", + "lerobot", + "megatron-core", + "transformers", + ] + + +def check_import_allowlist(allowlist, parent_name): + """Ensure that the parent_name is in the allowlist or, at least, the prefix (e.g., "transformers."). + This is done because PEFT uses importlib.import_module on adapter config values. To prevent PEFT being used as a + means to execute code by importing a potentially malicious package (i.e. as a means to execute planted code), we + limit the possible packages to a known value. + """ + if parent_name in allowlist: + return True + + return any(parent_name.startswith(f"{allowed}.") for allowed in allowlist) + + +class _BaseAutoPeftModel: + _target_class = None + _target_peft_class = None + + def __init__(self, *args, **kwargs): + # For consistency with transformers: https://github.com/huggingface/transformers/blob/91d7df58b6537d385e90578dac40204cb550f706/src/transformers/models/auto/auto_factory.py#L400 + raise EnvironmentError( # noqa: UP024 + f"{self.__class__.__name__} is designed to be instantiated " + f"using the `{self.__class__.__name__}.from_pretrained(pretrained_model_name_or_path)` or " + f"`{self.__class__.__name__}.from_config(config)` methods." + ) + + @classmethod + def from_pretrained( + cls, + pretrained_model_name_or_path, + adapter_name: str = "default", + is_trainable: bool = False, + config: Optional[PeftConfig] = None, + revision: Optional[str] = None, + import_allowlist: Optional[list[str]] = None, + **kwargs, + ): + r""" + A wrapper around all the preprocessing steps a user needs to perform in order to load a PEFT model. The kwargs + are passed along to `PeftConfig` that automatically takes care of filtering the kwargs of the Hub methods and + the config object init. + + The parameters are equivalent to the ones of [`PeftModel.from_pretrained`]. Differences are documented below. + + Args: + import_allowlist (`list[str]`, *optional*, defaults to `{get_default_import_allowlist()}`) + AutoPeftModel will attempt to instantiate the base model that is configured in the adapter config. + Since this operation needs to potentially import other packages, this allowlist is a safe-guard to + prevent importing malicious packages. You may need to specify your package's import name here if it is + not in the defaults. + """ + peft_config = PeftConfig.from_pretrained(pretrained_model_name_or_path, revision=revision, **kwargs) + base_model_path = peft_config.base_model_name_or_path + base_model_revision = peft_config.revision + + if import_allowlist is None: + import_allowlist = get_default_import_allowlist() + + task_type = getattr(peft_config, "task_type", None) + + if cls._target_class is not None: + target_class = cls._target_class + elif cls._target_class is None and task_type is not None: + # this is only in the case where we use `AutoPeftModel` + raise ValueError( + "Cannot use `AutoPeftModel` with a task type, please use a specific class for your task type. (e.g. `AutoPeftModelForCausalLM` for `task_type='CAUSAL_LM'`)" + ) + + if task_type is not None: + expected_target_class = MODEL_TYPE_TO_PEFT_MODEL_MAPPING[task_type] + if cls._target_peft_class.__name__ != expected_target_class.__name__: + raise ValueError( + f"Expected target PEFT class: {expected_target_class.__name__}, but you have asked for: {cls._target_peft_class.__name__}" + " make sure that you are loading the correct model for your task type." + ) + elif task_type is None and getattr(peft_config, "auto_mapping", None) is not None: + auto_mapping = getattr(peft_config, "auto_mapping", None) + base_model_class = auto_mapping["base_model_class"] + parent_library_name = auto_mapping["parent_library"] + + if not check_import_allowlist(import_allowlist, parent_library_name): + raise ValueError( + f"The auto mapping wants to import '{parent_library_name}' which is not in the import allowlist. " + "If you are sure that importing this library is safe, specify " + f"`import_allowlist=['{parent_library_name}']` in `from_pretrained()`." + ) + + parent_library = importlib.import_module(parent_library_name) + target_class = getattr(parent_library, base_model_class) + else: + raise ValueError( + "Cannot infer the auto class from the config, please make sure that you are loading the correct model for your task type." + ) + + base_model = target_class.from_pretrained(base_model_path, revision=base_model_revision, **kwargs) + + tokenizer_exists = False + if os.path.exists(os.path.join(pretrained_model_name_or_path, TOKENIZER_CONFIG_NAME)): + tokenizer_exists = True + else: + token = kwargs.get("token", None) + if token is None: + token = kwargs.get("use_auth_token", None) + + tokenizer_exists = check_file_exists_on_hf_hub( + repo_id=pretrained_model_name_or_path, + filename=TOKENIZER_CONFIG_NAME, + revision=revision, + repo_type=kwargs.get("repo_type", None), + token=token, + ) + + if tokenizer_exists and hasattr(base_model, "get_input_embeddings"): + tokenizer = AutoTokenizer.from_pretrained( + pretrained_model_name_or_path, trust_remote_code=kwargs.get("trust_remote_code", False) + ) + embedding_size = base_model.get_input_embeddings().weight.shape[0] + if len(tokenizer) > embedding_size: + # only resize if the tokenizer has a larger vocab size than there are embeddings + base_model.resize_token_embeddings(len(tokenizer)) + + return cls._target_peft_class.from_pretrained( + base_model, + pretrained_model_name_or_path, + adapter_name=adapter_name, + is_trainable=is_trainable, + config=config, + **kwargs, + ) + + +class AutoPeftModel(_BaseAutoPeftModel): + _target_class = None + _target_peft_class = PeftModel + + +class AutoPeftModelForCausalLM(_BaseAutoPeftModel): + _target_class = AutoModelForCausalLM + _target_peft_class = PeftModelForCausalLM + + +class AutoPeftModelForSeq2SeqLM(_BaseAutoPeftModel): + _target_class = AutoModelForSeq2SeqLM + _target_peft_class = PeftModelForSeq2SeqLM + + +class AutoPeftModelForSequenceClassification(_BaseAutoPeftModel): + _target_class = AutoModelForSequenceClassification + _target_peft_class = PeftModelForSequenceClassification + + +class AutoPeftModelForTokenClassification(_BaseAutoPeftModel): + _target_class = AutoModelForTokenClassification + _target_peft_class = PeftModelForTokenClassification + + +class AutoPeftModelForQuestionAnswering(_BaseAutoPeftModel): + _target_class = AutoModelForQuestionAnswering + _target_peft_class = PeftModelForQuestionAnswering + + +class AutoPeftModelForFeatureExtraction(_BaseAutoPeftModel): + _target_class = AutoModel + _target_peft_class = PeftModelForFeatureExtraction diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/config.py new file mode 100644 index 0000000000000000000000000000000000000000..df28d9f376f9650dc69a0c7ae97e156b0f136450 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/config.py @@ -0,0 +1,408 @@ +# 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 importlib.metadata +import inspect +import json +import os +import warnings +from dataclasses import asdict, dataclass, field +from typing import Optional, Union + +import packaging.version +from huggingface_hub import hf_hub_download +from transformers.utils import PushToHubMixin, http_user_agent + +from peft import __version__ + +from .utils import CONFIG_NAME, PeftType, TaskType + + +# we expect at least these keys to be present in a PEFT adapter_config.json +MIN_EXPECTED_CONFIG_KEYS = {"peft_type"} + + +def _check_and_remove_unused_kwargs(cls, kwargs): + """Make PEFT configs forward-compatible by removing unused kwargs that were added in later PEFT versions. + + This assumes that removing the unused kwargs will not affect the default behavior. + + Returns the filtered kwargs and the set of removed keys. + """ + # it's not pretty but eh + signature_parameters = inspect.signature(cls.__init__).parameters + unexpected_kwargs = set(kwargs.keys()) - set(signature_parameters.keys()) + for key in unexpected_kwargs: + del kwargs[key] + return kwargs, unexpected_kwargs + + +def _is_dev_version(version: str) -> bool: + # check if the given version is a dev version + return packaging.version.Version(version).dev is not None + + +def _get_commit_hash(pkg_name: str) -> str | None: + # If PEFT was installed from a specific commit hash, try to get it. This works e.g. when installing PEFT with `pip + # install git+https://github.com/huggingface/peft.git@`. This works not for other means, like editable + # installs. + try: + dist = importlib.metadata.distribution(pkg_name) + except importlib.metadata.PackageNotFoundError: + return None + + # See: https://packaging.python.org/en/latest/specifications/direct-url/ + for path in dist.files or []: + if path.name == "direct_url.json": + direct_url = json.loads((dist.locate_file(path)).read_text()) + vcs_info = direct_url.get("vcs_info") + if vcs_info and "commit_id" in vcs_info: + return vcs_info["commit_id"] + return None + + +@dataclass +class PeftConfigMixin(PushToHubMixin): + r""" + This is the base configuration class for PEFT adapter models. It contains all the methods that are common to all + PEFT adapter models. This class inherits from [`~transformers.utils.PushToHubMixin`] which contains the methods to + push your model to the Hub. The method `save_pretrained` will save the configuration of your adapter model in a + directory. The method `from_pretrained` will load the configuration of your adapter model from a directory. + + Args: + peft_type (Union[[`~peft.utils.config.PeftType`], `str`]): The type of Peft method to use. + """ + + task_type: Optional[TaskType] = field(default=None, metadata={"help": "The type of task."}) + peft_type: Optional[PeftType] = field(default=None, metadata={"help": "The type of PEFT model."}) + auto_mapping: Optional[dict] = field( + default=None, metadata={"help": "An auto mapping dict to help retrieve the base model class if needed."} + ) + peft_version: Optional[str] = field(default=None, metadata={"help": "PEFT version, leave empty to auto-fill."}) + + def __post_init__(self): + # check for invalid task type + if (self.task_type is not None) and (self.task_type not in list(TaskType)): + raise ValueError( + f"Invalid task type: '{self.task_type}'. Must be one of the following task types: {', '.join(TaskType)}." + ) + if self.peft_version is None: + self.peft_version = self._get_peft_version() + + @staticmethod + def _get_peft_version() -> str: + # gets the current peft version; if it's a dev version, try to get the commit hash too, as the dev version is + # ambiguous + version = __version__ + if not _is_dev_version(version): + return version + + try: + git_hash = _get_commit_hash("peft") + if git_hash is None: + git_hash = "UNKNOWN" + except Exception: + # Broad exception: We never want to break user code just because the git_hash could not be determined + warnings.warn( + "A dev version of PEFT is used but there was an error while trying to determine the commit hash. " + "Please open an issue: https://github.com/huggingface/peft/issues" + ) + git_hash = "UNKNOWN" + version = version + f"@{git_hash}" + return version + + def to_dict(self) -> dict: + r""" + Returns the configuration for your adapter model as a dictionary. + """ + return asdict(self) + + def save_pretrained(self, save_directory: str, **kwargs) -> None: + r""" + This method saves the configuration of your adapter model in a directory. + + Args: + save_directory (`str`): + The directory where the configuration will be saved. + kwargs (additional keyword arguments, *optional*): + Additional keyword arguments passed along to the [`~transformers.utils.PushToHubMixin.push_to_hub`] + method. + """ + if os.path.isfile(save_directory): + raise AssertionError(f"Provided path ({save_directory}) should be a directory, not a file") + + os.makedirs(save_directory, exist_ok=True) + auto_mapping_dict = kwargs.pop("auto_mapping_dict", None) + + output_dict = self.to_dict() + # converting set type to list + for key, value in output_dict.items(): + if isinstance(value, set): + output_dict[key] = list(value) + + output_path = os.path.join(save_directory, CONFIG_NAME) + + # Add auto mapping details for custom models. + if auto_mapping_dict is not None: + output_dict["auto_mapping"] = auto_mapping_dict + + # save it + with open(output_path, "w") as writer: + writer.write(json.dumps(output_dict, indent=2, sort_keys=True)) + + @classmethod + def from_peft_type(cls, **kwargs): + r""" + This method loads the configuration of your adapter model from a set of kwargs. + + The appropriate configuration type is determined by the `peft_type` argument. If `peft_type` is not provided, + the calling class type is instantiated. + + Args: + kwargs (configuration keyword arguments): + Keyword arguments passed along to the configuration initialization. + """ + # Avoid circular dependency .. TODO: fix this with a larger refactor + from peft.mapping import PEFT_TYPE_TO_CONFIG_MAPPING + + # TODO: this hack is needed to fix the following issue (on commit 702f937): + # if someone saves a default config and loads it back with `PeftConfig` class it yields to + # not loading the correct config class. + # + # from peft import AdaLoraConfig, PeftConfig + # peft_config = AdaLoraConfig() + # print(peft_config) + # >>> AdaLoraConfig(peft_type=, auto_mapping=None, base_model_name_or_path=None, + # revision=None, task_type=None, inference_mode=False, r=8, target_modules=None, lora_alpha=8, lora_dropout=0.0, ... + # + # peft_config.save_pretrained("./test_config") + # peft_config = PeftConfig.from_pretrained("./test_config") + # print(peft_config) + # >>> PeftConfig(peft_type='ADALORA', auto_mapping=None, base_model_name_or_path=None, revision=None, task_type=None, inference_mode=False) + + if "peft_type" in kwargs: + peft_type = kwargs["peft_type"] + config_cls = PEFT_TYPE_TO_CONFIG_MAPPING[peft_type] + else: + config_cls = cls + + try: + config = config_cls(**kwargs) + except TypeError as exc: + # Here we potentially handle forward compatibility. Sometimes new keywords are added to configs, which makes + # new configs incompatible with older PEFT versions. We catch these and remove them to allow the program to + # continue, but warn the user about it. + + # First check if the error is due to unexpected keyword arguments, we don't want to accidentally catch + # other TypeErrors. + if "got an unexpected keyword argument" not in str(exc): + raise + + filtered_kwargs, unexpected_kwargs = _check_and_remove_unused_kwargs(config_cls, kwargs) + if not MIN_EXPECTED_CONFIG_KEYS.issubset(set(filtered_kwargs.keys())): + raise TypeError( + f"The {cls.__name__} config that is trying to be loaded is missing required keys: " + f"{MIN_EXPECTED_CONFIG_KEYS}." + ) + + warnings.warn( + f"Unexpected keyword arguments {sorted(unexpected_kwargs)} for class {config_cls.__name__}, these are " + "ignored. This probably means that you're loading a configuration file that was saved using a " + "higher version of the library and additional parameters have been introduced since. It is " + "highly recommended to upgrade the PEFT version before continuing (e.g. by running `pip install " + "-U peft`)." + ) + config = config_cls.from_peft_type(**filtered_kwargs) + return config + + @classmethod + def from_pretrained(cls, pretrained_model_name_or_path: str, subfolder: Optional[str] = None, **kwargs): + r""" + This method loads the configuration of your adapter model from a directory. + + Args: + pretrained_model_name_or_path (`str`): + The directory or the Hub repository id where the configuration is saved. + kwargs (additional keyword arguments, *optional*): + Additional keyword arguments passed along to the child class initialization. + """ + path = ( + os.path.join(pretrained_model_name_or_path, subfolder) + if subfolder is not None + else pretrained_model_name_or_path + ) + + hf_hub_download_kwargs, class_kwargs, _ = cls._split_kwargs(kwargs) + if "user_agent" not in hf_hub_download_kwargs: + hf_hub_download_kwargs["user_agent"] = http_user_agent() + + if os.path.isfile(os.path.join(path, CONFIG_NAME)): + config_file = os.path.join(path, CONFIG_NAME) + else: + try: + config_file = hf_hub_download( + pretrained_model_name_or_path, CONFIG_NAME, subfolder=subfolder, **hf_hub_download_kwargs + ) + except Exception as exc: + raise ValueError(f"Can't find '{CONFIG_NAME}' at '{pretrained_model_name_or_path}'") from exc + + loaded_attributes = cls.from_json_file(config_file) + kwargs = {**class_kwargs, **loaded_attributes} + kwargs = cls.check_kwargs(**kwargs) + return cls.from_peft_type(**kwargs) + + @classmethod + def from_json_file(cls, path_json_file: str, **kwargs): + r""" + Loads a configuration file from a json file. + + Args: + path_json_file (`str`): + The path to the json file. + """ + with open(path_json_file) as file: + json_object = json.load(file) + + # Sanity check that config does not contain a runtime_config + if "runtime_config" in json_object: + warnings.warn( + "The configuration file contains a `runtime_config` key. This is ignored. Runtime configurations are only valid at runtime." + ) + del json_object["runtime_config"] + + return json_object + + @classmethod + def _split_kwargs(cls, kwargs): + hf_hub_download_kwargs = {} + class_kwargs = {} + other_kwargs = {} + + for key, value in kwargs.items(): + if key in inspect.signature(hf_hub_download).parameters: + hf_hub_download_kwargs[key] = value + elif key in list(cls.__annotations__): + class_kwargs[key] = value + else: + other_kwargs[key] = value + + return hf_hub_download_kwargs, class_kwargs, other_kwargs + + @classmethod + def _get_peft_type( + cls, + model_id: str, + **hf_hub_download_kwargs, + ): + subfolder = hf_hub_download_kwargs.get("subfolder", None) + + path = os.path.join(model_id, subfolder) if subfolder is not None else model_id + + if os.path.isfile(os.path.join(path, CONFIG_NAME)): + config_file = os.path.join(path, CONFIG_NAME) + else: + try: + config_file = hf_hub_download( + model_id, + CONFIG_NAME, + **hf_hub_download_kwargs, + ) + except Exception: + raise ValueError(f"Can't find '{CONFIG_NAME}' at '{model_id}'") + + loaded_attributes = cls.from_json_file(config_file) + return loaded_attributes["peft_type"] + + @classmethod + def check_kwargs(cls, **kwargs): + """Check kwargs before initializing the config instance. + + Subclasses can override this method to add specific checks. + + """ + return kwargs + + @property + def is_prompt_learning(self) -> bool: + r""" + Utility method to check if the configuration is for prompt learning. + """ + return False + + @property + def is_adaption_prompt(self) -> bool: + """Return True if this is an adaption prompt config.""" + return False + + +@dataclass +class PeftConfig(PeftConfigMixin): + """ + This is the base configuration class to store the configuration of a [`PeftModel`]. + + Args: + peft_type (Union[[`~peft.utils.config.PeftType`], `str`]): The type of Peft method to use. + task_type (Union[[`~peft.utils.config.TaskType`], `str`]): The type of task to perform. + inference_mode (`bool`, defaults to `False`): Whether to use the Peft model in inference mode. + """ + + base_model_name_or_path: Optional[str] = field( + default=None, metadata={"help": "The name of the base model to use."} + ) + revision: Optional[str] = field(default=None, metadata={"help": "The specific base model version to use."}) + peft_type: Optional[Union[str, PeftType]] = field(default=None, metadata={"help": "Peft type"}) + task_type: Optional[Union[str, TaskType]] = field(default=None, metadata={"help": "Task type"}) + inference_mode: bool = field(default=False, metadata={"help": "Whether to use inference mode"}) + + +@dataclass +class PromptLearningConfig(PeftConfig): + """ + This is the base configuration class to store the configuration of [`PrefixTuning`], [`PromptEncoder`], or + [`PromptTuning`]. + + Args: + num_virtual_tokens (`int`): The number of virtual tokens to use. + token_dim (`int`): The hidden embedding dimension of the base transformer model. + num_transformer_submodules (`int`): The number of transformer submodules in the base transformer model. + num_attention_heads (`int`): The number of attention heads in the base transformer model. + num_layers (`int`): The number of layers in the base transformer model. + """ + + num_virtual_tokens: int = field(default=None, metadata={"help": "Number of virtual tokens"}) + token_dim: int = field( + default=None, metadata={"help": "The hidden embedding dimension of the base transformer model"} + ) + num_transformer_submodules: Optional[int] = field( + default=None, metadata={"help": "Number of transformer submodules"} + ) + num_attention_heads: Optional[int] = field(default=None, metadata={"help": "Number of attention heads"}) + num_layers: Optional[int] = field(default=None, metadata={"help": "Number of transformer layers"}) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": "List of extra modules 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. " + "The module(s) will be fully fine-tuned." + }, + ) + + @property + def is_prompt_learning(self) -> bool: + r""" + Utility method to check if the configuration is for prompt learning. + """ + return True diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/functional.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/functional.py new file mode 100644 index 0000000000000000000000000000000000000000..60df690cafe1e9a3b5c8ff09d550f82110afe593 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/functional.py @@ -0,0 +1,34 @@ +# 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. +""" +Functions that are useful for integration with non-PeftModel models, e.g. transformers or diffusers. + +The functions provided here can be considered "public API" of PEFT and hence are safe to be used by packages that +provide PEFT integrations. +""" + +from peft.mapping import inject_adapter_in_model +from peft.tuners.tuners_utils import cast_adapter_dtype, delete_adapter, set_adapter, set_requires_grad +from peft.utils import get_peft_model_state_dict, set_peft_model_state_dict + + +__all__ = [ + "cast_adapter_dtype", + "delete_adapter", + "get_peft_model_state_dict", + "inject_adapter_in_model", + "set_adapter", + "set_peft_model_state_dict", + "set_requires_grad", +] diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/helpers.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..9c497ed16061c401d087d75841c1841a2fe02584 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/helpers.py @@ -0,0 +1,577 @@ +# 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 inspect +from contextlib import contextmanager +from copy import deepcopy +from functools import update_wrapper +from types import MethodType +from typing import Optional + +import torch +from torch import nn + + +try: + import bitsandbytes as bnb +except ImportError: + bnb = None + +from tqdm.auto import tqdm + +from .peft_model import PeftConfig, PeftModel +from .tuners.lora import LoraLayer, LoraModel, dora +from .tuners.tuners_utils import BaseTunerLayer + + +def update_forward_signature(model: PeftModel) -> None: + """ + Updates the forward signature of the PeftModel to include parents class signature + model (`PeftModel`): Peft model to update the forward signature + + Example: + + ```python + >>> from transformers import WhisperForConditionalGeneration + >>> from peft import get_peft_model, LoraConfig + >>> from peft.helpers import update_forward_signature + + >>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en") + >>> peft_config = LoraConfig(r=8, lora_alpha=32, lora_dropout=0.1, target_modules=["q_proj", "v_proj"]) + + >>> peft_model = get_peft_model(model, peft_config) + >>> update_forward_signature(peft_model) + ``` + """ + + # Only update signature when the current forward signature only has *args and **kwargs + current_signature = inspect.signature(model.forward) + if ( + len(current_signature.parameters) == 2 + and "args" in current_signature.parameters + and "kwargs" in current_signature.parameters + ): + forward = deepcopy(model.forward.__func__) + update_wrapper( + forward, type(model.get_base_model()).forward, assigned=("__doc__", "__name__", "__annotations__") + ) + model.forward = MethodType(forward, model) + + +def update_generate_signature(model: PeftModel) -> None: + """ + Updates the generate signature of a PeftModel with overriding generate to include parents class signature + model (`PeftModel`): Peft model to update the generate signature + + Example: + + ```python + >>> from transformers import AutoModelForSeq2SeqLM, AutoTokenizer + >>> from peft import get_peft_model, LoraConfig, TaskType + >>> from peft.helpers import update_generate_signature + + >>> model_name_or_path = "bigscience/mt0-large" + >>> tokenizer = AutoTokenizer.from_pretrained(model_name_or_path) + >>> model = AutoModelForSeq2SeqLM.from_pretrained(model_name_or_path) + + >>> peft_config = LoraConfig( + ... task_type=TaskType.SEQ_2_SEQ_LM, inference_mode=False, r=8, lora_alpha=32, lora_dropout=0.1 + ... ) + >>> peft_model = get_peft_model(model, peft_config) + >>> update_generate_signature(peft_model) + >>> help(peft_model.generate) + ``` + """ + if not hasattr(model, "generate"): + return + current_signature = inspect.signature(model.generate) + if ( + len(current_signature.parameters) == 2 + and "args" in current_signature.parameters + and "kwargs" in current_signature.parameters + ) or (len(current_signature.parameters) == 1 and "kwargs" in current_signature.parameters): + generate = deepcopy(model.generate.__func__) + update_wrapper( + generate, + type(model.get_base_model()).generate, + assigned=("__doc__", "__name__", "__annotations__"), + ) + model.generate = MethodType(generate, model) + + +def update_signature(model: PeftModel, method: str = "all") -> None: + """ + Updates the signature of a PeftModel include parents class signature for forward or generate method + model (`PeftModel`): Peft model to update generate or forward signature method (`str`): method to update + signature choose one of "forward", "generate", "all" + + Example: + ```python + >>> from transformers import AutoModelForSeq2SeqLM, AutoTokenizer + >>> from peft import get_peft_model, LoraConfig, TaskType + >>> from peft.helpers import update_signature + + >>> model_name_or_path = "bigscience/mt0-large" + >>> tokenizer = AutoTokenizer.from_pretrained(model_name_or_path) + >>> model = AutoModelForSeq2SeqLM.from_pretrained(model_name_or_path) + + >>> peft_config = LoraConfig( + ... task_type=TaskType.SEQ_2_SEQ_LM, inference_mode=False, r=8, lora_alpha=32, lora_dropout=0.1 + ... ) + >>> peft_model = get_peft_model(model, peft_config) + >>> update_signature(peft_model) + >>> help(peft_model.generate) + ``` + """ + if method == "forward": + update_forward_signature(model) + elif method == "generate": + update_generate_signature(model) + elif method == "all": + update_forward_signature(model) + update_generate_signature(model) + else: + raise ValueError(f"method {method} is not supported please choose one of ['forward', 'generate', 'all']") + + +def check_if_peft_model(model_name_or_path: str) -> bool: + """ + Check if the model is a PEFT model. + + Args: + model_name_or_path (`str`): + Model id to check, can be local or on the Hugging Face Hub. + + Returns: + `bool`: True if the model is a PEFT model, False otherwise. + """ + is_peft_model = True + try: + PeftConfig.from_pretrained(model_name_or_path) + except Exception: + # allow broad exceptions so that this works even if new exceptions are added on HF Hub side + is_peft_model = False + + return is_peft_model + + +@contextmanager +def rescale_adapter_scale(model, multiplier): + """ + Context manager to temporarily rescale the scaling of the LoRA adapter in a model. + + The original scaling values are restored when the context manager exits. This context manager works with the + transformers and diffusers models that have directly loaded LoRA adapters. + + For LoRA, applying this context manager with multiplier in [0, 1] is strictly equivalent to applying + [wise-ft](https://huggingface.co/papers/2109.01903) (see [#1940](https://github.com/huggingface/peft/issues/1940) + for details). It can improve the performances of the model if there is a distribution shiftbetween the training + data used for fine-tuning, and the test data used during inference. + + Warning: It has been reported that when using Apple's MPS backend for PyTorch, it is necessary to add a short sleep + time after exiting the context before the scales are fully restored. + + Args: + model: The model containing `LoraLayer` modules whose scaling is to be adjusted. + multiplier (float or int): + The multiplier that rescales the `scaling` attribute. Must be of type float or int. + + Raises: + ValueError: If the model does not contain any `LoraLayer` + instances, indicating that the model does not support scaling. + + Example: + + ```python + >>> model = ModelWithLoraLayer() + >>> multiplier = 0.5 + >>> with rescale_adapter_scale(model, multiplier): + ... outputs = model(**inputs) # Perform operations with the scaled model + >>> outputs = model(**inputs) # The original scaling values are restored here + ``` + """ + # check if multiplier has a valid data type + if not isinstance(multiplier, (float, int)): + raise TypeError(f"Argument multiplier should be of type float, got {type(multiplier)}") + + # iterate on the model's modules and grab the original scaling attribute + # from the lora layers if present + original_scaling = {} + for module in model.modules(): + if isinstance(module, LoraLayer): + original_scaling[module] = module.scaling.copy() + module.scaling = {k: v * multiplier for k, v in module.scaling.items()} + + # check whether scaling is prohibited on model + # the original scaling dictionary should be empty + # if there were no lora layers + if not original_scaling: + raise ValueError("scaling is only supported for models with `LoraLayer`s") + try: + yield + + finally: + # restore original scaling values after exiting the context + for module, scaling in original_scaling.items(): + module.scaling = scaling + + +@contextmanager +def disable_input_dtype_casting(model: nn.Module, active: bool = True): + """ + Context manager disables input dtype casting to the dtype of the weight. + + Parameters: + model (nn.Module): + The model containing PEFT modules whose input dtype casting is to be adjusted. + active (bool): + Whether the context manager is active (default) or inactive. + + """ + # Additional info: Normally, the dtype of the weight and input need to match, which is why the dtype is cast. + # However, in certain circumustances, this is handled by forward hooks, e.g. when using layerwise casting in + # diffusers. In that case, PEFT casting the dtype interferes with the layerwise casting, which is why the option to + # disable it is given. + if not active: + yield + return + + original_values = {} + for name, module in model.named_modules(): + if not isinstance(module, BaseTunerLayer): + continue + original_values[name] = module.cast_input_dtype_enabled + module.cast_input_dtype_enabled = False + + try: + yield + finally: + for name, module in model.named_modules(): + if not isinstance(module, BaseTunerLayer): + continue + if name in original_values: + module.cast_input_dtype_enabled = original_values[name] + + +class MontecloraTrainerMixin: + """ + Mixin class for adding Monteclora variational loss to the Trainer's compute_loss method. + + This mixin can be used with any Trainer class (e.g., Trainer, SFTTrainer) to add support for Monteclora's + variational regularization during training. + + Example: + ```python + from transformers import Trainer + from peft import get_peft_model, LoraConfig + from peft.helpers import MontecloraTrainerMixin + + + # custom trainer that supports Monteclora + class MontecloraTrainer(MontecloraTrainerMixin, Trainer): + pass + + + # Configure LoRA with Monteclora + monteclora_config = MontecloraConfig( + num_samples=8, + sample_scaler=1e-4, + kl_loss_weight=1e-5, + ) + lora_config = LoraConfig( + r=16, + lora_alpha=32, + target_modules=["q_proj", "v_proj"], + monteclora_config=monteclora_config, + ) + + # Get PEFT model and train + model = get_peft_model(base_model, lora_config) + trainer = MontecloraTrainer(model=model, args=training_args, ...) + trainer.train() + ``` + """ + + def compute_loss(self, model, inputs, return_outputs=False, **kwargs): + """ + Compute loss with Monteclora variational regularization. + + This method extends the standard compute_loss by adding the variational loss (KL divergence + entropy) from + Monteclora samplers to the task loss. + + Args: + model: The model being trained + inputs: Input batch + return_outputs: Whether to return model outputs along with loss + **kwargs: Additional arguments + + Returns: + loss or (loss, outputs) depending on return_outputs + """ + if return_outputs: + task_loss, outputs = super().compute_loss(model, inputs, return_outputs=True, **kwargs) + else: + task_loss = super().compute_loss(model, inputs, return_outputs=False, **kwargs) + outputs = None + + # `_get_monteclora_loss` already normalizes by the number of samplers within a single LoraModel. + # In the typical case there is exactly one LoraModel (PeftModel.base_model) so this loop runs once + # and matches the original behavior. For unusual setups with multiple tuners we additionally average + # across the LoraModels so the regularization magnitude does not scale with the number of tuners. + # `_get_monteclora_loss` returns 0.0 when no MonteCLoRA samplers are present, so this is a no-op + # for plain LoRA training. + monteclora_loss = 0.0 + num_lora_models = 0 + for module in model.modules(): + if isinstance(module, LoraModel): + monteclora_loss = monteclora_loss + module._get_monteclora_loss() + num_lora_models += 1 + if num_lora_models > 1: + monteclora_loss = monteclora_loss / num_lora_models + + total_loss = task_loss + monteclora_loss + + return (total_loss, outputs) if return_outputs else total_loss + + +class DoraCaching: + """Context manager to enable DoRA caching, which improves speed of DoRA inference at the expense of memory. + + With active caching, the materialized LoRA weight (B @ A) and the weight norm (base weight + LoRA weight) are + cached. + + Even within the caching context, if the model is in training mode, caching is disabled. When the model switches to + training mode, the cache will be cleared. + + Example: + + ```py + >>> from peft.helpers import DoraCaching + + >>> model.eval() # put in eval model for caching to work + + >>> with DoraCaching(): # use as a context manager + ... output = model(inputs) + + >>> dora_caching = DoraCaching() + >>> dora_caching(enabled=True) # permanently enable caching + >>> output = model(inputs) + >>> dora_caching(enabled=False) # permanently disable caching + >>> output = model(inputs) + ``` + + """ + + def __init__(self, enabled: bool = True) -> None: + self.enabled = enabled + self.prev_value = None + + def __enter__(self): + self.prev_value = dora.ENABLE_DORA_CACHING + dora.ENABLE_DORA_CACHING = self.enabled + + def __exit__(self, type, value, traceback): + dora.ENABLE_DORA_CACHING = self.prev_value + self.prev_value = None + + def __call__(self, enabled: bool = True): + dora.ENABLE_DORA_CACHING = enabled + + +class KappaTuneSelector: + """ + Lightweight utility to compute per-module / per-parameter condition numbers and return the best LoRA targets. + + Supports: + - Classic nn.Linear modules (target_modules in LoraConfig) + - Modern fused MoE weights stored as 3D nn.Parameter (gate_up_proj / down_proj, gate_proj / up_proj, etc.) used in + Llama-4, Qwen2_MoE, Qwen3_MoE, Mixtral, OLMoE and similar models. These are returned via target_parameters. + + Notes: + - Condition-number computation requires running SVD and can take several minutes on very large models. A progress + bar can be shown/disabled via `show_progress`. + + """ + + def __init__( + self, + model: nn.Module, + max_dim_size_to_analyze: int = 16384, + moe_param_suffixes: Optional[tuple[str, ...]] = None, + show_progress: bool = True, + ): + self.model = model + self.max_dim_size_to_analyze = max_dim_size_to_analyze + self.show_progress = show_progress + self.moe_param_suffixes = moe_param_suffixes or ( + ".gate_up_proj", + ".down_proj", + ".gate_proj", + ".up_proj", + ) + self._condition_numbers: Optional[dict[str, float]] = None + self._parameter_condition_numbers: Optional[dict[str, float]] = None + + def _compute_kappas(self) -> None: + if self._condition_numbers is not None: + return + + # === 1. nn.Linear modules === + condition_numbers: dict[str, float] = {} + linear_modules = [ + (module_name, module) + for module_name, module in self.model.named_modules() + if isinstance(module, nn.Linear) + ] + linear_iter = ( + tqdm(linear_modules, desc="Computing SVD (linear layers)", unit="layer") + if self.show_progress + else linear_modules + ) + for module_name, module in linear_iter: + weight = module.weight + if bnb is not None: + if hasattr(weight, "quant_state"): # 4-bit + w = bnb.functional.dequantize_4bit(weight.data, weight.quant_state).float() + elif hasattr(weight, "state") and hasattr(weight.state, "CB"): # int8 + w = bnb.functional.int8_vectorwise_dequant(weight.state.CB, weight.state.SCB).float() + else: + w = weight.data.detach().float() + else: + w = weight.data.detach().float() + + if any(dim > self.max_dim_size_to_analyze for dim in w.shape): + continue + + S = torch.linalg.svdvals(w.view(w.size(0), -1)) + kappa = (S[0] / (S[-1] + 1e-8)).item() + condition_numbers[module_name] = kappa + + self._condition_numbers = condition_numbers + + # === 2. fused MoE parameters (3D nn.Parameter) === + parameter_condition_numbers: dict[str, float] = {} + moe_params = [ + (param_name, param) + for param_name, param in self.model.named_parameters() + if any(param_name.endswith(s) for s in self.moe_param_suffixes) and param.dim() == 3 + ] + moe_iter = ( + tqdm(moe_params, desc="Computing SVD (MoE parameters)", unit="param") if self.show_progress else moe_params + ) + for param_name, param in moe_iter: + w = param.data.detach().float() + num_experts, *expert_shape = w.shape + + if any(dim > self.max_dim_size_to_analyze for dim in expert_shape): + continue + + kappas = [] + for expert_idx in range(num_experts): + expert_w = w[expert_idx] + S = torch.linalg.svdvals(expert_w) + kappa = (S[0] / (S[-1] + 1e-8)).item() + kappas.append(kappa) + kappa = sum(kappas) / len(kappas) + parameter_condition_numbers[param_name] = kappa + + self._parameter_condition_numbers = parameter_condition_numbers + + def get_best_targets( + self, top_p: Optional[float] = None, num_modules: Optional[int] = None, threshold: Optional[float] = None + ) -> list[str]: + self._compute_kappas() + if not self._condition_numbers: + return [] + + sorted_modules = sorted(self._condition_numbers.items(), key=lambda x: x[1]) + + if num_modules is not None: + k = min(num_modules, len(sorted_modules)) + return [name for name, _ in sorted_modules[:k]] + + if top_p is not None: + k = max(1, int(len(sorted_modules) * top_p)) + return [name for name, _ in sorted_modules[:k]] + + if threshold is not None: + return [name for name, kappa in sorted_modules if kappa <= threshold] + + return [name for name, _ in sorted_modules] + + def get_best_target_parameters( + self, top_p: Optional[float] = None, num_modules: Optional[int] = None, threshold: Optional[float] = None + ) -> list[str]: + self._compute_kappas() + if not self._parameter_condition_numbers: + return [] + + sorted_params = sorted(self._parameter_condition_numbers.items(), key=lambda x: x[1]) + + if num_modules is not None: + k = min(num_modules, len(sorted_params)) + return [name for name, _ in sorted_params[:k]] + + if top_p is not None: + k = max(1, int(len(sorted_params) * top_p)) + return [name for name, _ in sorted_params[:k]] + + if threshold is not None: + return [name for name, kappa in sorted_params if kappa <= threshold] + + return [name for name, _ in sorted_params] + + +def find_kappa_target_modules( + model: nn.Module, + top_p: float = 0.2, + max_dim_size_to_analyze: int = 16384, + moe_param_suffixes: Optional[tuple[str, ...]] = None, + show_progress: bool = True, +) -> dict[str, Optional[list[str]]]: + """ + One-liner convenience function for KappaTune target selection. Returns both target_modules and target_parameters. + + Args: + model (nn.Module): + Base model whose weights will be analyzed for condition numbers. + top_p (float, optional): + Select the top fraction of candidate modules/parameters with the lowest condition numbers. + max_dim_size_to_analyze (int, optional): + Upper bound on the maximum matrix dimension analyzed via SVD. Defaults to 16384. + moe_param_suffixes (Optional[tuple[str, ...]], optional): + Parameter-name suffixes used to identify fused MoE tensors that should be returned via `target_parameters`. + If None, sensible defaults are used. + show_progress (bool, optional): + Whether to display a progress bar while computing condition numbers (SVD-based) across candidate + tensors/modules. Disable in CI or other non-interactive environments. Defaults to True. + """ + selector = KappaTuneSelector( + model, + max_dim_size_to_analyze=max_dim_size_to_analyze, + moe_param_suffixes=moe_param_suffixes, + show_progress=show_progress, + ) + + target_modules = selector.get_best_targets(top_p=top_p) + target_parameters = selector.get_best_target_parameters(top_p=top_p) + + # Return None when there are no MoE layers (PEFT convention) + if not target_parameters: + target_parameters = None + + return { + "target_modules": target_modules, + "target_parameters": target_parameters, + } diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/import_utils.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/import_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ff187a17f0a2b9dccbff08aed3a1dbdd0fdf379d --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/import_utils.py @@ -0,0 +1,189 @@ +# 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 importlib +import importlib.metadata as importlib_metadata +import platform +from functools import lru_cache + +import packaging.version +import torch +import transformers + + +is_transformers_ge_v5 = packaging.version.parse(transformers.__version__) >= packaging.version.parse("5.0.0.dev0") + +is_transformers_ge_v5_1_0 = packaging.version.parse(transformers.__version__) >= packaging.version.parse("5.1.0") + +is_transformers_ge_v5_4_0 = packaging.version.parse(transformers.__version__) >= packaging.version.parse("5.4.0") + +is_transformers_ge_v5_6_0 = packaging.version.parse(transformers.__version__) >= packaging.version.parse("5.6.0.dev0") + +is_transformers_le_4_53 = packaging.version.parse(transformers.__version__) < packaging.version.parse("4.54.0.dev0") + + +@lru_cache +def is_bnb_available() -> bool: + return importlib.util.find_spec("bitsandbytes") is not None + + +@lru_cache +def is_bnb_4bit_available() -> bool: + if not is_bnb_available(): + return False + + import bitsandbytes as bnb + + return hasattr(bnb.nn, "Linear4bit") + + +@lru_cache +def is_gptqmodel_available() -> bool: + if importlib.util.find_spec("gptqmodel") is not None: + GPTQMODEL_MINIMUM_VERSION = packaging.version.parse("7.0.0") + OPTIMUM_MINIMUM_VERSION = packaging.version.parse("1.24.0") + version_gptqmodel = packaging.version.parse(importlib_metadata.version("gptqmodel")) + if GPTQMODEL_MINIMUM_VERSION <= version_gptqmodel: + if is_optimum_available(): + try: + version_optimum = packaging.version.parse(importlib_metadata.version("optimum")) + except importlib_metadata.PackageNotFoundError: + # Same idea as in diffusers: + # https://github.com/huggingface/diffusers/blob/9f06a0d1a4a998ac6a463c5be728c892f95320a8/src/diffusers/utils/import_utils.py#L351-L357 + # It's not clear under what circumstances `importlib_metadata.version("optimum")` can raise an error + # even though `importlib.util.find_spec("optimum") is not None` but it has been observed, so adding + # this for precaution. If we cannot detect it, we just optimistically assume it's high enough. + return True + + if OPTIMUM_MINIMUM_VERSION <= version_optimum: + return True + else: + raise ImportError( + f"gptqmodel requires optimum version `{OPTIMUM_MINIMUM_VERSION}` or higher. Found version `{version_optimum}`, " + f"but only versions above `{OPTIMUM_MINIMUM_VERSION}` are supported" + ) + else: + raise ImportError( + f"gptqmodel requires optimum version `{OPTIMUM_MINIMUM_VERSION}` or higher to be installed." + ) + else: + raise ImportError( + f"Found an incompatible version of gptqmodel. Found version `{version_gptqmodel}`, " + f"but only versions `{GPTQMODEL_MINIMUM_VERSION}` or higher are supported" + ) + + +@lru_cache +def is_optimum_available() -> bool: + return importlib.util.find_spec("optimum") is not None + + +@lru_cache +def is_torch_tpu_available(check_device=True) -> bool: + "Checks if `torch_xla` is installed and potentially if a TPU is in the environment" + if importlib.util.find_spec("torch_xla") is not None: + if check_device: + # We need to check if `xla_device` can be found, will raise a RuntimeError if not + try: + import torch_xla.core.xla_model as xm + + _ = xm.xla_device() + return True + except RuntimeError: + return False + return True + return False + + +@lru_cache +def is_aqlm_available() -> bool: + return importlib.util.find_spec("aqlm") is not None + + +@lru_cache +def is_eetq_available() -> bool: + return importlib.util.find_spec("eetq") is not None + + +@lru_cache +def is_hqq_available() -> bool: + return importlib.util.find_spec("hqq") is not None + + +@lru_cache +def is_inc_available() -> bool: + return importlib.util.find_spec("neural_compressor") is not None + + +@lru_cache +def is_torchao_available() -> bool: + if importlib.util.find_spec("torchao") is None: + return False + + TORCHAO_MINIMUM_VERSION = packaging.version.parse("0.16.0") + try: + torchao_version = packaging.version.parse(importlib_metadata.version("torchao")) + except importlib_metadata.PackageNotFoundError: + # Same idea as in diffusers: + # https://github.com/huggingface/diffusers/blob/9f06a0d1a4a998ac6a463c5be728c892f95320a8/src/diffusers/utils/import_utils.py#L351-L357 + # It's not clear under what circumstances `importlib_metadata.version("torchao")` can raise an error even + # though `importlib.util.find_spec("torchao") is not None` but it has been observed, so adding this for + # precaution. + return False + + if torchao_version < TORCHAO_MINIMUM_VERSION: + raise ImportError( + f"Found an incompatible version of torchao. Found version {torchao_version}, " + f"but only versions above {TORCHAO_MINIMUM_VERSION} are supported" + ) + return True + + +@lru_cache +def is_xpu_available(check_device=False) -> bool: + """ + Checks if XPU acceleration is available and potentially if a XPU is in the environment + """ + + system = platform.system() + if system == "Darwin": + return False + else: + if check_device: + try: + # Will raise a RuntimeError if no XPU is found + _ = torch.xpu.device_count() + return torch.xpu.is_available() + except RuntimeError: + return False + return hasattr(torch, "xpu") and torch.xpu.is_available() + + +@lru_cache +def is_diffusers_available() -> bool: + return importlib.util.find_spec("diffusers") is not None + + +@lru_cache +def is_te_available() -> bool: + return importlib.util.find_spec("transformer_engine") is not None + + +@lru_cache +def is_te_pytorch_available() -> bool: + if not is_te_available(): + return False + + import transformer_engine + + return hasattr(transformer_engine, "pytorch") diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/mapping.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/mapping.py new file mode 100644 index 0000000000000000000000000000000000000000..82c6ec1e40bb7b06f505b82346245b8bf00d789c --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/mapping.py @@ -0,0 +1,92 @@ +# 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 typing import TYPE_CHECKING, Any, Optional + +import torch + +from .utils import PeftType + + +if TYPE_CHECKING: + from .config import PeftConfig + from .tuners.tuners_utils import BaseTuner + + +# these will be filled by the register_peft_method function +PEFT_TYPE_TO_CONFIG_MAPPING: dict[PeftType, type[PeftConfig]] = {} +PEFT_TYPE_TO_TUNER_MAPPING: dict[PeftType, type[BaseTuner]] = {} +PEFT_TYPE_TO_MIXED_MODEL_MAPPING: dict[PeftType, type[BaseTuner]] = {} +PEFT_TYPE_TO_PREFIX_MAPPING: dict[PeftType, str] = {} + + +def get_peft_config(config_dict: dict[str, Any]) -> PeftConfig: + """ + Returns a Peft config object from a dictionary. + + Args: + config_dict (`Dict[str, Any]`): Dictionary containing the configuration parameters. + """ + + return PEFT_TYPE_TO_CONFIG_MAPPING[config_dict["peft_type"]](**config_dict) + + +def inject_adapter_in_model( + peft_config: PeftConfig, + model: torch.nn.Module, + adapter_name: str = "default", + low_cpu_mem_usage: bool = False, + state_dict: Optional[dict[str, torch.Tensor]] = None, +) -> torch.nn.Module: + r""" + Create PEFT layers and inject them into the model in-place. + + Currently the API does not support prompt learning methods and adaption prompt. + + This function is similar to [`get_peft_model`] but it does not return a [`PeftModel`] instance. Instead, it returns + the original, mutated instance of the passed model. + + Args: + peft_config (`PeftConfig`): + Configuration object containing the parameters of the PEFT model. + model (`torch.nn.Module`): + The input model where the adapter will be injected. + adapter_name (`str`, `optional`, defaults to `"default"`): + The name of the adapter to be injected, if not provided, the default adapter name is used ("default"). + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the loading process. + state_dict (`dict`, *optional*, defaults to `None`) + If a `state_dict` is passed here, the adapters will be injected based on the entries of the state_dict. + This can be useful when the exact `target_modules` of the PEFT method is unknown, for instance because the + checkpoint was created without meta data. Note that the values from the `state_dict` are not used, only the + keys are used to determine the correct layers that should be adapted. + """ + if peft_config.is_prompt_learning or peft_config.is_adaption_prompt: + raise ValueError("`create_and_replace` does not support prompt learning and adaption prompt yet.") + + if peft_config.peft_type not in PEFT_TYPE_TO_TUNER_MAPPING.keys(): + raise ValueError( + f"`inject_adapter_in_model` does not support {peft_config.peft_type} yet. Please use `get_peft_model`." + ) + + tuner_cls = PEFT_TYPE_TO_TUNER_MAPPING[peft_config.peft_type] + + # By instantiating a peft model we are injecting randomly initialized LoRA layers into the model's modules. + peft_model = tuner_cls( + model, peft_config, adapter_name=adapter_name, low_cpu_mem_usage=low_cpu_mem_usage, state_dict=state_dict + ) + + return peft_model.model diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/mapping_func.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/mapping_func.py new file mode 100644 index 0000000000000000000000000000000000000000..fae671819eb037e3a14f51dd2b94bffaaffaa819 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/mapping_func.py @@ -0,0 +1,128 @@ +# 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 warnings +from typing import Optional + +from transformers import PreTrainedModel + +from .auto import MODEL_TYPE_TO_PEFT_MODEL_MAPPING +from .config import PeftConfig +from .mapping import PEFT_TYPE_TO_CONFIG_MAPPING, PEFT_TYPE_TO_PREFIX_MAPPING +from .mixed_model import PeftMixedModel +from .peft_model import PeftModel +from .tuners.tuners_utils import BaseTuner, BaseTunerLayer + + +def get_peft_model( + model: PreTrainedModel, + peft_config: PeftConfig, + adapter_name: str = "default", + mixed: bool = False, + autocast_adapter_dtype: bool = True, + revision: Optional[str] = None, + low_cpu_mem_usage: bool = False, +) -> PeftModel | PeftMixedModel: + """ + Returns a Peft model object from a model and a config, where the model will be modified in-place. + + Args: + model ([`transformers.PreTrainedModel`]): + Model to be wrapped. + peft_config ([`PeftConfig`]): + Configuration object containing the parameters of the Peft model. + adapter_name (`str`, `optional`, defaults to `"default"`): + The name of the adapter to be injected, if not provided, the default adapter name is used ("default"). + mixed (`bool`, `optional`, defaults to `False`): + Whether to allow mixing different (compatible) adapter types. + autocast_adapter_dtype (`bool`, *optional*): + Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter weights + using float16 or bfloat16 to float32, as this is typically required for stable training, and only affect + select PEFT tuners. + revision (`str`, `optional`, defaults to `main`): + The revision of the base model. If this isn't set, the saved peft model will load the `main` revision for + the base model + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the loading process. Leave this setting as + False if you intend on training the model, unless the adapter weights will be replaced by different weights + before training starts. + """ + model_config = BaseTuner.get_model_config(model) + old_name = peft_config.base_model_name_or_path + new_name = model.__dict__.get("name_or_path", None) + peft_config.base_model_name_or_path = new_name + + # Especially in notebook environments there could be a case that a user wants to experiment with different + # configuration values. However, it is likely that there won't be any changes for new configs on an already + # initialized PEFT model. The best we can do is warn the user about it. + if any(isinstance(module, BaseTunerLayer) for module in model.modules()): + warnings.warn( + "You are trying to modify a model with PEFT for a second time. If you want to reload the model with a " + "different config, make sure to call `.unload()` before." + ) + + if (old_name is not None) and (old_name != new_name): + warnings.warn( + f"The PEFT config's `base_model_name_or_path` was renamed from '{old_name}' to '{new_name}'. " + "Please ensure that the correct base model is loaded when loading this checkpoint." + ) + + if revision is not None: + if peft_config.revision is not None and peft_config.revision != revision: + warnings.warn( + f"peft config has already set base model revision to {peft_config.revision}, overwriting with revision {revision}" + ) + peft_config.revision = revision + + if ( + (isinstance(peft_config, PEFT_TYPE_TO_CONFIG_MAPPING["LORA"])) + and (peft_config.init_lora_weights == "eva") + and not low_cpu_mem_usage + ): + warnings.warn( + "lora with eva initialization used with low_cpu_mem_usage=False. " + "Setting low_cpu_mem_usage=True can improve the maximum batch size possible for eva initialization." + ) + + prefix = PEFT_TYPE_TO_PREFIX_MAPPING.get(peft_config.peft_type) + if prefix and adapter_name in prefix: + warnings.warn( + f"Adapter name '{adapter_name}' should not be contained in the prefix '{prefix}'. " + "This may lead to reinitialization of the adapter weights during loading." + ) + + if mixed: + # note: PeftMixedModel does not support autocast_adapter_dtype, so don't pass it + return PeftMixedModel(model, peft_config, adapter_name=adapter_name) + + # We explicitly exclude prompt learning here since prompt learning is specific to the task and needs special + # handling in the PEFT model's forward method. + if peft_config.task_type not in MODEL_TYPE_TO_PEFT_MODEL_MAPPING.keys() and not peft_config.is_prompt_learning: + return PeftModel( + model, + peft_config, + adapter_name=adapter_name, + autocast_adapter_dtype=autocast_adapter_dtype, + low_cpu_mem_usage=low_cpu_mem_usage, + ) + + return MODEL_TYPE_TO_PEFT_MODEL_MAPPING[peft_config.task_type]( + model, + peft_config, + adapter_name=adapter_name, + autocast_adapter_dtype=autocast_adapter_dtype, + low_cpu_mem_usage=low_cpu_mem_usage, + ) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/mixed_model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/mixed_model.py new file mode 100644 index 0000000000000000000000000000000000000000..26409a6ed77f645b0296c44661b67ea0fdf159d2 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/mixed_model.py @@ -0,0 +1,473 @@ +# 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 os +from contextlib import contextmanager +from typing import Any, Optional, Union + +import torch +from accelerate.hooks import remove_hook_from_submodules +from torch import nn +from transformers.utils import PushToHubMixin + +from peft.utils.constants import DUMMY_MODEL_CONFIG + +from .config import PeftConfig +from .peft_model import PeftModel +from .tuners import MixedModel +from .utils import _set_adapter, _set_trainable + + +def _prepare_model_for_gradient_checkpointing(model: nn.Module) -> None: + r""" + Prepares the model for gradient checkpointing if necessary + """ + # Note: same as PeftModel._prepare_model_for_gradient_checkpointing + if not getattr(model, "is_gradient_checkpointing", True): + return model + + if not ( + getattr(model, "is_loaded_in_8bit", False) + or getattr(model, "is_loaded_in_4bit", False) + or getattr(model, "is_quantized", False) + ): + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + elif hasattr(model, "get_input_embeddings"): + + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + +def _check_config_compatible(peft_config: PeftConfig) -> None: + from .tuners.mixed import COMPATIBLE_TUNER_TYPES + + if peft_config.peft_type not in COMPATIBLE_TUNER_TYPES: + raise ValueError( + f"The provided `peft_type` '{peft_config.peft_type.value}' is not compatible with the `PeftMixedModel`. " + f"Compatible types are: {COMPATIBLE_TUNER_TYPES}" + ) + + +class PeftMixedModel(PushToHubMixin, torch.nn.Module): + """ + PeftMixedModel for loading mixing different types of adapters for inference. + + This class does not support loading/saving, and it shouldn't usually be initialized directly. Instead, use + `get_peft_model` with the argument `mixed=True`. + + > [!TIP] > Read the [Mixed adapter types](https://huggingface.co/docs/peft/en/developer_guides/mixed_models) guide + to learn > more about using different adapter types. + + Example: + + ```py + >>> base_model = ... # load the base model, e.g. from transformers + >>> peft_model = PeftMixedModel.from_pretrained(base_model, path_to_adapter1, "adapter1").eval() + >>> peft_model.load_adapter(path_to_adapter2, "adapter2") + >>> peft_model.set_adapter(["adapter1", "adapter2"]) # activate both adapters + >>> peft_model(data) # forward pass using both adapters + ``` + + Args: + model (`torch.nn.Module`): + The model to be tuned. + config (`PeftConfig`): + The config of the model to be tuned. The adapter type must be compatible. + adapter_name (`str`, `optional`, defaults to `"default"`): + The name of the first adapter. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the loading process. + """ + + def __init__(self, model: nn.Module, peft_config: PeftConfig, adapter_name: str = "default") -> None: + super().__init__() + _check_config_compatible(peft_config) + _prepare_model_for_gradient_checkpointing(model) + self.modules_to_save = None + self.base_model = MixedModel(model, {adapter_name: peft_config}, adapter_name) + self.set_modules_to_save(peft_config, adapter_name) + + self.config = getattr(model, "config", DUMMY_MODEL_CONFIG) + + # the `pretraining_tp` is set for some models to simulate Tensor Parallelism during inference to avoid + # numerical differences, https://github.com/pytorch/pytorch/issues/76232 - to avoid any unexpected + # behavior we disable that in this line. + if hasattr(self.base_model, "config") and hasattr(self.base_model.config, "pretraining_tp"): + self.base_model.config.pretraining_tp = 1 + + @property + def peft_config(self) -> dict[str, PeftConfig]: + return self.base_model.peft_config + + @property + def active_adapter(self) -> str: + return self.base_model.active_adapter + + @property + def active_adapters(self) -> list[str]: + return self.base_model.active_adapters + + def get_nb_trainable_parameters(self): + r""" + Returns the number of trainable parameters and number of all parameters in the model. + """ + # note: same as PeftModel.get_nb_trainable_parameters + trainable_params = 0 + all_param = 0 + for _, param in self.named_parameters(): + num_params = param.numel() + # if using DS Zero 3 and the weights are initialized empty + if num_params == 0 and hasattr(param, "ds_numel"): + num_params = param.ds_numel + + # Due to the design of 4bit linear layers from bitsandbytes + # one needs to multiply the number of parameters by 2 to get + # the correct number of parameters + if param.__class__.__name__ == "Params4bit": + num_params = num_params * 2 + + all_param += num_params + if param.requires_grad: + trainable_params += num_params + + return trainable_params, all_param + + def print_trainable_parameters(self): + """ + Prints the number of trainable parameters in the model. + + Note: print_trainable_parameters() uses get_nb_trainable_parameters() which is different from + num_parameters(only_trainable=True) from huggingface/transformers. get_nb_trainable_parameters() returns + (trainable parameters, all parameters) of the Peft Model which includes modified backbone transformer model. + For techniques like LoRA, the backbone transformer model is modified in place with LoRA modules. However, for + prompt tuning, the backbone transformer model is unmodified. num_parameters(only_trainable=True) returns number + of trainable parameters of the backbone transformer model which can be different. + """ + # note: same as PeftModel.print_trainable_parameters + trainable_params, all_param = self.get_nb_trainable_parameters() + + print( + f"trainable params: {trainable_params:,d} || " + f"all params: {all_param:,d} || " + f"trainable%: {100 * trainable_params / all_param:.4f}" + ) + + def __getattr__(self, name: str): + """Forward missing attributes to the wrapped module.""" + try: + return super().__getattr__(name) # defer to nn.Module's logic + except AttributeError: + if name == "base_model": # see #1892: prevent infinite recursion if class is not initialized + raise + return getattr(self.base_model, name) + + def forward(self, *args: Any, **kwargs: Any): + """ + Forward pass of the model. + """ + return self.base_model(*args, **kwargs) + + def generate(self, *args: Any, **kwargs: Any): + """ + Generate output. + """ + return self.base_model.generate(*args, **kwargs) + + @contextmanager + def disable_adapter(self): + """ + Disables the adapter module. + """ + try: + self.base_model.disable_adapter_layers() + yield + finally: + self.base_model.enable_adapter_layers() + + def add_adapter( + self, + adapter_name: str, + peft_config: PeftConfig, + low_cpu_mem_usage: bool = False, + autocast_adapter_dtype: bool = True, + ) -> None: + """ + Add an adapter to the model based on the passed configuration. + + This adapter is not trained. To load a trained adapter, check out [`PeftModel.load_adapter`]. + + The name for the new adapter should be unique. + + The new adapter is not automatically set as the active adapter. Use [`PeftModel.set_adapter`] to set the active + adapter. + + Args: + adapter_name (`str`): + The name of the adapter to be added. + peft_config ([`PeftConfig`]): + The configuration of the adapter to be added. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the process when loading saved + adapters. + + > [!TIP] > Don't use `low_cpu_mem_usage=True` when creating a new PEFT adapter for training (training + is untested > and discouraged for PeftMixedModel in general). + autocast_adapter_dtype (`bool`, *optional*, defaults to `True`): + Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter + weights using float16 and bfloat16 to float32, as this is typically required for stable training, and + only affect select PEFT tuners. If set to `False`, the dtypes will stay the same as those of the + corresponding layer. + """ + _check_config_compatible(peft_config) + + try: + self.peft_config[adapter_name] = peft_config + self.base_model.inject_adapter(self, adapter_name, low_cpu_mem_usage=low_cpu_mem_usage) + except Exception: # something went wrong, roll back + if adapter_name in self.peft_config: + del self.peft_config[adapter_name] + raise + + self.base_model._cast_adapter_dtype(adapter_name=adapter_name, autocast_adapter_dtype=autocast_adapter_dtype) + + self.set_modules_to_save(peft_config, adapter_name) + + def set_modules_to_save(self, peft_config: PeftConfig, adapter_name: str) -> None: + if (modules_to_save := getattr(peft_config, "modules_to_save", None)) is None: + return + + if self.modules_to_save is None: + self.modules_to_save = set(modules_to_save) + else: + self.modules_to_save.update(modules_to_save) + _set_trainable( + self, + adapter_name, + module_names=getattr(peft_config, "modules_to_save", None), + inference_mode=peft_config.inference_mode, + ) + + def set_adapter(self, adapter_name: Union[str, list[str]], inference_mode: bool = False) -> None: + """ + Sets the active adapter(s) for the model. + + Note that the order in which the adapters are applied during the forward pass may not be the same as the order + in which they are passed to this function. Instead, the order during the forward pass is determined by the + order in which the adapters were loaded into the model. The active adapters only determine which adapters are + active during the forward pass, but not the order in which they are applied. + + Additionally, this function will set the specified adapter to trainable (i.e., requires_grad=True) unless + inference_mode is True. + + Args: + adapter_name (str, list[str]): + The name(s) of the adapter(s) to set as active + inference_mode (bool, optional): + Whether the activated adapter should be frozen (i.e. `requires_grad=False`). Default is False. + """ + if isinstance(adapter_name, str): + adapter_name = [adapter_name] + + mismatched = set(adapter_name) - set(self.peft_config.keys()) + if mismatched: + raise ValueError( + f"Adapter(s) {sorted(mismatched)} not found, available adapters: {sorted(self.peft_config.keys())}" + ) + + self.base_model.set_adapter(adapter_name, inference_mode=inference_mode) + _set_adapter(self, adapter_name, inference_mode=inference_mode) + + def delete_adapter(self, adapter_name: Union[str, list[str]]) -> None: + if isinstance(adapter_name, str): + adapter_name = [adapter_name] + + mismatched = set(adapter_name) - set(self.peft_config.keys()) + if mismatched: + raise ValueError( + f"Adapter(s) {sorted(mismatched)} not found, available adapters: {sorted(self.peft_config.keys())}" + ) + + self.base_model.delete_adapter(adapter_name) + + def merge_and_unload(self, *args: Any, **kwargs: Any): + r""" + This method merges the adapter layers into the base model. This is needed if someone wants to use the base + model as a standalone model. + + Args: + progressbar (`bool`): + whether to show a progressbar indicating the unload and merge process + safe_merge (`bool`): + whether to activate the safe merging check to check if there is any potential Nan in the adapter + weights + 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`. + """ + return self.base_model.merge_and_unload(*args, **kwargs) + + def unload(self, *args: Any, **kwargs: Any): + """ + Gets back the base model by removing all the adapter modules without merging. This gives back the original base + model. + """ + return self.base_model.unload(*args, **kwargs) + + def get_layer_status(self): + raise TypeError(f"get_layer_status is not supported for {self.__class__.__name__}.") + + def get_model_status(self): + raise TypeError(f"get_model_status is not supported for {self.__class__.__name__}.") + + @classmethod + def _split_kwargs(cls, kwargs: dict[str, Any]): + return PeftModel._split_kwargs(kwargs) + + def _check_new_adapter_config(self, peft_config: PeftConfig, is_trainable: bool) -> None: + return PeftModel._check_new_adapter_config(self, peft_config, is_trainable=is_trainable) + + def load_adapter(self, model_id: str, adapter_name: str, *args: Any, **kwargs: Any): + """ + Load a trained adapter into the model. + + The name for the new adapter should be unique. + + The new adapter is not automatically set as the active adapter. Use [`PeftModel.set_adapter`] to set the active + adapter. + + Args: + adapter_name (`str`): + The name of the adapter to be added. + peft_config ([`PeftConfig`]): + The configuration of the adapter to be added. + is_trainable (`bool`, *optional*, defaults to `False`): + Whether the adapter should be trainable or not. If `False`, the adapter will be frozen and can only be + used for inference. + torch_device (`str`, *optional*, defaults to None): + The device to load the adapter on. If `None`, the device will be inferred. + autocast_adapter_dtype (`bool`, *optional*, defaults to `True`): + Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter + weights using float16 and bfloat16 to float32, as this is typically required for stable training, and + only affect select PEFT tuners. + ephemeral_gpu_offload (`bool`, *optional*, defaults to `False`): + Whether to use ephemeral GPU offloading for partially loaded modules. Defaults to `False`. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device before loading the saved weights. Useful to speed up the + process. + kwargs: (`optional`): + Additional arguments to modify the way the adapter is loaded, e.g. the token for Hugging Face Hub. + """ + # the low_cpu_mem_usage option is handled through kwargs + output = PeftModel.load_adapter(self, model_id, adapter_name, *args, **kwargs) + # TODO: not quite clear why this is necessary but tests fail without it + self.set_adapter(self.active_adapters) + return output + + def create_or_update_model_card(self, output_dir: str): + raise NotImplementedError(f"Model card creation is not supported for {self.__class__.__name__} (yet).") + + def save_pretrained( + self, + save_directory: str, + safe_serialization: bool = False, + selected_adapters: Optional[list[str]] = None, + **kwargs: Any, + ): + raise NotImplementedError(f"Saving is not supported for {self.__class__.__name__} (yet).") + + @classmethod + def from_pretrained( + cls, + model: nn.Module, + model_id: str | os.PathLike, + adapter_name: str = "default", + is_trainable: bool = False, + config: Optional[PeftConfig] = None, + **kwargs: Any, + ): + r""" + Instantiate a PEFT mixed model from a pretrained model and loaded PEFT weights. + + Note that the passed `model` may be modified inplace. + + Args: + model (`nn.Module`): + The model to be adapted. + model_id (`str` or `os.PathLike`): + The name of the PEFT configuration to use. Can be either: + - A string, the `model id` of a PEFT configuration hosted inside a model repo on the Hugging Face + Hub. + - A path to a directory containing a PEFT configuration file saved using the `save_pretrained` + method (`./my_peft_config_directory/`). + adapter_name (`str`, *optional*, defaults to `"default"`): + The name of the adapter to be loaded. This is useful for loading multiple adapters. + is_trainable (`bool`, *optional*, defaults to `False`): + Whether the adapter should be trainable or not. If `False`, the adapter will be frozen and use for + inference + config ([`~peft.PeftConfig`], *optional*): + The configuration object to use instead of an automatically loaded configuration. This configuration + object is mutually exclusive with `model_id` and `kwargs`. This is useful when configuration is already + loaded before calling `from_pretrained`. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device before loading the saved weights. Useful to speed up the + process. + kwargs: (`optional`): + Additional keyword arguments passed along to the specific PEFT configuration class. + """ + # note: adapted from PeftModel.from_pretrained + from .mapping import PEFT_TYPE_TO_CONFIG_MAPPING, PEFT_TYPE_TO_MIXED_MODEL_MAPPING + + # load the config + if config is None: + hf_kwargs = { + "subfolder": kwargs.get("subfolder", None), + "revision": kwargs.get("revision", None), + "cache_dir": kwargs.get("cache_dir", None), + "token": kwargs.get("token", None), + } + if use_auth_token := kwargs.get("use_auth_token", None): + hf_kwargs["use_auth_token"] = use_auth_token + config = PEFT_TYPE_TO_CONFIG_MAPPING[PeftConfig._get_peft_type(model_id, **hf_kwargs)].from_pretrained( + model_id, **kwargs + ) + elif isinstance(config, PeftConfig): + config.inference_mode = not is_trainable + else: + raise ValueError(f"The input config must be a PeftConfig, got {config.__class__}") + + # note: this is different from PeftModel.from_pretrained + if config.peft_type not in PEFT_TYPE_TO_MIXED_MODEL_MAPPING: + raise ValueError(f"Adapter of type {config.peft_type} is not supported for mixed models.") + + if (getattr(model, "hf_device_map", None) is not None) and len( + set(model.hf_device_map.values()).intersection({"cpu", "disk"}) + ) > 0: + remove_hook_from_submodules(model) + + if config.is_prompt_learning and is_trainable: + # note: should not be possible to reach, but just in case + raise ValueError("Cannot set a prompt learning adapter to trainable when loading pretrained adapter.") + else: + config.inference_mode = not is_trainable + + # note: this is different from PeftModel.from_pretrained, we always return a PeftMixedModel + model = cls(model, config, adapter_name) + # the low_cpu_mem_usage option is handled through kwargs + model.load_adapter(model_id, adapter_name, is_trainable=is_trainable, **kwargs) + return model diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/optimizers/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/optimizers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0e8821f45db8e2dcf8f26fd8b38f8f90a28f5c09 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/optimizers/__init__.py @@ -0,0 +1,19 @@ +# 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 .lorafa import create_lorafa_optimizer +from .loraplus import create_loraplus_optimizer + + +__all__ = ["create_lorafa_optimizer", "create_loraplus_optimizer"] diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/optimizers/lorafa.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/optimizers/lorafa.py new file mode 100644 index 0000000000000000000000000000000000000000..bbf282b7e3d980ed3e93c4098ecdee316839fc70 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/optimizers/lorafa.py @@ -0,0 +1,255 @@ +# 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 contains the implementation of the LoRA-FA optimizer. +""" + +from __future__ import annotations + +import math +from collections.abc import Callable, Iterable + +import torch +from accelerate.utils.imports import is_bf16_available +from torch import autocast, nn +from torch.optim import Optimizer + +from ..peft_model import PeftModel +from ..utils.other import infer_device + + +class LoraFAOptimizer(Optimizer): + """ + Implements the LoRA-FA optimizer designed specifically for training Low-Rank Adaptation (LoRA) parameters + efficiently. Note that LoraFAOptimizer is based on adamw-hf in transformers, with only LoRA part modified. Without + LoRA it will fall back to adamw-hf. + + Args: + params (Iterable[nn.parameter.Parameter]): Parameters to optimize. + lr (float, optional): Learning rate (default: 1e-3). + betas (Tuple[float, float], optional): + Coefficients for computing running averages of gradient and squared gradient (default: (0.9, 0.999)). + eps (float, optional): Term added to denominator to improve numerical stability (default: 1e-6). + weight_decay (float, optional): Weight decay (L2 penalty) (default: 0.0). + correct_bias (bool, optional): Whether to apply bias correction as in original Adam (default: True). + + Args in sub-function step: + closure (Callable, optional): A closure that reevaluates the model and returns the loss. + + Reference: + - LoRA-FA: https://huggingface.co/papers/2308.03303 + """ + + def __init__( + self, + params: Iterable[nn.parameter.Parameter], + lr: float = 1e-3, + betas: tuple[float, float] = (0.9, 0.999), + eps: float = 1e-6, + weight_decay: float = 0.0, + correct_bias: bool = True, + ): + if lr < 0.0: + raise ValueError(f"Invalid learning rate: {lr} - should be >= 0.0") + if not 0.0 <= betas[0] < 1.0: + raise ValueError(f"Invalid beta parameter: {betas[0]} - should be in [0.0, 1.0)") + if not 0.0 <= betas[1] < 1.0: + raise ValueError(f"Invalid beta parameter: {betas[1]} - should be in [0.0, 1.0)") + if not 0.0 <= eps: + raise ValueError(f"Invalid epsilon value: {eps} - should be >= 0.0") + defaults = { + "lr": lr, + "betas": betas, + "eps": eps, + "weight_decay": weight_decay, + "correct_bias": correct_bias, + } + super().__init__(params, defaults) + + @torch.no_grad() + def step(self, closure: Callable | None = None): + """ + Performs a single optimization step. + + Arguments: + closure (`Callable`, *optional*): A closure that reevaluates the model and returns the loss. + """ + loss = None + if closure is not None: + loss = closure() + + for group in self.param_groups: + scaling_factor = group["scaling_factor"] + param_list = [] + name_list = [] + for p, n in zip(group["params"], group["names"]): + # Skip non-lora no-grad module, since we need lora_A which is no-grad. + if "lora" not in n and p.grad is None: + continue + grad = p.grad + + if "lora" in n: + param_list.append(p) + name_list.append(n) + if len(param_list) == 2: + name = n[: n.find("lora")] + "lora" + elif len(param_list) == 1: + continue + else: + name = n + # param_list contains a pair of A and B adapters + # i.e., param_list -> [A,B] + + state = self.state[name] + # State initialization + if len(state) == 0: + if len(param_list) == 2: + state["step"] = 0 + # Exponential moving average of gradient values + state["exp_avg_B"] = torch.zeros_like(param_list[1]) + # Exponential moving average of squared gradient values + state["exp_avg_sq_B"] = torch.zeros_like(param_list[1]) + else: + state["step"] = 0 + # Exponential moving average of gradient values + state["exp_avg"] = torch.zeros_like(p) + # Exponential moving average of squared gradient values + state["exp_avg_sq"] = torch.zeros_like(p) + + # Below is the LoRA-FA part + # 1. In this part, we optimize the gradient of B as: + # g^B = \left(\frac{r}{\alpha}\right)^2 (A^\top A)^{-1} g_{\text{LoRA-FA}}^B + # to min the func as described below: + # \min_{g^B} \|\hat{g}_\text{LoRA-FA} - g\|_F^2 + # 2. After the gradient of B is ready, update the optimizer state + if len(param_list) == 2: + A = param_list[0] + B = param_list[1] + grad_B_orin = B.grad + + # projection + delta = 1e-8 + + # computing the inverse matrix + AA_T = A @ A.T + AA_T_inv = torch.linalg.pinv(AA_T + delta * torch.eye(A.shape[0]).to(A.device)) + + device_type = infer_device() + + if is_bf16_available(): + with autocast(device_type=device_type, dtype=torch.bfloat16): + grad_B = (1 / scaling_factor**2) * (grad_B_orin @ AA_T_inv) + else: + grad_B = (1 / scaling_factor**2) * (grad_B_orin @ AA_T_inv) + + if grad_B.dtype != B.grad.dtype: + grad_B = grad_B.to(B.grad.dtype) + + exp_avg_B, exp_avg_sq_B = state["exp_avg_B"], state["exp_avg_sq_B"] + beta1, beta2 = group["betas"] + state["step"] += 1 + exp_avg_B.mul_(beta1).add_(grad_B, alpha=(1.0 - beta1)) + exp_avg_sq_B.mul_(beta2).addcmul_(grad_B, grad_B, value=1.0 - beta2) + + denom_B = exp_avg_sq_B.sqrt().add_(group["eps"]) + step_size = group["lr"] + if group["correct_bias"]: # No bias correction for Bert + bias_correction1 = 1.0 - beta1 ** state["step"] + bias_correction2 = 1.0 - beta2 ** state["step"] + step_size = step_size * math.sqrt(bias_correction2) / bias_correction1 + B.addcdiv_(exp_avg_B, denom_B, value=-step_size) + if group["weight_decay"] > 0.0: + B.add_(B, alpha=(-group["lr"] * group["weight_decay"])) + param_list = [] + name_list = [] + + # Below is the original AdamW + else: + exp_avg, exp_avg_sq = state["exp_avg"], state["exp_avg_sq"] + beta1, beta2 = group["betas"] + + state["step"] += 1 + + # Decay the first and second moment running average coefficient + # In-place operations to update the averages at the same time + exp_avg.mul_(beta1).add_(grad, alpha=(1.0 - beta1)) + exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=1.0 - beta2) + denom = exp_avg_sq.sqrt().add_(group["eps"]) + + step_size = group["lr"] + if group["correct_bias"]: # No bias correction for Bert + bias_correction1 = 1.0 - beta1 ** state["step"] + bias_correction2 = 1.0 - beta2 ** state["step"] + step_size = step_size * math.sqrt(bias_correction2) / bias_correction1 + + p.addcdiv_(exp_avg, denom, value=-step_size) + + # Just adding the square of the weights to the loss function is *not* + # the correct way of using L2 regularization/weight decay with Adam, + # since that will interact with the m and v parameters in strange ways. + # + # Instead we want to decay the weights in a manner that doesn't interact + # with the m/v parameters. This is equivalent to adding the square + # of the weights to the loss with plain (non-momentum) SGD. + # Add weight decay at the end (fixed version) + if group["weight_decay"] > 0.0: + p.add_(p, alpha=(-group["lr"] * group["weight_decay"])) + + return loss + + +def create_lorafa_optimizer( + model: PeftModel, r: int, lora_alpha: int, lr: float, weight_decay: float = 0.0, use_rslora: bool = False +) -> Optimizer: + """ + Helper function to instantiate a lorafa optimizer specifically configured for a given model using the LoRA method. + + This function will: + - Disable gradient updates for the "lora_A" parameters (these are typically frozen during LoRA training). + - Compute the scaling factor based on provided `lora_alpha` and rank `r` for proper gradient projection. + - Create and configure parameter groups for the optimizer including specified learning rate, weight decay, and + additional optimizer options. + + For hyper-params, LoRA-FA uses the same hyper-params as AdamW, except for the LoRA hyper-params (r, lora_alpha, + use_rslora). One can always use the same hyper-params such as lr and weight_decay, as AdamW in LoRA tuning. + + Args: + model (PeftModel): The model containing LoRA-adapted parameters. + r (int): Rank of the LoRA decomposition. + lora_alpha (int): Scaling factor for LoRA parameterization. + lr (float): Learning rate for optimizer updates. + weight_decay (float): Weight decay for AdamW. + use_rslora (bool): + whether to use rslora. In rslora, the lora scaling factor becomes to lora_alpha / math.sqrt(r) instead of + lora_alpha / r. + + Returns: + Optimizer: Configured lorafa optimizer instance ready for training. + """ + for name, param in model.named_parameters(): + if "lora_A" in name: + param.requires_grad_(False) + lora_scaling = lora_alpha / math.sqrt(r) if use_rslora else lora_alpha / r + param_groups = [ + { + "params": model.parameters(), + "lr": lr, + "names": [name for name, _ in model.named_parameters()], + "scaling_factor": lora_scaling, + "betas": (0.9, 0.999), + "weight_decay": weight_decay, + } + ] + return LoraFAOptimizer(param_groups) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/optimizers/loraplus.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/optimizers/loraplus.py new file mode 100644 index 0000000000000000000000000000000000000000..bdb4215db3c808cb4b30ccb2370818049fea27d1 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/optimizers/loraplus.py @@ -0,0 +1,121 @@ +# 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. + +""" +This module contains the implementation of the LoraPlus optimizer. +""" + +from __future__ import annotations + +from operator import attrgetter + +from torch import nn +from torch.optim import Optimizer +from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS +from transformers.trainer_pt_utils import get_parameter_names + +from ..peft_model import PeftModel +from ..tuners.lora.layer import Embedding + + +def create_loraplus_optimizer( + model: PeftModel, optimizer_cls: type[Optimizer], *, lr: float, loraplus_lr_ratio: float, **kwargs +) -> Optimizer: + """ + Creates a LoraPlus optimizer. + + Efficient Low Rank Adaptation of Large Models: https://huggingface.co/papers/2402.12354 + + Reference: https://github.com/nikhil-ghosh-berkeley/loraplus/ + + Args: + model (`torch.nn.Module`): The model to be optimized. + optimizer_cls (`torch.optim.Optimizer`): The optimizer class to be used. + lr (`float`): The learning rate to be used for the optimizer. + loraplus_lr_ratio (`float`): + The ratio of learning ηB/ηA where ηA (lr) is passed in as the optimizer learning rate. Should be ≥1. Should + be set in tandem with the optimizer learning rate (lr); should be larger when the task is more difficult + and the model needs to update its features to learn well. In this case, it helps to make the learning rate + slightly smaller (e.g., by a factor of 2) than typical vanilla LoRA learning rates + loraplus_lr_embedding (optional `float`): + If LoRA modules are added to embedding layers your can specify a different learning rate for them. Default + value 1e-6. + kwargs (`dict`): Additional keyword arguments to be passed to the optimizer. + + Returns: + `torch.optim.Optimizer`: An instance of the specified optimizer class configured with the model's parameters + organized into groups with custom learning rates. + """ + + decay_parameters = get_parameter_names(model, ALL_LAYERNORM_LAYERS) + decay_parameters = [name for name in decay_parameters if "bias" not in name] + param_groups = { + "groupA": {}, + "groupB": {}, + "groupB_no_decay": {}, + "embedding": {}, + } + + for name, param in model.named_parameters(): + if not param.requires_grad: + continue + + module = attrgetter(name)(model) + if isinstance(module, Embedding): + param_groups["embedding"][name] = param + elif "lora_B" in name or param.ndim == 1: + if name in decay_parameters: + param_groups["groupB"][name] = param + else: + param_groups["groupB_no_decay"][name] = param + else: + param_groups["groupA"][name] = param + + kwargs["lr"] = lr + loraplus_weight_decay = kwargs.pop("loraplus_weight_decay", 0.0) + loraplus_lr_embedding = kwargs.pop("loraplus_lr_embedding", 1e-6) + + optimizer_grouped_parameters = [ + { + "params": list(param_groups["groupA"].values()), + "weight_decay": loraplus_weight_decay, + "lr": lr, + }, + { + "params": list(param_groups["embedding"].values()), + "weight_decay": loraplus_weight_decay, + "lr": loraplus_lr_embedding, + }, + { + "params": list(param_groups["groupB"].values()), + "weight_decay": loraplus_weight_decay, + "lr": lr * loraplus_lr_ratio, + }, + { + "params": list(param_groups["groupB_no_decay"].values()), + "weight_decay": 0.0, + "lr": lr * loraplus_lr_ratio, + }, + ] + + optimizer = optimizer_cls(optimizer_grouped_parameters, **kwargs) + eight_bit_names = ["Adam8bit", "AdamW8bit", "PagedAdam8bit", "PagedAdamW8bit"] + if optimizer_cls.__name__ in eight_bit_names: + import bitsandbytes + + manager = bitsandbytes.optim.GlobalOptimManager.get_instance() + for module in model.modules(): + if isinstance(module, nn.Embedding): + manager.register_module_override(module, "weight", {"optim_bits": 32}) + return optimizer diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/peft_model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/peft_model.py new file mode 100644 index 0000000000000000000000000000000000000000..b1140fbed46f9161be85f39e76c57230a18cbd5e --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/peft_model.py @@ -0,0 +1,3524 @@ +# 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 collections +import copy +import inspect +import os +import warnings +from collections.abc import Sequence +from contextlib import contextmanager, nullcontext +from copy import deepcopy +from dataclasses import dataclass +from typing import Any, Literal, Optional, Union + +import packaging.version +import torch +import transformers +from accelerate import dispatch_model, infer_auto_device_map +from accelerate.hooks import AlignDevicesHook, add_hook_to_module, remove_hook_from_submodules +from accelerate.utils import get_balanced_memory, named_module_tensors +from huggingface_hub import HfFileSystem, ModelCard, ModelCardData, hf_hub_download +from safetensors import safe_open +from safetensors.torch import save_file as safe_save_file +from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss +from transformers import Cache, DynamicCache, EncoderDecoderCache, PreTrainedModel +from transformers.modeling_outputs import QuestionAnsweringModelOutput, SequenceClassifierOutput, TokenClassifierOutput +from transformers.utils import PushToHubMixin + +from peft.tuners.lora.variants import get_alora_offsets_for_forward, get_alora_offsets_for_generate +from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer +from peft.utils import AuxiliaryTrainingWrapper +from peft.utils.constants import DUMMY_MODEL_CONFIG +from peft.utils.integrations import init_empty_weights +from peft.utils.other import TrainableTokensWrapper, create_attention_mask, set_additional_trainable_modules + +from . import __version__ +from .config import PeftConfig +from .mapping import PEFT_TYPE_TO_CONFIG_MAPPING, PEFT_TYPE_TO_PREFIX_MAPPING, PEFT_TYPE_TO_TUNER_MAPPING +from .utils import ( + SAFETENSORS_WEIGHTS_NAME, + TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING, + WEIGHTS_NAME, + PeftType, + TaskType, + _get_batch_size, + _prepare_prompt_learning_config, + _set_adapter, + _set_trainable, + get_peft_model_state_dict, + id_tensor_storage, + infer_device, + load_peft_weights, + map_cache_to_layer_device_map, + set_peft_model_state_dict, + shift_tokens_right, +) + + +def _get_layer_kv_target_shape(base_config, layer_idx: int) -> tuple[int, int] | None: + """Per-layer (num_kv_heads, head_dim) for prefix-tuning injection, or None for uniform models. + + Models with heterogeneous attention (e.g. Gemma4) expose `global_head_dim` / `num_global_key_value_heads` alongside + the sliding-layer `head_dim` / `num_key_value_heads`. The provisioned prefix is sized for the global footprint; + this returns the shape each layer actually expects so the caller can slice down or skip layers that don't fit. + """ + layer_types = getattr(base_config, "layer_types", None) + global_head_dim = getattr(base_config, "global_head_dim", None) + if not layer_types or global_head_dim is None: + return None + + is_sliding = layer_types[layer_idx] == "sliding_attention" + head_dim = base_config.head_dim if is_sliding else global_head_dim + num_global_kv = getattr(base_config, "num_global_key_value_heads", None) + if not is_sliding and num_global_kv is not None: + num_kv_heads = num_global_kv + else: + num_kv_heads = base_config.num_key_value_heads + return num_kv_heads, head_dim + + +class PeftModel(PushToHubMixin, torch.nn.Module): + """ + Base model encompassing various Peft methods. + + Args: + model ([`~transformers.PreTrainedModel`]): The base transformer model used for Peft. + peft_config ([`PeftConfig`]): The configuration of the Peft model. + adapter_name (`str`, *optional*): The name of the adapter, defaults to `"default"`. + autocast_adapter_dtype (`bool`, *optional*, defaults to `True`): + Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter weights + using float16 and bfloat16 to float32, as this is typically required for stable training, and only affect + select PEFT tuners. If set to `False`, the dtypes will stay the same as those of the corresponding layer. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the loading loading process. + + > [!TIP] > Don't use `low_cpu_mem_usage=True` when creating a new PEFT adapter for training. + + **Attributes**: + - **base_model** ([`torch.nn.Module`]) -- The base transformer model used for Peft. + - **peft_config** ([`PeftConfig`]) -- The configuration of the Peft model. + - **modules_to_save** (`list` of `str`) -- The list of sub-module names to save when + saving the model. + - **prompt_encoder** ([`PromptEncoder`]) -- The prompt encoder used for Peft if + using [`PromptLearningConfig`]. + - **prompt_tokens** (`torch.Tensor`) -- The virtual prompt tokens used for Peft if + using [`PromptLearningConfig`]. + - **transformer_backbone_name** (`str`) -- The name of the transformer + backbone in the base model if using [`PromptLearningConfig`]. + - **word_embeddings** (`torch.nn.Embedding`) -- The word embeddings of the transformer backbone + in the base model if using [`PromptLearningConfig`]. + """ + + def __init__( + self, + model: PreTrainedModel, + peft_config: PeftConfig, + adapter_name: str = "default", + autocast_adapter_dtype: bool = True, + low_cpu_mem_usage: bool = False, + ) -> None: + super().__init__() + self.active_adapter = adapter_name + self.peft_type = peft_config.peft_type + # These args are special PEFT arguments that users can pass. They need to be removed before passing them to + # forward. + self.special_peft_forward_args = {"adapter_names", "alora_offsets"} + + self._is_prompt_learning = peft_config.is_prompt_learning + if self._is_prompt_learning: + self._peft_config = {adapter_name: peft_config} + self.base_model = model + self.add_adapter(adapter_name, peft_config, low_cpu_mem_usage=low_cpu_mem_usage) + else: + self._peft_config = None + cls = PEFT_TYPE_TO_TUNER_MAPPING[peft_config.peft_type] + ctx = init_empty_weights if low_cpu_mem_usage else nullcontext + with ctx(): + self.base_model = cls(model, {adapter_name: peft_config}, adapter_name) + + if hasattr(self.base_model, "_cast_adapter_dtype"): + self.base_model._cast_adapter_dtype( + adapter_name=adapter_name, autocast_adapter_dtype=autocast_adapter_dtype + ) + + if getattr(model, "is_gradient_checkpointing", True): + model = self.prepare_model_for_gradient_checkpointing(model) + + # the `pretraining_tp` is set for some models to simulate Tensor Parallelism during inference to avoid + # numerical differences, https://github.com/pytorch/pytorch/issues/76232 - to avoid any unexpected + # behavior we disable that in this line. + if hasattr(self.base_model, "config") and hasattr(self.base_model.config, "pretraining_tp"): + self.base_model.config.pretraining_tp = 1 + + self._adapters_disabled = False + + @property + def peft_config(self) -> dict[str, PeftConfig]: + if self._is_prompt_learning: + return self._peft_config + return self.base_model.peft_config + + @property + def active_adapters(self) -> list[str]: + try: + adapters = self.base_model.active_adapters + if not isinstance(adapters, list): + # Base model is probably a transformers model, see: + # https://github.com/huggingface/transformers/pull/30790#issuecomment-2253808249 + # Unfortunately, transformers models also have an active_adapters method but it's 1) not a property and + # 2) calling it fails because the base model (usually) has no loaded adapter. The base model can be a + # transformers model for prompt learning, where the base model is not wrapped in a LoraModel or similar. + adapters = self.active_adapter + if isinstance(adapters, str): + adapters = [adapters] + except AttributeError: + adapters = self.active_adapter + if isinstance(adapters, str): + adapters = [adapters] + return adapters + + @property + def has_active_enabled_adapter(self) -> bool: + """Reflects whether the adapters are purposefully disabled (via disable_adapter) or if there + are no active adapters (enabled but inactive). They are two separate mechanisms but sometimes it is helpful to + know whether the model has any active/enabled adapter at all. + """ + if self.peft_config[self.active_adapter].is_prompt_learning: + return not self._adapters_disabled + + return not self._adapters_disabled or not self.active_adapters + + @peft_config.setter + def peft_config(self, value: dict[str, PeftConfig]): + if self._is_prompt_learning: + self._peft_config = value + else: + self.base_model.peft_config = value + + def save_pretrained( + self, + save_directory: str, + safe_serialization: bool = True, + selected_adapters: Optional[list[str]] = None, + save_embedding_layers: Union[str, bool] = "auto", + is_main_process: bool = True, + path_initial_model_for_weight_conversion: Optional[str] = None, + **kwargs: Any, + ) -> None: + r""" + This function saves the adapter model and the adapter configuration files to a directory, so that it can be + reloaded using the [`PeftModel.from_pretrained`] class method, and also used by the [`PeftModel.push_to_hub`] + method. + + Args: + save_directory (`str`): + Directory where the adapter model and configuration files will be saved (will be created if it does not + exist). + safe_serialization (`bool`, *optional*): + Whether to save the adapter files in safetensors format, defaults to `True`. + selected_adapters (`List[str]`, *optional*): + A list of adapters to be saved. If `None`, will default to all adapters. + save_embedding_layers (`Union[bool, str]`, *optional*, defaults to `"auto"`): + If `True`, save the embedding layers in addition to adapter weights. If `auto`, checks the common + embedding layers `peft.utils.other.EMBEDDING_LAYER_NAMES` in config's `target_modules` when available. + and automatically sets the boolean flag. This only works for 🤗 transformers models. + is_main_process (`bool`, *optional*): + Whether the process calling this is the main process or not. Will default to `True`. Will not save the + checkpoint if not on the main process, which is important for multi device setups (e.g. DDP). + path_initial_model_for_weight_conversion (`str`, *optional*): + The path to the initialized adapter, which is obtained after initializing the model with + PiSSA/CorDA/OLoRA and before performing any training. When `path_initial_model_for_weight_conversion` + is not None, the difference in adapter before and after fine-tuning is calculated. This difference can + be represented as the parameters of a standard LoRA adapter. Using this converted adapter does not + require changes to the base model, thus conveniently allowing the use of multiple PiSSA/CorDA/OLoRA + adapters with LoRA adapters, and the activation or deactivation of any adapters. Note that this + conversion is not supported if `rslora` is used in combination with `rank_pattern` or `alpha_pattern`. + kwargs (additional keyword arguments, *optional*): + Additional keyword arguments passed along to the `push_to_hub` method. + + """ + if os.path.isfile(save_directory): + raise ValueError(f"Provided path ({save_directory}) should be a directory, not a file") + + if selected_adapters is None: + selected_adapters = list(self.peft_config.keys()) + else: + if any( + selected_adapter_name not in list(self.peft_config.keys()) + for selected_adapter_name in selected_adapters + ): + raise ValueError( + f"You passed an invalid `selected_adapters` arguments, current supported adapter names are" + f" {list(self.peft_config.keys())} - got {selected_adapters}." + ) + + def save_mutated_as_lora(peft_config, path_initial_model_for_weight_conversion, output_state_dict, kwargs): + if peft_config.use_rslora and (peft_config.rank_pattern or peft_config.alpha_pattern): + msg = ( + "Passing `path_initial_model_for_weight_conversion` to `save_pretrained` is not supported when " + "using `rank_pattern` or `alpha_pattern` at the same time as `use_rslora=True`." + ) + raise ValueError(msg) + + if not any( + str(peft_config.init_lora_weights).lower().startswith(prefix) + for prefix in ["pissa", "corda", "olora", "lora_ga", "true"] + ): + warnings.warn( + "`path_initial_model_for_weight_conversion` only works for converting a PiSSA/CorDA/OLoRA/LoRA-GA adapter to " + "a LoRA adapter" + ) + initial_adapter_name = os.path.basename(path_initial_model_for_weight_conversion) + try: + self.load_adapter( + os.path.dirname(path_initial_model_for_weight_conversion), + subfolder=initial_adapter_name, + adapter_name=initial_adapter_name, + ) + is_pissa = str(self.peft_config[initial_adapter_name].init_lora_weights).lower().startswith("pissa") + is_corda = str(self.peft_config[initial_adapter_name].init_lora_weights).lower() == "corda" + is_olora = str(self.peft_config[initial_adapter_name].init_lora_weights).lower() == "olora" + is_lora_ga = str(self.peft_config[initial_adapter_name].init_lora_weights).lower() == "lora_ga" + if is_pissa or is_corda or is_olora or is_lora_ga: + raise ValueError( + "The `init_lora_weights` parameter of the initial adapter should be set to `True`. " + "Otherwise, `self.load_adapter` will subtract the decomposed values again based on the " + "residual model." + ) + output_state_dict = self.base_model.subtract_mutated_init( + output_state_dict, initial_adapter_name, kwargs + ) + finally: + self.delete_adapter(initial_adapter_name) + return output_state_dict + + if is_main_process: + os.makedirs(save_directory, exist_ok=True) + self.create_or_update_model_card(save_directory) + + for adapter_name in selected_adapters: + peft_config = self.peft_config[adapter_name] + # save only the trainable weights + output_state_dict = get_peft_model_state_dict( + self, + state_dict=kwargs.get("state_dict", None), + adapter_name=adapter_name, + save_embedding_layers=save_embedding_layers, + ) + output_dir = os.path.join(save_directory, adapter_name) if adapter_name != "default" else save_directory + os.makedirs(output_dir, exist_ok=True) + + if is_main_process and safe_serialization: + # Section copied from: https://github.com/huggingface/transformers/blob/main/src/transformers/modeling_utils.py#L2111-L2134 + # Safetensors does not allow tensor aliasing. + # We're going to remove aliases before saving + ptrs = collections.defaultdict(list) + for name, tensor in output_state_dict.items(): + # Sometimes in the state_dict we have non-tensor objects. + # e.g. in bitsandbytes we have some `str` objects in the state_dict + if isinstance(tensor, torch.Tensor): + ptrs[id_tensor_storage(tensor)].append(name) + else: + # In the non-tensor case, fall back to the pointer of the object itself + ptrs[id(tensor)].append(name) + + # These are all the pointers of shared tensors. + shared_ptrs = {ptr: names for ptr, names in ptrs.items() if len(names) > 1} + + for names in shared_ptrs.values(): + # Here we just clone the shared tensors to avoid tensor aliasing which is + # not supported in safetensors. + for shared_tensor_name in names[1:]: + output_state_dict[shared_tensor_name] = output_state_dict[shared_tensor_name].clone() + if path_initial_model_for_weight_conversion is not None: + peft_config = copy.deepcopy(peft_config) + peft_config.init_lora_weights = True + peft_config.save_pretrained(path_initial_model_for_weight_conversion) + output_state_dict = save_mutated_as_lora( + peft_config, path_initial_model_for_weight_conversion, output_state_dict, kwargs + ) + + # Before exporting the parameters we need to make sure all the tensors are contigious as saving + # non-contiguous parameters is not supported. Tensors can become non contigiuous + # if they are a transpose view of another tensor. This can happen + # during adapter tying or parameter sharing. + for k, v in output_state_dict.items(): + if not v.is_contiguous(): + output_state_dict[k] = v.contiguous() + + safe_save_file( + output_state_dict, + os.path.join(output_dir, SAFETENSORS_WEIGHTS_NAME), + metadata={"format": "pt"}, + ) + elif is_main_process: + if path_initial_model_for_weight_conversion is not None: + peft_config = copy.deepcopy(peft_config) + peft_config.init_lora_weights = True + peft_config.save_pretrained(path_initial_model_for_weight_conversion) + output_state_dict = save_mutated_as_lora( + peft_config, path_initial_model_for_weight_conversion, output_state_dict, kwargs + ) + torch.save(output_state_dict, os.path.join(output_dir, WEIGHTS_NAME)) + + # save the config and change the inference mode to `True` + if peft_config.base_model_name_or_path is None: + peft_config.base_model_name_or_path = ( + self.base_model.__dict__.get("name_or_path", None) + if peft_config.is_prompt_learning + else self.base_model.model.__dict__.get("name_or_path", None) + ) + inference_mode = peft_config.inference_mode + peft_config.inference_mode = True + + if peft_config.task_type is None: + # deal with auto mapping + base_model_class = self._get_base_model_class( + is_prompt_tuning=peft_config.is_prompt_learning, + ) + parent_library = base_model_class.__module__ + + auto_mapping_dict = { + "base_model_class": base_model_class.__name__, + "parent_library": parent_library, + } + else: + auto_mapping_dict = None + + if is_main_process: + if path_initial_model_for_weight_conversion is not None: + peft_config.init_lora_weights = True + peft_config.r *= 2 + if not peft_config.use_rslora: + peft_config.lora_alpha *= 2 + else: + # with rslora, we have scaling = alpha / sqrt(r), we thus adjust alpha to keep the same scaling + peft_config.lora_alpha *= 2**0.5 + + if peft_config.rank_pattern: + peft_config.rank_pattern = {key: 2 * val for key, val in peft_config.rank_pattern.items()} + if peft_config.alpha_pattern: + peft_config.alpha_pattern = {key: 2 * val for key, val in peft_config.alpha_pattern.items()} + + peft_config.save_pretrained(output_dir, auto_mapping_dict=auto_mapping_dict) + peft_config.inference_mode = inference_mode + + @classmethod + def from_pretrained( + cls, + model: torch.nn.Module, + model_id: Union[str, os.PathLike], + adapter_name: str = "default", + is_trainable: bool = False, + config: Optional[PeftConfig] = None, + autocast_adapter_dtype: bool = True, + ephemeral_gpu_offload: bool = False, + low_cpu_mem_usage: bool = False, + key_mapping: Optional[dict[str, str]] = None, + **kwargs: Any, + ) -> PeftModel: + r""" + Instantiate a PEFT model from a pretrained model and loaded PEFT weights. + + Note that the passed `model` may be modified inplace. + + Args: + model ([`torch.nn.Module`]): + The model to be adapted. For 🤗 Transformers models, the model should be initialized with the + [`~transformers.PreTrainedModel.from_pretrained`]. + model_id (`str` or `os.PathLike`): + The name of the PEFT configuration to use. Can be either: + - A string, the `model id` of a PEFT configuration hosted inside a model repo on the Hugging Face + Hub. + - A path to a directory containing a PEFT configuration file saved using the `save_pretrained` + method (`./my_peft_config_directory/`). + adapter_name (`str`, *optional*, defaults to `"default"`): + The name of the adapter to be loaded. This is useful for loading multiple adapters. + is_trainable (`bool`, *optional*, defaults to `False`): + Whether the adapter should be trainable or not. If `False`, the adapter will be frozen and can only be + used for inference. + config ([`~peft.PeftConfig`], *optional*): + The configuration object to use instead of an automatically loaded configuration. This configuration + object is mutually exclusive with `model_id` and `kwargs`. This is useful when configuration is already + loaded before calling `from_pretrained`. + autocast_adapter_dtype (`bool`, *optional*, defaults to `True`): + Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter + weights using float16 and bfloat16 to float32, as this is typically required for stable training, and + only affect select PEFT tuners. If set to `False`, the dtypes will stay the same as those of the + corresponding layer. + ephemeral_gpu_offload (`bool`, *optional*): + Whether to use ephemeral GPU offloading for partially loaded modules. Defaults to `False`. This is + useful when parts of the model and/or components (such as adapters) are kept in CPU memory until they + are needed. Rather than perform expensive operations on small data, the data is transferred to the GPU + on-demand, the operation(s) performed, and the results moved back to CPU memory. This brings a slight + momentary VRAM overhead but gives orders of magnitude speedup in certain cases. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device before loading the saved weights. Useful to speed up the + process. + torch_device (`str`, *optional*, defaults to None): + The device to load the adapter on. If `None`, the device will be inferred. + key_mapping (dict, *optional*, defaults to None) + Extra mapping of PEFT `state_dict` keys applied before loading the `state_dict`. When this mapping is + applied, the PEFT-specific `"base_model.model"` prefix is removed beforehand and the adapter name (e.g. + `"default"`) is not inserted yet. Only pass this argument if you know what you're doing. + kwargs: (`optional`): + Additional keyword arguments passed along to the specific PEFT configuration class. + + """ + from .auto import MODEL_TYPE_TO_PEFT_MODEL_MAPPING + from .tuners import XLoraConfig, XLoraModel + + # load the config + if config is None: + hf_kwargs = { + "subfolder": kwargs.get("subfolder", None), + "revision": kwargs.get("revision", None), + "cache_dir": kwargs.get("cache_dir", None), + "token": kwargs.get("token", None), + } + if use_auth_token := kwargs.get("use_auth_token", None): + hf_kwargs["use_auth_token"] = use_auth_token + config = PEFT_TYPE_TO_CONFIG_MAPPING[PeftConfig._get_peft_type(model_id, **hf_kwargs)].from_pretrained( + model_id, **kwargs + ) + elif isinstance(config, PeftConfig): + config.inference_mode = not is_trainable + else: + raise ValueError(f"The input config must be a PeftConfig, got {config.__class__}") + + # See discussion in https://github.com/huggingface/transformers/pull/38627 + # Some transformers models can have a _checkpoint_conversion_mapping dict that is used to map state_dicts + # stemming from updated model architectures so that they still correspond to the initial architecture. When + # loading a PEFT state_dict created with the initial architecture on a model with the new architecture, we need + # to map it too according to the same rules. Note that we skip prompt learning methods. This is because they + # don't have the "base_model.model." prefix, which we need to remove before mapping. Instead just using + # "base_model.". This could be fine, we could only remove "base_model.", However, the subsequent sub-module + # could also be called "model", resulting in what looks like "base_model.model.". To avoid this confusion, we + # skip prompt learning. Since it applies itself directly to the pre-trained model (unlike LoRA et al that target + # sub-modules), skipping should be fine. + if (key_mapping is None) and (not config.is_prompt_learning): + key_mapping = getattr(model, "_checkpoint_conversion_mapping", {}) + + # Runtime configuration, if supported + if hasattr(config, "runtime_config"): + config.runtime_config.ephemeral_gpu_offload = ephemeral_gpu_offload + else: + if ephemeral_gpu_offload: + warnings.warn("Ephemeral GPU offloading is not supported for this model. Ignoring.") + + if hasattr(model, "hf_device_map"): + weight_map = dict(named_module_tensors(model, recurse=True)) + + # recreate the offload_index for disk-offloaded modules: we need to know the location in storage of each weight + # before the offload hook is removed from the model + disk_modules = set() + index = None + for name, module in model.named_modules(): + if hasattr(module, "_hf_hook") and hasattr(module._hf_hook, "original_devices"): + if hasattr(module._hf_hook.weights_map, "dataset"): + index = module._hf_hook.weights_map.dataset.index + for key in module._hf_hook.original_devices.keys(): + if module._hf_hook.original_devices[key] == torch.device("meta"): + disk_modules.add(str(name) + "." + str(key)) + + if disk_modules and not kwargs.get("use_safetensors", True): + raise ValueError("Disk offloading currently only supported for safetensors") + + if index: + offload_index = { + p: { + "safetensors_file": index[p]["safetensors_file"], + "weight_name": p, + "dtype": str(weight_map[p].dtype).replace("torch.", ""), + } + for p in weight_map.keys() + if p in disk_modules + } + kwargs["offload_index"] = offload_index + + if (getattr(model, "hf_device_map", None) is not None) and len( + set(model.hf_device_map.values()).intersection({"cpu", "disk"}) + ) > 0: + remove_hook_from_submodules(model) + + if config.is_prompt_learning and is_trainable: + raise ValueError("Cannot set a prompt learning adapter to trainable when loading pretrained adapter.") + else: + config.inference_mode = not is_trainable + if isinstance(getattr(model, "base_model", None), XLoraModel): + if not isinstance(config, XLoraConfig): + raise TypeError(f"Expected 'XLoraConfig', got '{type(config)}' instead.") + if "adapters" in kwargs: + config.adapters = kwargs["adapters"] + else: + # If the path is on HF hub, then we get the adapter names to create a subfolders list which tells + # `load_adapter` where the adapters are. + if not os.path.exists(model_id): + s = HfFileSystem() + + # The names of the adapters which must be in folders + adapter_names = [ + file["name"][len(model_id) + 1 :] for file in s.ls(model_id) if file["type"] == "directory" + ] + # Prepare a dict of adapter paths, which really just point to the hf id; we will use the subfolders + adapter_paths = {} + for loaded_adapter_name in adapter_names: + adapter_paths[loaded_adapter_name] = os.path.join(model_id, model_id) + config.adapters = adapter_paths + config._subfolders = adapter_names + else: + if "adapters" not in kwargs: + raise ValueError("If model_id is a local path, then `adapters` must be passed in kwargs.") + + if config.task_type not in MODEL_TYPE_TO_PEFT_MODEL_MAPPING.keys(): + model = cls( + model, + config, + adapter_name, + autocast_adapter_dtype=autocast_adapter_dtype, + low_cpu_mem_usage=low_cpu_mem_usage, + ) + else: + model = MODEL_TYPE_TO_PEFT_MODEL_MAPPING[config.task_type]( + model, + config, + adapter_name, + autocast_adapter_dtype=autocast_adapter_dtype, + low_cpu_mem_usage=low_cpu_mem_usage, + ) + + load_result = model.load_adapter( + model_id, + adapter_name, + is_trainable=is_trainable, + autocast_adapter_dtype=autocast_adapter_dtype, + low_cpu_mem_usage=low_cpu_mem_usage, + key_mapping=key_mapping, + **kwargs, + ) + + # Filter out shared parameters that are duplicated at layer level: + # 1. Remove VB-LoRA vector bank, since it's a shared parameter set via the VBLoRAModel + # 2. Remove the prompt encoder, as it does not need to be part of the checkpoint + # 3. Remove TinyLoRA layer-level tinylora_v references (they share with model-level tinylora_v) + def is_expected_missing_key(k): + # TinyLoRA: layer-level tinylora_v is a reference to model-level, exclude from warning + return not ("vblora_vector_bank" in k or "prompt_encoder" in k or ".tinylora_v." in k) + + missing_keys = [k for k in load_result.missing_keys if is_expected_missing_key(k)] + if missing_keys: + # Let's warn here since (in contrast to load_adapter) we don't return the load result, so it could be quite + # difficult for users to even notice that something might have gone wrong here. As we filter out non PEFT + # keys from the missing keys, this gives no false positives. + + # careful: if the wording of the warning is changed, adjust the unit tests accordingly! + warn_message = f"Found missing adapter keys while loading the checkpoint: {missing_keys}." + + prefix = PEFT_TYPE_TO_PREFIX_MAPPING.get(config.peft_type) + if prefix and adapter_name in prefix: + warn_message = ( + f"Adapter name '{adapter_name}' should not be contained in the prefix '{prefix}'. " + "This could be the potential reason for missing adapter keys. " + ) + warn_message + + warnings.warn(warn_message) + + return model + + def _setup_prompt_encoder(self, adapter_name: str): + config = self.peft_config[adapter_name] + if not hasattr(self, "prompt_encoder"): + self.prompt_encoder = torch.nn.ModuleDict({}) + self.prompt_tokens = {} + transformer_backbone = None + for name, module in self.base_model.named_children(): + for param in module.parameters(): + param.requires_grad = False + if isinstance(module, PreTrainedModel): + # Make sure to freeze Tranformers model + if transformer_backbone is None: + transformer_backbone = module + self.transformer_backbone_name = name + if transformer_backbone is None: + transformer_backbone = self.base_model + + if config.num_transformer_submodules is None: + config.num_transformer_submodules = 2 if config.task_type == TaskType.SEQ_2_SEQ_LM else 1 + + # determine the word embeddings + word_embeddings = None + try: + # First try to find the word embeddings based on the module name, this should work for models like Bert, + # Roberta, Deberta, etc. + word_embeddings = self.base_model.get_submodule("embeddings.word_embeddings") + except AttributeError: + pass + + if word_embeddings is None: + # Word embeddings could not be determined. Next try to guess them by checking which parameter has the size + # of the vocab. + for named_param, value in list(transformer_backbone.named_parameters()): + # for ZeRO-3, the tensor is sharded across accelerators and deepspeed modifies it to a tensor with shape + # [0] the actual unsharded shape is stored in "ds_shape" attribute special handling is needed in case + # the model is initialized in deepspeed.zero.Init() context or HfDeepSpeedConfig has been called before + # For reference refer to issue: https://github.com/huggingface/peft/issues/996 + deepspeed_distributed_tensor_shape = getattr(value, "ds_shape", None) + + # Handle VLM case with separate text and vision configs + if hasattr(self.base_model.config, "get_text_config"): + vocab_size = self.base_model.config.get_text_config().vocab_size + # below: for older transformers versions before get_text_config was added + elif "text_config" in self.base_model.config: + vocab_size = self.base_model.config.text_config.vocab_size + else: + vocab_size = self.base_model.config.vocab_size + + if value.shape[0] == vocab_size or ( + deepspeed_distributed_tensor_shape is not None + and deepspeed_distributed_tensor_shape[0] == vocab_size + ): + word_embeddings = transformer_backbone.get_submodule(named_param.replace(".weight", "")) + break + + self.word_embeddings = word_embeddings + model_cls = PEFT_TYPE_TO_TUNER_MAPPING[config.peft_type] + + if config.peft_type in (PeftType.PROMPT_TUNING, PeftType.MULTITASK_PROMPT_TUNING, PeftType.CPT): + prompt_encoder = model_cls(config, self.word_embeddings) + elif config.peft_type == PeftType.P_TUNING: + prompt_encoder = model_cls(config) + elif config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + # prefix tuning now uses Cache but that won't work with gradient checkpointing + if any(getattr(module, "gradient_checkpointing", False) for module in self.get_base_model().modules()): + raise ValueError(f"{config.peft_type.value} does not work with gradient checkpointing.") + prompt_encoder = model_cls(config) + else: + raise ValueError("Not supported") + + prompt_encoder = prompt_encoder.to(self.device) + self.prompt_encoder.update(torch.nn.ModuleDict({adapter_name: prompt_encoder})) + self.prompt_tokens[adapter_name] = torch.arange( + config.num_virtual_tokens * config.num_transformer_submodules + ).long() + + def prepare_model_for_gradient_checkpointing(self, model: PreTrainedModel): + r""" + Prepares the model for gradient checkpointing if necessary + """ + self._prepare_model_for_gradient_checkpointing(model) + + def _prepare_model_for_gradient_checkpointing(self, model: PreTrainedModel): + if not ( + getattr(model, "is_loaded_in_8bit", False) + or getattr(model, "is_loaded_in_4bit", False) + or getattr(model, "is_quantized", False) + ): + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + elif hasattr(model, "get_input_embeddings"): + + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + return model + + def get_prompt_embedding_to_save(self, adapter_name: str) -> torch.Tensor: + """ + Returns the prompt embedding to save when saving the model. Only applicable when using a prompt learning + method. + """ + prompt_encoder = self.prompt_encoder[adapter_name] + prompt_tokens = ( + self.prompt_tokens[adapter_name].unsqueeze(0).expand(1, -1).to(prompt_encoder.embedding.weight.device) + ) + peft_type = self.peft_config[adapter_name].peft_type + if self.peft_config[adapter_name].peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + prompt_tokens = prompt_tokens[:, : self.peft_config[adapter_name].num_virtual_tokens] + + if self.peft_config[adapter_name].peft_type == PeftType.MULTITASK_PROMPT_TUNING: + prompt_embedding_cls = PEFT_TYPE_TO_TUNER_MAPPING[peft_type] + prompt_embeddings = super(prompt_embedding_cls, prompt_encoder).forward(prompt_tokens) + else: + prompt_embeddings = prompt_encoder(prompt_tokens) + + return prompt_embeddings[0].detach().cpu() + + def get_prompt( + self, batch_size: int, task_ids: Optional[torch.Tensor] = None, max_cache_len: Optional[int] = None + ) -> torch.Tensor: + """ + Returns the virtual prompts to use for Peft. Only applicable when using a prompt learning method. + """ + peft_config = self.active_peft_config + prompt_encoder = self.prompt_encoder[self.active_adapter] + prompt_tokens = ( + self.prompt_tokens[self.active_adapter] + .unsqueeze(0) + .expand(batch_size, -1) + .to(prompt_encoder.embedding.weight.device) + ) + if peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + prompt_tokens = prompt_tokens[:, : peft_config.num_virtual_tokens] + if peft_config.inference_mode: + past_key_values = prompt_encoder.embedding.weight.repeat(batch_size, 1, 1) + else: + past_key_values = prompt_encoder(prompt_tokens) + if self.base_model_torch_dtype is not None: + past_key_values = past_key_values.to(self.base_model_torch_dtype) + past_key_values = past_key_values.view( + batch_size, + peft_config.num_virtual_tokens, + peft_config.num_layers * 2, + peft_config.num_attention_heads, + peft_config.token_dim // peft_config.num_attention_heads, + ) + if peft_config.num_transformer_submodules == 2: + past_key_values = torch.cat([past_key_values, past_key_values], dim=2) + + # Transpose: 2 x [num_layers, batch_size, num_heads, num_virtual_tokens, head_dim] + past_key_values = past_key_values.permute([2, 0, 3, 1, 4]).split( + peft_config.num_transformer_submodules * 2 + ) + + base_model = self.get_base_model() + model_config = getattr(base_model, "config", None) + model_type = getattr(model_config, "model_type", "") + if TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING.get(self.config.model_type, None) is not None: + post_process_fn = TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING[self.config.model_type] + past_key_values = post_process_fn(past_key_values) + elif ("gemma2" in model_type) or ("gemma3_text" in model_type) or ("gemma4" in model_type): + # TODO: remove this logic once transformers < 4.56 is dropped + transformers_lt_4_56 = packaging.version.parse(transformers.__version__) < packaging.version.parse( + "4.56.0.dev0" + ) + # Gemma2 and Gemma3 only support HybridCache (which does not have the from_legacy_cache method) + if transformers_lt_4_56 and ((max_cache_len is None) or (max_cache_len == -1)): + raise ValueError( + "max_cache_len is missing but it should have been passed. Something went wrong, please open an " + "issue on GitHub with a reproducer: https://github.com/huggingface/peft/issues" + ) + base_config = base_model.config + if hasattr(base_config, "get_text_config"): + base_config = base_config.get_text_config() + if transformers_lt_4_56: + # HybridCache is deprecated, and will be removed in 4.60.0 + # see https://github.com/huggingface/transformers/pull/40276 + from transformers import HybridCache + + new_cache = HybridCache( + config=base_config, + max_batch_size=batch_size, + max_cache_len=max_cache_len, + dtype=past_key_values[0].dtype, + device=past_key_values[0].device, + ) + else: + # transformers 4.56+ uses DynamicCache for gemma + new_cache = DynamicCache(config=base_config) + cache_position = torch.arange(peft_config.num_virtual_tokens, device=past_key_values[0].device) + # Layers from `num_hidden_layers - num_kv_shared_layers` onward share KV with an earlier layer (no own + # k_proj/v_proj) and never call `cache.update`; the prefix reaches them transitively via the source + # layer. + num_kv_shared_layers = getattr(base_config, "num_kv_shared_layers", 0) + first_kv_shared_layer_idx = ( + getattr(base_config, "num_hidden_layers", peft_config.num_layers) - num_kv_shared_layers + ) + injected_layers: list[int] = [] + skipped_layers: list[int] = [] + # past_key_values is a tuple of `num_layers` per-layer tensors each shaped + # [2, batch, num_heads, num_virtual_tokens, head_dim], where dim 0 stacks K and V. + for layer_idx, layer_past_key_values in enumerate(past_key_values): + if num_kv_shared_layers > 0 and layer_idx >= first_kv_shared_layer_idx: + skipped_layers.append(layer_idx) + continue + key_states, value_states = layer_past_key_values + shape_or_none = _get_layer_kv_target_shape(base_config, layer_idx) + if shape_or_none is not None: # e.g. gemma 4 + n_h, d = shape_or_none + # Provisioned shape: [batch, num_heads, num_virtual_tokens, head_dim]. If a layer's KV is wider + # than what we provisioned, we cannot slice up; skip rather than silently truncating to a shape + # the model won't accept. + if n_h > key_states.shape[1] or d > key_states.shape[3]: + skipped_layers.append(layer_idx) + continue + key_states = key_states[:, :n_h, :, :d] + value_states = value_states[:, :n_h, :, :d] + new_cache.update( + key_states, value_states, layer_idx, cache_kwargs={"cache_position": cache_position} + ) + injected_layers.append(layer_idx) + past_key_values = new_cache + + if not injected_layers: + # raise if no layer was matched; similar logic as in target_modules not matching any layer + raise ValueError( + "Prefix tuning skipped every layer because no layer's KV shape matched the provisioned prefix " + f"(num_attention_heads={peft_config.num_attention_heads}, " + f"head_dim={peft_config.token_dim // peft_config.num_attention_heads}). Override `token_dim` " + "and `num_attention_heads` in `PrefixTuningConfig` to match a layer that should receive the " + "prefix." + ) + if skipped_layers: + warnings.warn( + f"Prefix tuning injected into layers {injected_layers}; skipped {skipped_layers} due to KV " + "shape mismatch or shared-KV layers." + ) + + elif peft_config.num_transformer_submodules == 1: + # Dont' apply this to encoder-decoder models and not to models requiring special processing. + # TODO: remove from_legacy_cache once transformers < 4.56 is dropped + transformers_lt_4_56 = packaging.version.parse(transformers.__version__) < packaging.version.parse( + "4.56.0.dev0" + ) + if transformers_lt_4_56: + past_key_values = DynamicCache.from_legacy_cache(past_key_values) + else: + past_key_values = DynamicCache(past_key_values) + + elif (peft_config.num_transformer_submodules == 2) and getattr( + self.base_model, "_supports_cache_class", True + ): + # Dont' apply this to encoder-decoder models that don't support new Cache format yet + # If we don't apply this, prefix-tuning fails to update cross-attn cache + # TODO: remove check for _supports_cache_class once transformers 4.53 is no longer supported + # TODO: remove from_legacy_cache once transformers < 4.56 is dropped + transformers_lt_4_56 = packaging.version.parse(transformers.__version__) < packaging.version.parse( + "4.56.0.dev0" + ) + if transformers_lt_4_56: + past_key_values = EncoderDecoderCache.from_legacy_cache(past_key_values) + else: + past_key_values = EncoderDecoderCache(past_key_values) + + past_key_values.cross_attention_cache = DynamicCache() + # invalidate the cross attention cache, since we add virtual tokens to the encoder + for key in past_key_values.is_updated.keys(): + past_key_values.is_updated[key] = False + map_cache_to_layer_device_map(self.get_base_model(), past_key_values) # no-op if not a Cache instance + return past_key_values + else: + if peft_config.peft_type == PeftType.MULTITASK_PROMPT_TUNING: + prompts = prompt_encoder(prompt_tokens, task_ids) + else: + if peft_config.inference_mode: + prompts = prompt_encoder.embedding.weight + else: + # Take only one prompt token sample and expand the output instead of expanding the input, see: + # https://github.com/huggingface/peft/issues/2043#issuecomment-2321522577 + prompt_tokens = prompt_tokens[:1] + prompts = prompt_encoder(prompt_tokens) + prompts = prompts.repeat(batch_size, 1, 1) + return prompts + + def get_nb_trainable_parameters(self) -> tuple[int, int]: + r""" + Returns the number of trainable parameters and the number of all parameters in the model. + """ + trainable_params = 0 + all_param = 0 + for _, param in self.named_parameters(): + num_params = param.numel() + # if using DS Zero 3 and the weights are initialized empty + if num_params == 0 and hasattr(param, "ds_numel"): + num_params = param.ds_numel + + # Due to the design of 4bit linear layers from bitsandbytes + # one needs to multiply the number of parameters by 2 to get + # the correct number of parameters + if param.__class__.__name__ == "Params4bit": + if hasattr(param, "element_size"): + num_bytes = param.element_size() + elif not hasattr(param, "quant_storage"): + num_bytes = 1 + else: + num_bytes = param.quant_storage.itemsize + num_params = num_params * 2 * num_bytes + + all_param += num_params + if param.requires_grad: + trainable_params += num_params + + return trainable_params, all_param + + def print_trainable_parameters(self) -> None: + """ + Prints the number of trainable parameters in the model. + + Note: print_trainable_parameters() uses get_nb_trainable_parameters() which is different from + num_parameters(only_trainable=True) from huggingface/transformers. get_nb_trainable_parameters() returns + (trainable parameters, all parameters) of the Peft Model which includes modified backbone transformer model. + For techniques like LoRA, the backbone transformer model is modified in place with LoRA modules. However, for + prompt tuning, the backbone transformer model is unmodified. num_parameters(only_trainable=True) returns number + of trainable parameters of the backbone transformer model which can be different. + """ + trainable_params, all_param = self.get_nb_trainable_parameters() + + print( + f"trainable params: {trainable_params:,d} || all params: {all_param:,d} || trainable%: {100 * trainable_params / all_param:.4f}" + ) + + def __getattr__(self, name: str): + """Forward missing attributes to the wrapped module.""" + try: + return super().__getattr__(name) # defer to nn.Module's logic + except AttributeError: + if name == "base_model": # see #1892: prevent infinite recursion if class is not initialized + raise + return getattr(self.base_model, name) + + @contextmanager + def _enable_peft_forward_hooks(self, *args, **kwargs): + # If the base model has a method called _enable_peft_forward_hooks, it is invoked as a context. Otherwise, this + # runs without any changes + if hasattr(self.base_model, "_enable_peft_forward_hooks") and self.has_active_enabled_adapter: + with self.base_model._enable_peft_forward_hooks(*args, **kwargs): + yield + return + else: + # nothing to enable + yield + return + + def forward(self, *args: Any, **kwargs: Any): + """ + Forward pass of the model. + """ + with self._enable_peft_forward_hooks(*args, **kwargs): + kwargs = {k: v for k, v in kwargs.items() if k not in self.special_peft_forward_args} + return self.get_base_model()(*args, **kwargs) + + def generate(self, *args, **kwargs): + with self._enable_peft_forward_hooks(*args, **kwargs): + kwargs = {k: v for k, v in kwargs.items() if k not in self.special_peft_forward_args} + return self.get_base_model().generate(*args, **kwargs) + + def _get_base_model_class(self, is_prompt_tuning=False): + """ + Returns the base model class. + """ + if not is_prompt_tuning: + return self.base_model.model.__class__ + return self.base_model.__class__ + + @contextmanager + def disable_adapter(self): + """ + Context manager that disables the adapter module. Use this to run inference on the base model. + + Example: + + ```py + >>> with model.disable_adapter(): + ... model(inputs) + ``` + """ + if self.peft_config[self.active_adapter].is_prompt_learning: + try: + # TODO: consider replacing this patching of methods with a more robust mechanism: setting a flag and + # letting the underlying methods deal with it, same as how LoRA does it. + old_forward = self.forward + self.forward = self.base_model.forward + old_prepare_inputs_for_generation = self.prepare_inputs_for_generation + self.prepare_inputs_for_generation = self.base_model.prepare_inputs_for_generation + self._adapters_disabled = True + yield + finally: + self.forward = old_forward + self.prepare_inputs_for_generation = old_prepare_inputs_for_generation + self._adapters_disabled = False + + elif self.peft_config[self.active_adapter].is_adaption_prompt: + try: + self.base_model.disable_adapter_layers() + self._adapters_disabled = True + yield + finally: + self.base_model.enable_adapter_layers() + self._adapters_disabled = False + + else: # LoRA, LoHa, etc. + model_status = self.get_model_status() + if model_status.enabled == "irregular": + warnings.warn( + "The model contains some adapter layers that are enabled and others that are disabled. " + "This is most likely unintentional. After exiting the disable_adapter context, all adapters " + "will be enabled" + ) + try: + self.base_model.disable_adapter_layers() + self._adapters_disabled = True + yield + finally: + if model_status.enabled is not False: + # model_status.enabled is `True` or `"irregular"` + self.base_model.enable_adapter_layers() + self._adapters_disabled = False + + def get_base_model(self) -> torch.nn.Module: + """ + Returns the base model. + """ + return self.base_model if self.active_peft_config.is_prompt_learning else self.base_model.model + + def add_adapter( + self, + adapter_name: str, + peft_config: PeftConfig, + low_cpu_mem_usage: bool = False, + autocast_adapter_dtype: bool = True, + ) -> None: + """ + Add an adapter to the model based on the passed configuration. + + This adapter is not trained. To load a trained adapter, check out [`PeftModel.load_adapter`]. + + The name for the new adapter should be unique. + + The new adapter is not automatically set as the active adapter. Use [`PeftModel.set_adapter`] to set the active + adapter. + + Args: + adapter_name (`str`): + The name of the adapter to be added. + peft_config ([`PeftConfig`]): + The configuration of the adapter to be added. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the process when loading saved + adapters. Don't use this option when creating a new PEFT adapter for training. + autocast_adapter_dtype (`bool`, *optional*, defaults to `True`): + Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter + weights using float16 and bfloat16 to float32, as this is typically required for stable training, and + only affect select PEFT tuners. If set to `False`, the dtypes will stay the same as those of the + corresponding layer. + """ + prefix = PEFT_TYPE_TO_PREFIX_MAPPING.get(peft_config.peft_type) + if prefix and adapter_name in prefix: + warnings.warn( + f"Adapter name '{adapter_name}' should not be contained in the prefix '{prefix}'. " + "This may lead to reinitialization of the adapter weights during loading." + ) + + if peft_config.peft_type != self.peft_type: + raise ValueError( + f"Cannot combine adapters with different peft types. " + f"Found {self.peft_type} and {peft_config.peft_type}." + ) + + try: + if peft_config.is_prompt_learning: + self.peft_config[adapter_name] = peft_config + peft_config = _prepare_prompt_learning_config(peft_config, self.config) + self._setup_prompt_encoder(adapter_name) + set_additional_trainable_modules( + model=self.base_model, + peft_config=peft_config, + model_config=BaseTuner.get_model_config(self), + adapter_name=adapter_name, + ) + elif peft_config.is_adaption_prompt: + self.base_model.add_adapter(adapter_name, peft_config) + set_additional_trainable_modules( + model=self.base_model, + peft_config=peft_config, + model_config=BaseTuner.get_model_config(self), + adapter_name=adapter_name, + ) + else: + self.peft_config[adapter_name] = peft_config + self.base_model.inject_adapter( + self.base_model.model, adapter_name, low_cpu_mem_usage=low_cpu_mem_usage + ) + except Exception: # something went wrong, roll back + if adapter_name in self.peft_config: + del self.peft_config[adapter_name] + raise + + if hasattr(self.base_model, "_cast_adapter_dtype"): + self.base_model._cast_adapter_dtype( + adapter_name=adapter_name, autocast_adapter_dtype=autocast_adapter_dtype + ) + + def delete_adapter(self, adapter_name: str) -> None: + """ + Deletes an existing adapter. + + Args: + adapter_name (str): Name of the adapter to be deleted. + """ + if adapter_name not in self.peft_config: + raise ValueError(f"Adapter {adapter_name} does not exist") + + self.base_model.delete_adapter(adapter_name=adapter_name) + new_active_adapters = self.active_adapters + num_adapters = len(new_active_adapters) + # Note: PeftModel assumes that there is exactly one active adapter, so we should theoretically raise if + # num_adapters != 1. However, we have allowed this in the past (maybe inadvertently), so we let it slip and + # don't introduce a backwards incompatibility by raising an error. + if num_adapters == 1: + self.active_adapter = new_active_adapters[0] + + @property + def modules_to_save(self) -> Optional[set[str]]: + modules: set[str] = set() + for config in self.peft_config.values(): + if getattr(config, "modules_to_save", None) is not None: + # modules_to_save can only be a sequence of str, not a str + modules.update(config.modules_to_save) + + if not modules: + # for backwards compatibility, as modules_to_save was initialized as None + return None + return modules + + def get_layer_status(self) -> list[TunerLayerStatus]: + """Get the status of each adapter layer in the model. + + This method returns a list of `TunerLayerStatus` dataclass instances, each of which contains the following + attributes: + + - `name` (`str`): + The name of the adapter layer, e.g. `model.encoder.block.0.layer.0.SelfAttention.q`. + - `module_type` (`str`): + The type of the adapter layer, e.g. `lora.Linear`. + - `enabled` (`bool`): + Whether the adapter layer is enabled. + - `active_adapters` (`list[str]`): + The names of the active adapters, if any, e.g. `["default"]`. + - `merged_adapters` (`list[str]`): + The names of the merged adapters, if any, e.g. `["default"]`. + - `available_adapters` (`list[str]`): + The names of the available adapters, e.g. `["default"]`. + - `quantization_backend` (`str` or `None`): + The name of the quantization backend, e.g. `"bnb 4bit"`, or `None` if not quantized. + + Args: + model ([`~PeftModel`]): + The model to get the adapter layer status from. + + Returns: + list[`peft.peft_model.TunerLayerStatus`]: + A list of dataclasses, each containing the status of the corresponding adapter layer. + + """ + return get_layer_status(self) + + def get_model_status(self) -> TunerModelStatus: + """Get the status of tuners of the model. + + This method returns a `TunerModelStatus` dataclass instance, which contains the following attributes: + + - `base_model_type` (`str`): + The type of the base model, e.g. `T5Model`. + - `adapter_model_type` (`str`): + The type of the adapter model, e.g. `LoraModel`. + - `peft_types` (`dict[str, str]`): + The mapping of adapter name to adapter type, e.g. `{"default": "LORA"}`. + - `trainable_params` (`int`): + The number of trainable parameters in the model. + - `total_params` (`int`): + The total number of parameters in the model. + - `num_adapter_layers` (`int`): + The number of adapter layers in the model. + - `enabled` (`bool`, `Literal["irregular"]`): + Whether all adapter layers are enabled. If some are enabled and some are not, this will be `"irregular"`. + This means that your model is in an inconsistent state and might not work as expected. + - `active_adapters` (`list[str]`, `Literal["irregular"]`): + The names of the active adapters. If the active adapters are not consistent across all layers, this will be + `"irregular"`, which means that your model is in an inconsistent state and might not work as expected. + - `merged_adapters` (`list[str]`, `Literal["irregular"]`): + The names of the merged adapters. If the merged adapters are not consistent across all layers, this will be + `"irregular"`, which means that your model is in an inconsistent state and might not work as expected. + - `available_adapters` (`list[str]`): + The names of the available adapters, e.g. `["default"]`. + - `quantization_backend` (`str`, `None`, `Literal["irregular"]`): + The name of the quantization backend, e.g. `"bnb 4bit"`, or `None` if not quantized. If the backend is not + consistent across all layers, this will be `"irregular"`. + + Args: + model ([`~PeftModel`]): + The model to get the adapter layer status from. + + Returns: + `peft.peft_model.TunerModelStatus`: + A dataclass containing the status of the model. + + """ + return get_model_status(self) + + @classmethod + def _split_kwargs(cls, kwargs: dict[str, Any]): + _kwargs_not_in_hf_hub_download_signature = ("use_auth_token",) + hf_hub_download_kwargs = {} + other_kwargs = {} + + for key, value in kwargs.items(): + if key in inspect.signature(hf_hub_download).parameters or key in _kwargs_not_in_hf_hub_download_signature: + hf_hub_download_kwargs[key] = value + else: + other_kwargs[key] = value + + return hf_hub_download_kwargs, other_kwargs + + def _update_offload(self, offload_index: dict[str, dict[str, str]], adapters_weights: dict[str, torch.tensor]): + """ + Update the offload_index and safetensors files for loading and mergine PeftModels with disk-offloaded modules. + + Args: + offload_index (Dict[str: str]): + Dictionary of disk-offloaded modules with their metadata and safetensors filenames + adapters_weights (Dict[str: torch.tensor]): + Dictionary of Peft adapter module names and weights + """ + + if not offload_index: + return offload_index + + prefix = "base_model.model." + # rename offload index weight and model names + adapter_names = list(self.peft_config.keys()) + for adapter_name in adapter_names: + keys = list(offload_index.keys()) + block_id = keys[0].split(".")[0] + "." # for writing safetensors key, + + # replace original offload index keys with PeftModel keys + for key in keys: + suffix_pos = key.rfind(".") + extended_prefix = prefix + key[:suffix_pos] + module = dict(self.named_modules())[extended_prefix] + if isinstance(module, BaseTunerLayer): + new_key = prefix + key[:suffix_pos] + ".base_layer" + key[suffix_pos:] + else: + new_key = prefix + key + offload_index[key]["weight_name"] = new_key + offload_index[new_key] = offload_index[key] + del offload_index[key] + + files_seen = set() + # rename safetensors for dispatch + for new_key in list(offload_index.keys()): + fname = offload_index[new_key]["safetensors_file"] + + # make a new file name + new_fname_list = list(fname.split(os.sep)) + for i, name in enumerate(new_fname_list): + if "--" in name: + new_fname_list[i] += "-peft" + break + new_fname = os.path.join(*new_fname_list) + + if fname in files_seen: + continue + safe_dict = {} + with safe_open(fname, framework="pt") as f: + for safe_key in f.keys(): + safe_tensor = f.get_tensor(safe_key) + metadata = f.metadata() + suffix_pos = safe_key.rfind(".") + extended_prefix = prefix + block_id + safe_key[:suffix_pos] + safe_module = dict(self.named_modules())[extended_prefix] + if isinstance(safe_module, BaseTunerLayer): + final_key = extended_prefix + ".base_layer" + safe_key[suffix_pos:] + lora_dict = {key: val for key, val in adapters_weights.items() if extended_prefix in key} + + # add LoRA keys and values to disk offload + for lora_key, lora_val in lora_dict.items(): + divide = lora_key.rfind(".") + new_key = lora_key[:divide] + f".{adapter_name}" + lora_key[divide:] + safe_dict[new_key] = lora_val + else: + final_key = prefix + block_id + safe_key + safe_dict[final_key] = safe_tensor + files_seen.add(new_fname) + + # avoid overwriting original safetensors + for key in safe_dict.keys(): + offload_index[key] = {"safetensors_file": new_fname, "weight_name": key} + + base_name = os.path.dirname(new_fname) + if not os.path.exists(base_name): + os.makedirs(base_name) + safe_save_file(safe_dict, new_fname, metadata=metadata) + + def _check_new_adapter_config(self, peft_config: PeftConfig, is_trainable: bool) -> None: + """Perform checks on newly added PEFT configs to ensure integrity.""" + if peft_config.is_prompt_learning and is_trainable: + raise ValueError("Cannot set a prompt learning adapter to trainable when loading pretrained adapter.") + + # Since PiSSA/CorDA/OLoRA modifies the base weights, it should not be combined with other adapters. + all_configs = [peft_config] + list(self.peft_config.values()) + if len(all_configs) > 1: + if any(getattr(config, "init_lora_weights", None) == "pissa" for config in all_configs): + msg = ( + "PiSSA changes the base weights of the model and should thus not be used with other adapters. " + "Consider converting the PiSSA adapter into a normal LoRA adapter: " + "https://github.com/huggingface/peft/tree/main/examples/pissa_finetuning#convert-pissa-to-lora" + ) + warnings.warn(msg) + elif any(getattr(config, "init_lora_weights", None) == "corda" for config in all_configs): + msg = ( + "CorDA changes the base weights of the model and should thus not be used with other adapters. " + "Consider converting the CorDA adapter into a normal LoRA adapter: " + "https://github.com/huggingface/peft/tree/main/examples/corda_finetuning#convert-corda-to-lora" + ) + warnings.warn(msg) + elif any(getattr(config, "init_lora_weights", None) == "olora" for config in all_configs): + msg = ( + "OLoRA changes the base weights of the model and should thus not be used with other adapters. " + "Consider converting the OLoRA adapter into a normal LoRA adapter: " + "https://github.com/huggingface/peft/tree/main/examples/olora_finetuning#olora-and-lora" + ) + warnings.warn(msg) + + def load_adapter( + self, + model_id: Union[str, os.PathLike], + adapter_name: str, + is_trainable: bool = False, + torch_device: Optional[str] = None, + autocast_adapter_dtype: bool = True, + ephemeral_gpu_offload: bool = False, + low_cpu_mem_usage: bool = False, + key_mapping: Optional[dict[str, str]] = None, + **kwargs: Any, + ): + """ + Load a trained adapter into the model. + + The name for the new adapter should be unique. + + The new adapter is not automatically set as the active adapter. Use [`PeftModel.set_adapter`] to set the active + adapter. + + Args: + model_id (`str` or `os.PathLike`): + The name of the PEFT configuration to use. Can be either: + - A string, the `model id` of a PEFT configuration hosted inside a model repo on the Hugging Face + Hub. + - A path to a directory containing a PEFT configuration file saved using the `save_pretrained` + method (`./my_peft_config_directory/`). + adapter_name (`str`): + The name of the adapter to be added. + is_trainable (`bool`, *optional*, defaults to `False`): + Whether the adapter should be trainable or not. If `False`, the adapter will be frozen and can only be + used for inference. + torch_device (`str`, *optional*, defaults to None): + The device to load the adapter on. If `None`, the device will be inferred. + autocast_adapter_dtype (`bool`, *optional*, defaults to `True`): + Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter + weights using float16 and bfloat16 to float32, as this is typically required for stable training, and + only affect select PEFT tuners. If set to `False`, the dtypes will stay the same as those of the + corresponding layer. + ephemeral_gpu_offload (`bool`, *optional*, defaults to `False`): + Whether to use ephemeral GPU offloading for partially loaded modules. Defaults to `False`. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device before loading the saved weights. Useful to speed up the + process. + key_mapping (dict, *optional*, defaults to None) + Extra mapping of PEFT `state_dict` keys applied before loading the `state_dict`. When this mapping is + applied, the PEFT-specific `"base_model.model"` prefix is removed beforehand and the adapter name (e.g. + `"default"`) is not inserted yet. Only pass this argument if you know what you're doing. + kwargs: (`optional`): + Additional arguments to modify the way the adapter is loaded, e.g. the token for Hugging Face Hub. + """ + from .mapping import PEFT_TYPE_TO_CONFIG_MAPPING + + hf_hub_download_kwargs, kwargs = self._split_kwargs(kwargs) + if torch_device is None: + torch_device = infer_device() + + if adapter_name not in self.peft_config: + # load the config + peft_config = PEFT_TYPE_TO_CONFIG_MAPPING[ + PeftConfig._get_peft_type( + model_id, + **hf_hub_download_kwargs, + ) + ].from_pretrained( + model_id, + ephemeral_gpu_offload=ephemeral_gpu_offload, + **hf_hub_download_kwargs, + ) + self._check_new_adapter_config(peft_config, is_trainable=is_trainable) + peft_config.inference_mode = not is_trainable + self.add_adapter( + adapter_name, + peft_config, + low_cpu_mem_usage=low_cpu_mem_usage, + autocast_adapter_dtype=autocast_adapter_dtype, + ) + + adapters_weights = load_peft_weights( + model_id, device=torch_device, key_mapping=key_mapping, **hf_hub_download_kwargs + ) + + # load the weights into the model + ignore_mismatched_sizes = kwargs.get("ignore_mismatched_sizes", False) + load_result = set_peft_model_state_dict( + self, + adapters_weights, + adapter_name=adapter_name, + ignore_mismatched_sizes=ignore_mismatched_sizes, + low_cpu_mem_usage=low_cpu_mem_usage, + ) + + tuner = self.peft_config[adapter_name].peft_type + tuner_prefix = PEFT_TYPE_TO_PREFIX_MAPPING.get(tuner, "") + adapter_missing_keys = [] + + # Filter missing keys specific to the current adapter and tuner prefix. + for key in load_result.missing_keys: + if tuner_prefix in key and adapter_name in key: + # TinyLoRA: layer-level tinylora_v is a reference to model-level, skip it + if ".tinylora_v." in key: + continue + adapter_missing_keys.append(key) + + load_result.missing_keys.clear() + load_result.missing_keys.extend(adapter_missing_keys) + + if ( + (getattr(self, "hf_device_map", None) is not None) + and (len(set(self.hf_device_map.values()).intersection({"cpu", "disk"})) > 0) + and len(self.peft_config) == 1 + ): + device_map = kwargs.get("device_map", "auto") + max_memory = kwargs.get("max_memory", None) + offload_folder = kwargs.get("offload_folder", None) + offload_dir = kwargs.get("offload_dir", None) + offload_index = kwargs.get("offload_index", None) + + if offload_dir is not None and offload_folder is not None: + # see https://github.com/huggingface/peft/issues/2541 + raise ValueError("Cannot use `offload_folder` when `offload_dir` is specified.") + elif offload_dir is None: + # to keep backwards compatibility + offload_dir = offload_folder + + dispatch_model_kwargs = {} + # Safety checker for previous `accelerate` versions + # `offload_index` was introduced in https://github.com/huggingface/accelerate/pull/873/ + if "offload_index" in inspect.signature(dispatch_model).parameters: + dispatch_model_kwargs["offload_index"] = offload_index + + no_split_module_classes = self._no_split_modules + if isinstance(no_split_module_classes, set): + no_split_module_classes = list(no_split_module_classes) + + if device_map != "sequential": + max_memory = get_balanced_memory( + self, + max_memory=max_memory, + no_split_module_classes=no_split_module_classes, + low_zero=(device_map == "balanced_low_0"), + ) + + if isinstance(device_map, str): + device_map = infer_auto_device_map( + self, max_memory=max_memory, no_split_module_classes=no_split_module_classes + ) + + self._update_offload(offload_index, adapters_weights) + dispatch_model_kwargs["offload_index"] = offload_index + + dispatch_model( + self, + device_map=device_map, + offload_dir=offload_dir, + **dispatch_model_kwargs, + ) + + hook = AlignDevicesHook(io_same_device=True) + if self.peft_config[adapter_name].is_prompt_learning: + remove_hook_from_submodules(self.prompt_encoder) + add_hook_to_module(self.get_base_model(), hook) + + if hasattr(self.base_model, "_cast_adapter_dtype"): + self.base_model._cast_adapter_dtype( + adapter_name=adapter_name, autocast_adapter_dtype=autocast_adapter_dtype + ) + + # Set model in evaluation mode to deactivate Dropout modules by default + if not is_trainable: + self.eval() + return load_result + + def set_adapter(self, adapter_name: str, inference_mode: bool = False) -> None: + """ + Sets the active adapter. + + Only one adapter can be active at a time. + + Additionally, this function will set the specified adapter to trainable (i.e., requires_grad=True) unless + inference_mode is True. + + Args: + adapter_name (`str`): + The name of the adapter to be set as active. The adapter must be loaded first. + inference_mode (`bool`, optional): + Whether the activated adapter should be frozen (i.e. `requires_grad=False`). Default is False. + """ + if adapter_name not in self.peft_config: + raise ValueError(f"Adapter {adapter_name} not found.") + self.active_adapter = adapter_name + if not self.peft_config[adapter_name].is_prompt_learning: + # _set_adapter does not need to be called, since it's called through the BaseTuner class. + self.base_model.set_adapter(adapter_name, inference_mode=inference_mode) + else: + # handle auxiliary modules + _set_adapter(self, adapter_name, inference_mode=inference_mode) + + def set_requires_grad(self, adapter_names: str | Sequence[str], requires_grad: bool = True) -> None: + """ + Enable or disable gradients on the given adapter(s). + + Note: Not supported for prompt learning methods like prompt tuning. + + Args: + adapter_name (`str` or `Sequence[str]`): + The name of the adapter(s) whose gradients should be enabled/disabled. + requires_grad (`bool`, *optional*) + Whether to enable (`True`, default) or disable (`False`). + """ + if self.active_peft_config.is_prompt_learning: + raise TypeError( + "Setting `requires_grad` is not supported for prompt learning methods like " + f"{self.active_peft_config.peft_type.value}." + ) + + self.base_model.set_requires_grad(adapter_names=adapter_names, requires_grad=requires_grad) + + @property + def base_model_torch_dtype(self): + return getattr(self.base_model, "dtype", None) + + @property + def active_peft_config(self): + return self.peft_config[self.active_adapter] + + def _get_peft_specific_model_tags(self): + """Derive tags for the model card from the adapter's config. For example, setting the + base model is important for enabling support for HF inference providers but it also makes models more + searchable on the HF hub. + """ + peft_method = self.active_peft_config.peft_type + if not isinstance(peft_method, str): + peft_method = peft_method.value + + tags = [] + + if hasattr(self.base_model, "model") and isinstance(self.base_model.model, transformers.PreTrainedModel): + tags.append("transformers") + + if peft_method == "LORA": + tags.append("lora") + + if hasattr(self.base_model, "name_or_path"): + tags.append(f"base_model:adapter:{self.base_model.name_or_path}") + + return tags + + def create_or_update_model_card(self, output_dir: str): + """ + Updates or create model card to include information about peft: + 1. Adds `peft` library tag + 2. Adds peft version + 3. Adds base model info + 4. Adds quantization information if it was used + """ + + filename = os.path.join(output_dir, "README.md") + + card = ModelCard.load(filename) if os.path.exists(filename) else ModelCard.from_template(ModelCardData()) + + card.data["library_name"] = "peft" + + tags = set() + base_model = self.get_base_model() + if hasattr(base_model, "model_tags"): + tags = tags.union(base_model.model_tags or []) + + tags = tags.union(self._get_peft_specific_model_tags()) + if tags: + card.data["tags"] = sorted(tags) + + # One of the rare moments where we can select the pipeline tag with certainty, so let's do that. + # Makes it easier to deploy an adapter with auto inference since the user doesn't have to add any tags. + if not card.data.pipeline_tag and isinstance(self, PeftModelForCausalLM): + card.data.pipeline_tag = "text-generation" + + model_config = BaseTuner.get_model_config(self) + model_config = None if model_config == DUMMY_MODEL_CONFIG else model_config + if model_config is not None and "_name_or_path" in model_config: + card.data["base_model"] = model_config["_name_or_path"] + + lines = card.text.splitlines() + + quantization_config = None + if hasattr(model_config, "quantization_config"): + quantization_config = self.config.quantization_config.to_dict() + training_config_text = "" + quantization_prefix = "The following `bitsandbytes` quantization config was used during training:" + # Adds quantization information if it was used + if quantization_config is not None: + training_config_text += f"\n{quantization_prefix}\n" + training_config_text += "\n".join([f"- {name}: {value}" for name, value in quantization_config.items()]) + training_config_text += "\n" + + training_procedure_heading = "## Training procedure" + if quantization_prefix not in lines and bool(training_config_text): + if training_procedure_heading in lines: + lines.insert(lines.index(training_procedure_heading) + 2, training_config_text) + else: + lines.append(f"{training_procedure_heading}\n{training_config_text}") + + # Adds peft version + framework_block_heading = "### Framework versions" + if f"- PEFT {__version__}" not in lines: + if framework_block_heading in lines: + lines.insert(lines.index(framework_block_heading) + 2, f"- PEFT {__version__}") + else: + lines.append(f"{framework_block_heading}\n\n- PEFT {__version__}") + + card.text = "\n".join(lines) + card.save(filename) + + def supports_lora_conversion(self, adapter_name: str = "default") -> bool: + """ + Whether it is possible for the adapter of this model to be converted to LoRA. + + Normally, this works if the PEFT method is additive, i.e. W' = W_base + delta_weight. + """ + peft_config = self.active_peft_config + if peft_config.is_prompt_learning: + return False + + if not hasattr(self.base_model, "supports_lora_conversion"): + return False + + return self.base_model.supports_lora_conversion() + + +class PeftModelForSequenceClassification(PeftModel): + """ + Peft model for sequence classification tasks. + + Args: + model ([`~transformers.PreTrainedModel`]): Base transformer model. + peft_config ([`PeftConfig`]): Peft config. + adapter_name (`str`, *optional*): The name of the adapter, defaults to `"default"`. + autocast_adapter_dtype (`bool`, *optional*, defaults to `True`): + Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter weights + using float16 and bfloat16 to float32, as this is typically required for stable training, and only affect + select PEFT tuners. If set to `False`, the dtypes will stay the same as those of the corresponding layer. + + **Attributes**: + - **config** ([`~transformers.PretrainedConfig`]) -- The configuration object of the base model. + - **cls_layer_name** (`str`) -- The name of the classification layer. + + Example: + + ```py + >>> from transformers import AutoModelForSequenceClassification + >>> from peft import PeftModelForSequenceClassification, get_peft_config + + >>> config = { + ... "peft_type": "PREFIX_TUNING", + ... "task_type": "SEQ_CLS", + ... "inference_mode": False, + ... "num_virtual_tokens": 20, + ... "token_dim": 768, + ... "num_transformer_submodules": 1, + ... "num_attention_heads": 12, + ... "num_layers": 12, + ... "encoder_hidden_size": 768, + ... "prefix_projection": False, + ... "postprocess_past_key_value_function": None, + ... } + + >>> peft_config = get_peft_config(config) + >>> model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased") + >>> peft_model = PeftModelForSequenceClassification(model, peft_config) + >>> peft_model.print_trainable_parameters() + trainable params: 370178 || all params: 108680450 || trainable%: 0.3406113979101117 + ``` + """ + + def __init__( + self, model: torch.nn.Module, peft_config: PeftConfig, adapter_name: str = "default", **kwargs + ) -> None: + classifier_module_names = ["classifier", "score"] + + if hasattr(peft_config, "modules_to_save"): + if peft_config.modules_to_save is None: + peft_config.modules_to_save = classifier_module_names[:] + else: + peft_config.modules_to_save.extend(classifier_module_names) + + # The modification of peft_config must happen before the init call as the `modules_to_save` information + # will be used to guard the target layer matching against matching `modules_to_save` layers. Only the + # config is relevant for this, the `modules_to_save` attribute can follow later. + super().__init__(model, peft_config, adapter_name, **kwargs) + + if hasattr(peft_config, "modules_to_save"): + for name, _ in self.base_model.named_children(): + if any(module_name in name for module_name in self.modules_to_save): + self.cls_layer_name = name + break + + # to make sure classifier layer is trainable; this may add a new ModulesToSaveWrapper + _set_trainable( + self, + adapter_name, + module_names=getattr(peft_config, "modules_to_save", None), + inference_mode=peft_config.inference_mode, + ) + + def add_adapter( + self, + adapter_name: str, + peft_config: PeftConfig, + low_cpu_mem_usage: bool = False, + autocast_adapter_dtype: bool = True, + ) -> None: + """ + Add an adapter to the model based on the passed configuration. + + This adapter is not trained. To load a trained adapter, check out [`PeftModel.load_adapter`]. + + The name for the new adapter should be unique. + + The new adapter is not automatically set as the active adapter. Use [`PeftModel.set_adapter`] to set the active + adapter. + + Args: + adapter_name (`str`): + The name of the adapter to be added. + peft_config ([`PeftConfig`]): + The configuration of the adapter to be added. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the process when loading saved + adapters. Don't use this option when creating a new PEFT adapter for training. + autocast_adapter_dtype (`bool`, *optional*, defaults to `True`): + Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter + weights using float16 and bfloat16 to float32, as this is typically required for stable training, and + only affect select PEFT tuners. If set to `False`, the dtypes will stay the same as those of the + corresponding layer. + """ + # ensure that additional adapters also add the classifier layer to modules_to_save + if hasattr(peft_config, "modules_to_save"): + classifier_module_names = ["classifier", "score"] + if peft_config.modules_to_save is None: + peft_config.modules_to_save = classifier_module_names[:] + else: + peft_config.modules_to_save.extend(classifier_module_names) + + return super().add_adapter(adapter_name, peft_config, low_cpu_mem_usage=low_cpu_mem_usage) + + def forward( + self, + input_ids=None, + attention_mask=None, + inputs_embeds=None, + labels=None, + output_attentions=None, + output_hidden_states=None, + return_dict=None, + task_ids=None, + **kwargs, + ): + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + peft_config = self.active_peft_config + if not peft_config.is_prompt_learning: + with self._enable_peft_forward_hooks(**kwargs): + kwargs = {k: v for k, v in kwargs.items() if k not in self.special_peft_forward_args} + if peft_config.peft_type == PeftType.POLY: + kwargs["task_ids"] = task_ids + return self.base_model( + input_ids=input_ids, + attention_mask=attention_mask, + inputs_embeds=inputs_embeds, + labels=labels, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + **kwargs, + ) + + batch_size = _get_batch_size(input_ids, inputs_embeds) + if attention_mask is not None: + # concat prompt attention mask + prefix_attention_mask = torch.ones(batch_size, peft_config.num_virtual_tokens).to(attention_mask.device) + attention_mask = torch.cat((prefix_attention_mask, attention_mask), dim=1) + if kwargs.get("position_ids", None) is not None: + if peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + # Offset position_ids by num_virtual_tokens to account for the KV cache prefix + kwargs["position_ids"] = kwargs["position_ids"] + peft_config.num_virtual_tokens + else: + warnings.warn("Position ids are not supported for parameter efficient tuning. Ignoring position ids.") + kwargs["position_ids"] = None + kwargs.update( + { + "attention_mask": attention_mask, + "labels": labels, + "output_attentions": output_attentions, + "output_hidden_states": output_hidden_states, + "return_dict": return_dict, + } + ) + + if peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + return self._prefix_tuning_forward(input_ids=input_ids, **kwargs) + else: + if kwargs.get("token_type_ids", None) is not None: + kwargs["token_type_ids"] = torch.cat( + ( + torch.zeros(batch_size, peft_config.num_virtual_tokens).to(self.word_embeddings.weight.device), + kwargs["token_type_ids"], + ), + dim=1, + ).long() + if inputs_embeds is None: + inputs_embeds = self.word_embeddings(input_ids) + prompts = self.get_prompt(batch_size=batch_size, task_ids=task_ids) + prompts = prompts.to(inputs_embeds.dtype) + inputs_embeds = torch.cat((prompts, inputs_embeds), dim=1) + return self.base_model(inputs_embeds=inputs_embeds, **kwargs) + + def _prefix_tuning_forward( + self, + input_ids=None, + attention_mask=None, + inputs_embeds=None, + labels=None, + output_attentions=None, + output_hidden_states=None, + return_dict=None, + **kwargs, + ): + batch_size = _get_batch_size(input_ids, inputs_embeds) + past_key_values = self.get_prompt(batch_size) + fwd_params = list(inspect.signature(self.base_model.forward).parameters.keys()) + kwargs.update( + { + "input_ids": input_ids, + "attention_mask": attention_mask, + "inputs_embeds": inputs_embeds, + "output_attentions": output_attentions, + "output_hidden_states": output_hidden_states, + "return_dict": return_dict, + "past_key_values": past_key_values, + } + ) + if "past_key_values" in fwd_params: + return self.base_model(labels=labels, **kwargs) + else: + transformer_backbone_name = self.base_model.get_submodule(self.transformer_backbone_name) + fwd_params = list(inspect.signature(transformer_backbone_name.forward).parameters.keys()) + if "past_key_values" not in fwd_params: + raise ValueError("Model does not support past key values which are required for prefix tuning.") + outputs = transformer_backbone_name(**kwargs) + pooled_output = outputs[1] if len(outputs) > 1 else outputs[0] + if "dropout" in [name for name, _ in list(self.base_model.named_children())]: + pooled_output = self.base_model.dropout(pooled_output) + logits = self.base_model.get_submodule(self.cls_layer_name)(pooled_output) + + loss = None + if labels is not None: + if self.config.problem_type is None: + if self.base_model.num_labels == 1: + self.config.problem_type = "regression" + elif self.base_model.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): + self.config.problem_type = "single_label_classification" + else: + self.config.problem_type = "multi_label_classification" + + if self.config.problem_type == "regression": + loss_fct = MSELoss() + if self.base_model.num_labels == 1: + loss = loss_fct(logits.squeeze(), labels.squeeze()) + else: + loss = loss_fct(logits, labels) + elif self.config.problem_type == "single_label_classification": + loss_fct = CrossEntropyLoss() + loss = loss_fct(logits.view(-1, self.base_model.num_labels), labels.view(-1)) + elif self.config.problem_type == "multi_label_classification": + loss_fct = BCEWithLogitsLoss() + loss = loss_fct(logits, labels) + if not return_dict: + output = (logits,) + outputs[2:] + return ((loss,) + output) if loss is not None else output + + return SequenceClassifierOutput( + loss=loss, + logits=logits, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + +class PeftModelForCausalLM(PeftModel): + """ + Peft model for causal language modeling. + + Args: + model ([`~transformers.PreTrainedModel`]): Base transformer model. + peft_config ([`PeftConfig`]): Peft config. + adapter_name (`str`, *optional*): The name of the adapter, defaults to `"default"`. + autocast_adapter_dtype (`bool`, *optional*, defaults to `True`): + Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter weights + using float16 and bfloat16 to float32, as this is typically required for stable training, and only affect + select PEFT tuners. If set to `False`, the dtypes will stay the same as those of the corresponding layer. + + Example: + + ```py + >>> from transformers import AutoModelForCausalLM + >>> from peft import PeftModelForCausalLM, get_peft_config + + >>> config = { + ... "peft_type": "PREFIX_TUNING", + ... "task_type": "CAUSAL_LM", + ... "inference_mode": False, + ... "num_virtual_tokens": 20, + ... "token_dim": 1280, + ... "num_transformer_submodules": 1, + ... "num_attention_heads": 20, + ... "num_layers": 36, + ... "encoder_hidden_size": 1280, + ... "prefix_projection": False, + ... "postprocess_past_key_value_function": None, + ... } + + >>> peft_config = get_peft_config(config) + >>> model = AutoModelForCausalLM.from_pretrained("gpt2-large") + >>> peft_model = PeftModelForCausalLM(model, peft_config) + >>> peft_model.print_trainable_parameters() + trainable params: 1843200 || all params: 775873280 || trainable%: 0.23756456724479544 + ``` + """ + + def __init__( + self, model: torch.nn.Module, peft_config: PeftConfig, adapter_name: str = "default", **kwargs + ) -> None: + super().__init__(model, peft_config, adapter_name, **kwargs) + self.base_model_prepare_inputs_for_generation = self.base_model.prepare_inputs_for_generation + + def forward( + self, + input_ids=None, + attention_mask=None, + inputs_embeds=None, + labels=None, + output_attentions=None, + output_hidden_states=None, + return_dict=None, + task_ids=None, + **kwargs, + ): + peft_config = self.active_peft_config + + if not peft_config.is_prompt_learning: + # Adds alora_offsets to kwargs if relevant. No other modifications. + kwargs = get_alora_offsets_for_forward(self, input_ids, inputs_embeds, **kwargs) + if self.base_model.config.model_type == "mpt": + if inputs_embeds is not None: + raise AssertionError("forward in MPTForCausalLM does not support inputs_embeds") + return self.base_model( + input_ids=input_ids, + attention_mask=attention_mask, + labels=labels, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + **kwargs, + ) + + if peft_config.peft_type == PeftType.POLY: + kwargs["task_ids"] = task_ids + + with self._enable_peft_forward_hooks(**kwargs): + kwargs = {k: v for k, v in kwargs.items() if k not in self.special_peft_forward_args} + return self.base_model( + input_ids=input_ids, + attention_mask=attention_mask, + inputs_embeds=inputs_embeds, + labels=labels, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + **kwargs, + ) + + batch_size = _get_batch_size(input_ids, inputs_embeds) + if attention_mask is not None: + # concat prompt attention mask + prefix_attention_mask = torch.ones(batch_size, peft_config.num_virtual_tokens).to(attention_mask.device) + attention_mask = torch.cat((prefix_attention_mask, attention_mask), dim=1) + + if kwargs.get("position_ids", None) is not None: + if peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + # Offset position_ids by num_virtual_tokens to account for the KV cache prefix + kwargs["position_ids"] = kwargs["position_ids"] + peft_config.num_virtual_tokens + else: + warnings.warn("Position ids are not supported for parameter efficient tuning. Ignoring position ids.") + kwargs["position_ids"] = None + if kwargs.get("token_type_ids", None) is not None: + warnings.warn("Token type ids are not supported for parameter efficient tuning. Ignoring token type ids") + kwargs["token_type_ids"] = None + kwargs.update( + { + "attention_mask": attention_mask, + "labels": labels, + "output_attentions": output_attentions, + "output_hidden_states": output_hidden_states, + "return_dict": return_dict, + } + ) + + if peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + # overwrite past_kv in kwargs + # some archs require max_cache_len to re-initialize the cache + if input_ids is not None: + max_cache_len = input_ids.shape[1] + peft_config.num_virtual_tokens + else: + max_cache_len = inputs_embeds.shape[1] + peft_config.num_virtual_tokens + kwargs["past_key_values"] = self.get_prompt(batch_size, max_cache_len=max_cache_len) + return self.base_model(input_ids=input_ids, inputs_embeds=inputs_embeds, **kwargs) + elif peft_config.peft_type == PeftType.CPT: + return self._cpt_forward(input_ids, inputs_embeds, peft_config, task_ids, batch_size, **kwargs) + else: + if inputs_embeds is None: + inputs_embeds = self.word_embeddings(input_ids) + # concat prompt labels + if labels is not None: + prefix_labels = torch.full((batch_size, peft_config.num_virtual_tokens), -100).to(labels.device) + kwargs["labels"] = torch.cat((prefix_labels, labels), dim=1) + prompts = self.get_prompt(batch_size=batch_size, task_ids=task_ids) + prompts = prompts.to(inputs_embeds.dtype) + inputs_embeds = torch.cat((prompts, inputs_embeds), dim=1) + return self.base_model(inputs_embeds=inputs_embeds, **kwargs) + + def _cpt_forward(self, input_ids, inputs_embeds, peft_config, task_ids, batch_size, **kwargs): + # Extract labels from kwargs + labels = kwargs.pop("labels") + device = next(i.device for i in [input_ids, inputs_embeds, labels] if i is not None) + # Extract input_type_mask from kwargs and move it to the same device as labels + if "input_type_mask" in kwargs.keys(): + input_type_mask = kwargs.pop("input_type_mask").to(device) + else: + if input_ids is None: + N_tokens = inputs_embeds.shape[1] + else: + N_tokens = input_ids.shape[1] + input_type_mask = torch.ones((batch_size, N_tokens)).to(device) * 4 + + cpt_token_ids = peft_config.cpt_token_ids + cpt_tokens_type_mask = peft_config.cpt_tokens_type_mask + + # Generate embeddings if not provided + if inputs_embeds is None: + inputs_embeds = self.word_embeddings(input_ids) + # Get prompt and concatenate with input embeddings + prompts = self.get_prompt(batch_size=batch_size, task_ids=task_ids) + prompts = prompts.to(inputs_embeds.dtype) + inputs_embeds = torch.cat((prompts, inputs_embeds), dim=1) + # If labels are provided, generate prefix labels and type mask + cpt_labels = None + if labels is not None: + # Generate prefix labels and concatenate with the input labels + prefix_labels = torch.Tensor(cpt_token_ids).long().view(1, -1) + prefix_labels = prefix_labels.repeat(batch_size, 1).to(labels.device) + cpt_labels = torch.cat((prefix_labels, labels), dim=1) + # Generate prefix type mask and shift input type mask values to avoid conflicts + prefix_type_mask = torch.Tensor(cpt_tokens_type_mask).long().view(1, -1) + prefix_type_mask = prefix_type_mask.repeat(batch_size, 1).to(labels.device) + adjusted_input_type_mask = input_type_mask + adjusted_input_type_mask[adjusted_input_type_mask > 0] += prefix_type_mask.max() + # Concatenate prefix and shifted input type masks + cpt_type_mask = torch.cat((prefix_type_mask, adjusted_input_type_mask), dim=1) + # Identify valid label positions and mask invalid ones with -100 + labels_idx = (cpt_type_mask > 0) & (cpt_type_mask % 4 == 0) + cpt_labels[~labels_idx] = -100 + # Update kwargs with the modified labels + + kwargs["labels"] = cpt_labels + # Pass the modified inputs to the base model + base_model_output = self.base_model(inputs_embeds=inputs_embeds, **kwargs) + if labels is None: + return base_model_output + else: + # Calculate the loss using the custom CPT loss function + cpt_embedding = PEFT_TYPE_TO_TUNER_MAPPING[peft_config.peft_type] + base_model_output = cpt_embedding.calculate_loss( + base_model_output, cpt_labels, cpt_type_mask, self.peft_config["default"] + ) + return base_model_output + + def generate(self, *args, **kwargs): + peft_config = self.active_peft_config + self.base_model.prepare_inputs_for_generation = self.prepare_inputs_for_generation + if hasattr(self.base_model, "model"): + self.base_model.model.generation_config = self.generation_config + else: + self.base_model.generation_config = self.generation_config + try: + if not peft_config.is_prompt_learning: + # Adds alora_offsets to kwargs if relevant. No other changes. + kwargs = get_alora_offsets_for_generate(self, *args, **kwargs) + with self._enable_peft_forward_hooks(*args, **kwargs): + kwargs = {k: v for k, v in kwargs.items() if k not in self.special_peft_forward_args} + outputs = self.base_model.generate(*args, **kwargs) + else: + outputs = self.base_model.generate(*args, **kwargs) + except: + self.base_model.prepare_inputs_for_generation = self.base_model_prepare_inputs_for_generation + raise + else: + self.base_model.prepare_inputs_for_generation = self.base_model_prepare_inputs_for_generation + return outputs + + def prepare_inputs_for_generation(self, *args, task_ids: Optional[torch.Tensor] = None, **kwargs): + peft_config = self.active_peft_config + model_kwargs = self.base_model_prepare_inputs_for_generation(*args, **kwargs) + + # https://github.com/huggingface/transformers/pull/26681/ introduced new cache format + # for some architectures which requires a special fix for prompt tuning etc. + # TODO: starting with transformers 4.38, all architectures should support caching. + uses_transformers_4_38 = packaging.version.parse(transformers.__version__) >= packaging.version.parse("4.38.0") + uses_transformers_4_36 = packaging.version.parse(transformers.__version__) >= packaging.version.parse("4.36.0") + transformers_new_cache_archs = ["llama", "mistral", "persimmon", "phi"] + if packaging.version.parse(transformers.__version__) > packaging.version.parse("4.43.3"): + # https://github.com/huggingface/transformers/pull/31445 + transformers_new_cache_archs.append("bloom") + + uses_cache = uses_transformers_4_38 or ( + uses_transformers_4_36 and self.base_model.config.model_type in transformers_new_cache_archs + ) + + # heuristic to determine if we're in 'prefill stage' (when the KV cache is filled with the values from the + # initial input) + is_prefill = (model_kwargs.get("cache_position") is not None) and (model_kwargs["cache_position"][0] == 0) + + if peft_config.peft_type == PeftType.POLY: + model_kwargs["task_ids"] = task_ids + if peft_config.is_prompt_learning: + if uses_cache and (model_kwargs.get("past_key_values", None) is not None): + # change in the logic of `prepare_inputs_for_generation` makes the below code necessary + # In prompt learning methods, past key values are longer when compared to the `input_ids`. + # As such only consider the last input ids in the autogressive generation phase. + past_key_values = model_kwargs["past_key_values"] + if isinstance(past_key_values, (tuple, list)): + seq_len = past_key_values[0][0].shape[-2] + else: # using transformers kv cache + seq_len = past_key_values.get_seq_length() + if seq_len >= model_kwargs["input_ids"].shape[1]: + model_kwargs["input_ids"] = model_kwargs["input_ids"][:, -1:] + + if (attention_mask := model_kwargs.get("attention_mask", None)) is not None: + if isinstance(attention_mask, dict): + # see: https://github.com/huggingface/transformers/pull/37866 + # For now, just deal with the case of a single attention mask + if len(attention_mask) != 1: + raise ValueError( + f"Expected a single attention mask, got {len(attention_mask)} instead, please open an " + "issue (https://github.com/huggingface/peft/issues) and report the error." + ) + attention_mask = next(iter(attention_mask.values())) + + size = model_kwargs["input_ids"].shape[0], peft_config.num_virtual_tokens + prefix_attention_mask = torch.ones(size).to(model_kwargs["input_ids"].device) + if attention_mask.dim() == 4: + # Transform the 4d attention mask to 2d, leave it up to the model to deal with it instead of trying + # to create a 4d attention mask here. + # from [batch_size, heads, input_ids_length, total_sequence_length] + # to [batch_size, total_sequence_length] + bs = attention_mask.shape[0] + total_seq_len = prefix_attention_mask.shape[1] + attention_mask.shape[2] + attention_mask_2d = torch.ones((bs, total_seq_len), dtype=attention_mask.dtype) + + if is_prefill and (peft_config.peft_type not in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE)): + # if in prefill stage, for prompt learning methods that are not prefix tuning, new tokens + # (embeddings) are inserted, thus set cache_position to correspond to these tokens + cache_position_ = torch.arange(total_seq_len, device=model_kwargs["input_ids"].device) + else: + # prefix tuning acts directly on the cache, no need to upate cache_position + cache_position_ = model_kwargs["cache_position"] + + attention_mask_new = create_attention_mask( + self.get_base_model(), + model_input=None, + attention_mask=attention_mask_2d, + past_key_values=model_kwargs.get("past_key_values"), + cache_position=cache_position_, + batch_size=bs, + sequence_length=total_seq_len, + position_ids=model_kwargs.get("position_ids", None), + ) + model_kwargs["attention_mask"] = attention_mask_new + else: + # 2d attention mask + model_kwargs["attention_mask"] = torch.cat((prefix_attention_mask, attention_mask), dim=1) + + if model_kwargs.get("position_ids", None) is not None: + if peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + # Offset position_ids by num_virtual_tokens to account for the KV cache prefix + model_kwargs["position_ids"] = model_kwargs["position_ids"] + peft_config.num_virtual_tokens + else: + warnings.warn( + "Position ids are not supported for parameter efficient tuning. Ignoring position ids." + ) + model_kwargs["position_ids"] = None + + if kwargs.get("token_type_ids", None) is not None: + warnings.warn( + "Token type ids are not supported for parameter efficient tuning. Ignoring token type ids" + ) + kwargs["token_type_ids"] = None + + cache: transformers.Cache | None = model_kwargs.get("past_key_values", None) + # no past_key_values or past_key_values empty cache + requires_prompt_injection = (cache is None) or ( + isinstance(cache, transformers.Cache) and not cache.get_seq_length() + ) + + if requires_prompt_injection and peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + # some archs require max_cache_len to re-initialize the cache, but DynamicCache has no max len + if isinstance(cache, transformers.Cache) and not isinstance(cache, transformers.DynamicCache): + max_cache_len = cache.max_cache_len + else: + max_cache_len = -1 # -1 means no max length + new_past_key_values = self.get_prompt( + batch_size=model_kwargs["input_ids"].shape[0], + max_cache_len=max_cache_len, + ) + model_kwargs["past_key_values"] = new_past_key_values + elif requires_prompt_injection: + inputs_embeds = self.word_embeddings(model_kwargs["input_ids"]) + prompts = self.get_prompt(batch_size=model_kwargs["input_ids"].shape[0], task_ids=task_ids) + prompts = prompts.to(inputs_embeds.dtype) + model_kwargs["inputs_embeds"] = torch.cat((prompts, inputs_embeds), dim=1) + model_kwargs["input_ids"] = None + + # if we're in the prefill stage + if is_prefill and (peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE)): + # for prefix tuning, the past_key_values have been prefilled + model_kwargs["cache_position"] += peft_config.num_virtual_tokens + elif peft_config.peft_type not in ( + PeftType.PREFIX_TUNING, + PeftType.CARTRIDGE, + ): # prefix-style needs cache_position + # For transformers>=4.38.0 - for some architectures such as Llama, `cache_position` is passed in the forward + # pass to keep track of the position ids of the cache. We have to pop that from `model_kwargs` as + # `cache_position` is properly created by the model, using the passed `inputs_embeds`: + # https://github.com/huggingface/transformers/blob/593230f0a1150ea9c0477b9d859f25daf73c8c33/src/transformers/models/llama/modeling_llama.py#L956 + _ = model_kwargs.pop("cache_position", None) + + return model_kwargs + + +class PeftModelForSeq2SeqLM(PeftModel): + """ + Peft model for sequence-to-sequence language modeling. + + Args: + model ([`~transformers.PreTrainedModel`]): Base transformer model. + peft_config ([`PeftConfig`]): Peft config. + adapter_name (`str`, *optional*): The name of the adapter, defaults to `"default"`. + autocast_adapter_dtype (`bool`, *optional*, defaults to `True`): + Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter weights + using float16 and bfloat16 to float32, as this is typically required for stable training, and only affect + select PEFT tuners. If set to `False`, the dtypes will stay the same as those of the corresponding layer. + + Example: + + ```py + >>> from transformers import AutoModelForSeq2SeqLM + >>> from peft import PeftModelForSeq2SeqLM, get_peft_config + + >>> config = { + ... "peft_type": "LORA", + ... "task_type": "SEQ_2_SEQ_LM", + ... "inference_mode": False, + ... "r": 8, + ... "target_modules": ["q", "v"], + ... "lora_alpha": 32, + ... "lora_dropout": 0.1, + ... "fan_in_fan_out": False, + ... "enable_lora": None, + ... "bias": "none", + ... } + + >>> peft_config = get_peft_config(config) + >>> model = AutoModelForSeq2SeqLM.from_pretrained("t5-base") + >>> peft_model = PeftModelForSeq2SeqLM(model, peft_config) + >>> peft_model.print_trainable_parameters() + trainable params: 884736 || all params: 223843584 || trainable%: 0.3952474242013566 + ``` + """ + + def __init__( + self, model: torch.nn.Module, peft_config: PeftConfig, adapter_name: str = "default", **kwargs + ) -> None: + super().__init__(model, peft_config, adapter_name, **kwargs) + self.base_model_prepare_inputs_for_generation = self.base_model.prepare_inputs_for_generation + self.base_model_prepare_encoder_decoder_kwargs_for_generation = ( + self.base_model._prepare_encoder_decoder_kwargs_for_generation + ) + + def forward( + self, + input_ids=None, + attention_mask=None, + inputs_embeds=None, + decoder_input_ids=None, + decoder_attention_mask=None, + decoder_inputs_embeds=None, + labels=None, + output_attentions=None, + output_hidden_states=None, + return_dict=None, + task_ids=None, + **kwargs, + ): + peft_config = self.active_peft_config + if not peft_config.is_prompt_learning: + if peft_config.peft_type == PeftType.POLY: + kwargs["task_ids"] = task_ids + + with self._enable_peft_forward_hooks(**kwargs): + kwargs = {k: v for k, v in kwargs.items() if k not in self.special_peft_forward_args} + return self.base_model( + input_ids=input_ids, + attention_mask=attention_mask, + inputs_embeds=inputs_embeds, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + decoder_inputs_embeds=decoder_inputs_embeds, + labels=labels, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + **kwargs, + ) + + batch_size = _get_batch_size(input_ids, inputs_embeds) + if decoder_attention_mask is not None: + # concat prompt attention mask + prefix_attention_mask = torch.ones(batch_size, peft_config.num_virtual_tokens).to( + decoder_attention_mask.device + ) + if peft_config.peft_type not in [PeftType.PROMPT_TUNING, PeftType.P_TUNING]: + decoder_attention_mask = torch.cat((prefix_attention_mask, decoder_attention_mask), dim=1) + + if kwargs.get("position_ids", None) is not None: + if peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + # Offset position_ids by num_virtual_tokens to account for the KV cache prefix + kwargs["position_ids"] = kwargs["position_ids"] + peft_config.num_virtual_tokens + else: + warnings.warn("Position ids are not supported for parameter efficient tuning. Ignoring position ids.") + kwargs["position_ids"] = None + if kwargs.get("token_type_ids", None) is not None: + warnings.warn("Token type ids are not supported for parameter efficient tuning. Ignoring token type ids") + kwargs["token_type_ids"] = None + kwargs.update( + { + "attention_mask": attention_mask, + "decoder_attention_mask": decoder_attention_mask, + "labels": labels, + "output_attentions": output_attentions, + "output_hidden_states": output_hidden_states, + "return_dict": return_dict, + } + ) + + if peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + # overwrite past_kv in kwargs + kwargs["past_key_values"] = self.get_prompt(batch_size) + return self.base_model( + input_ids=input_ids, + decoder_input_ids=decoder_input_ids, + decoder_inputs_embeds=decoder_inputs_embeds, + **kwargs, + ) + elif peft_config.peft_type in [PeftType.PROMPT_TUNING, PeftType.P_TUNING]: + if inputs_embeds is None: + inputs_embeds = self.word_embeddings(input_ids) + + if attention_mask is not None: + # concat prompt attention mask + prefix_attention_mask = torch.ones(batch_size, peft_config.num_virtual_tokens).to( + attention_mask.device + ) + kwargs["attention_mask"] = torch.cat((prefix_attention_mask, attention_mask), dim=1) + + prompts = self.get_prompt(batch_size=batch_size) + prompts = prompts.to(inputs_embeds.dtype) + inputs_embeds = torch.cat((prompts[:, : peft_config.num_virtual_tokens], inputs_embeds), dim=1) + + return self.base_model( + inputs_embeds=inputs_embeds, + decoder_input_ids=decoder_input_ids, + decoder_inputs_embeds=decoder_inputs_embeds, + **kwargs, + ) + else: + if inputs_embeds is None: + inputs_embeds = self.word_embeddings(input_ids) + if decoder_inputs_embeds is None and decoder_input_ids is None: + decoder_input_ids = shift_tokens_right( + labels, self.config.pad_token_id, self.config.decoder_start_token_id + ) + decoder_inputs_embeds = self.word_embeddings(decoder_input_ids) + + if attention_mask is not None: + # concat prompt attention mask + prefix_attention_mask = torch.ones(batch_size, peft_config.num_virtual_tokens).to( + attention_mask.device + ) + kwargs["attention_mask"] = torch.cat((prefix_attention_mask, attention_mask), dim=1) + # concat prompt labels + if labels is not None: + if peft_config.num_transformer_submodules == 1: + kwargs["labels"] = labels + elif peft_config.num_transformer_submodules == 2: + prefix_labels = torch.full((batch_size, peft_config.num_virtual_tokens), -100).to(labels.device) + kwargs["labels"] = torch.cat((prefix_labels, labels), dim=1) + prompts = self.get_prompt(batch_size=batch_size, task_ids=task_ids) + prompts = prompts.to(inputs_embeds.dtype) + inputs_embeds = torch.cat((prompts[:, : peft_config.num_virtual_tokens], inputs_embeds), dim=1) + if peft_config.num_transformer_submodules == 1: + return self.base_model(inputs_embeds=inputs_embeds, **kwargs) + elif peft_config.num_transformer_submodules == 2: + decoder_inputs_embeds = torch.cat( + (prompts[:, peft_config.num_virtual_tokens :], decoder_inputs_embeds), dim=1 + ) + return self.base_model( + inputs_embeds=inputs_embeds, decoder_inputs_embeds=decoder_inputs_embeds, **kwargs + ) + + def generate(self, **kwargs): + peft_config = self.active_peft_config + self.base_model.prepare_inputs_for_generation = self.prepare_inputs_for_generation + self.base_model._prepare_encoder_decoder_kwargs_for_generation = ( + self._prepare_encoder_decoder_kwargs_for_generation + ) + try: + if not peft_config.is_prompt_learning: + with self._enable_peft_forward_hooks(**kwargs): + kwargs = {k: v for k, v in kwargs.items() if k not in self.special_peft_forward_args} + outputs = self.base_model.generate(**kwargs) + else: + if "input_ids" not in kwargs: + raise ValueError("input_ids must be provided for Peft model generation") + if kwargs.get("position_ids", None) is not None: + if peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + # Offset position_ids by num_virtual_tokens to account for the KV cache prefix + kwargs["position_ids"] = kwargs["position_ids"] + peft_config.num_virtual_tokens + else: + warnings.warn( + "Position ids are not supported for parameter efficient tuning. Ignoring position ids." + ) + kwargs["position_ids"] = None + if kwargs.get("token_type_ids", None) is not None: + warnings.warn( + "Token type ids are not supported for parameter efficient tuning. Ignoring token type ids" + ) + kwargs["token_type_ids"] = None + + if peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + outputs = self.base_model.generate(**kwargs) + elif peft_config.peft_type in [ + PeftType.PROMPT_TUNING, + PeftType.P_TUNING, + PeftType.MULTITASK_PROMPT_TUNING, + ]: + kwargs = deepcopy(kwargs) + + if "encoder_outputs" in kwargs: + del kwargs["encoder_outputs"] + warnings.warn( + "`encoder_outputs` should not be passed to `generate` when using prompt tuning. Ignoring it." + ) + + input_ids = kwargs.pop("input_ids") + inputs_embeds = self.word_embeddings(input_ids) + batch_size = inputs_embeds.shape[0] + prompts = self.get_prompt(batch_size=batch_size, task_ids=kwargs.pop("task_ids", None)) + prompts = prompts.to(inputs_embeds.dtype) + + inputs_embeds = torch.cat((prompts[:, : peft_config.num_virtual_tokens], inputs_embeds), dim=1) + kwargs["inputs_embeds"] = inputs_embeds + + if "attention_mask" in kwargs: + prefix_attention_mask = torch.ones(batch_size, peft_config.num_virtual_tokens).to( + kwargs["attention_mask"].device + ) + kwargs["attention_mask"] = torch.cat((prefix_attention_mask, kwargs["attention_mask"]), dim=1) + + return self.base_model.generate(**kwargs) + else: + raise NotImplementedError + except: + self.base_model.prepare_inputs_for_generation = self.base_model_prepare_inputs_for_generation + self.base_model._prepare_encoder_decoder_kwargs_for_generation = ( + self.base_model_prepare_encoder_decoder_kwargs_for_generation + ) + raise + else: + self.base_model.prepare_inputs_for_generation = self.base_model_prepare_inputs_for_generation + self.base_model._prepare_encoder_decoder_kwargs_for_generation = ( + self.base_model_prepare_encoder_decoder_kwargs_for_generation + ) + return outputs + + def prepare_inputs_for_generation(self, *args, task_ids: torch.Tensor = None, **kwargs): + peft_config = self.active_peft_config + model_kwargs = self.base_model_prepare_inputs_for_generation(*args, **kwargs) + if peft_config.peft_type == PeftType.POLY: + model_kwargs["task_ids"] = task_ids + elif peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + past_key_values = model_kwargs.get("past_key_values", None) + cache_position = model_kwargs.get("cache_position", [None]) + # check prefill stage + is_prefill_stage = kwargs.get("is_first_iteration") + if is_prefill_stage is None: # transformers < v5 + is_prefill_stage = ( + # old cache implementation + (past_key_values is None) + # new cache implementation + or (isinstance(past_key_values, Cache) and (past_key_values.get_seq_length() == 0)) + ) + if is_prefill_stage: + batch_size = model_kwargs["decoder_input_ids"].shape[0] + new_past_key_values = self.get_prompt(batch_size) + model_kwargs["past_key_values"] = new_past_key_values + + return model_kwargs + + +class PeftModelForTokenClassification(PeftModel): + """ + Peft model for token classification tasks. + + Args: + model ([`~transformers.PreTrainedModel`]): Base transformer model. + peft_config ([`PeftConfig`]): Peft config. + adapter_name (`str`, *optional*): The name of the adapter, defaults to `"default"`. + autocast_adapter_dtype (`bool`, *optional*, defaults to `True`): + Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter weights + using float16 and bfloat16 to float32, as this is typically required for stable training, and only affect + select PEFT tuners. If set to `False`, the dtypes will stay the same as those of the corresponding layer. + + **Attributes**: + - **config** ([`~transformers.PretrainedConfig`]) -- The configuration object of the base model. + - **cls_layer_name** (`str`) -- The name of the classification layer. + + Example: + + ```py + >>> from transformers import AutoModelForSequenceClassification + >>> from peft import PeftModelForTokenClassification, get_peft_config + + >>> config = { + ... "peft_type": "PREFIX_TUNING", + ... "task_type": "TOKEN_CLS", + ... "inference_mode": False, + ... "num_virtual_tokens": 20, + ... "token_dim": 768, + ... "num_transformer_submodules": 1, + ... "num_attention_heads": 12, + ... "num_layers": 12, + ... "encoder_hidden_size": 768, + ... "prefix_projection": False, + ... "postprocess_past_key_value_function": None, + ... } + + >>> peft_config = get_peft_config(config) + >>> model = AutoModelForTokenClassification.from_pretrained("bert-base-cased") + >>> peft_model = PeftModelForTokenClassification(model, peft_config) + >>> peft_model.print_trainable_parameters() + trainable params: 370178 || all params: 108680450 || trainable%: 0.3406113979101117 + ``` + """ + + def __init__( + self, model: torch.nn.Module, peft_config: PeftConfig = None, adapter_name: str = "default", **kwargs + ) -> None: + super().__init__(model, peft_config, adapter_name, **kwargs) + + classifier_module_names = ["classifier", "score"] + if hasattr(peft_config, "modules_to_save"): + if peft_config.modules_to_save is None: + peft_config.modules_to_save = classifier_module_names[:] + else: + peft_config.modules_to_save.extend(classifier_module_names) + + for name, _ in self.base_model.named_children(): + if any(module_name in name for module_name in self.modules_to_save): + self.cls_layer_name = name + break + + # to make sure classifier layer is trainable; this may add a new ModulesToSaveWrapper + _set_trainable( + self, + adapter_name, + module_names=getattr(peft_config, "modules_to_save", None), + inference_mode=peft_config.inference_mode, + ) + + def add_adapter( + self, + adapter_name: str, + peft_config: PeftConfig, + low_cpu_mem_usage: bool = False, + autocast_adapter_dtype: bool = True, + ) -> None: + """ + Add an adapter to the model based on the passed configuration. + + This adapter is not trained. To load a trained adapter, check out [`PeftModel.load_adapter`]. + + The name for the new adapter should be unique. + + The new adapter is not automatically set as the active adapter. Use [`PeftModel.set_adapter`] to set the active + adapter. + + Args: + adapter_name (`str`): + The name of the adapter to be added. + peft_config ([`PeftConfig`]): + The configuration of the adapter to be added. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the process when loading saved + adapters. Don't use this option when creating a new PEFT adapter for training. + autocast_adapter_dtype (`bool`, *optional*, defaults to `True`): + Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter + weights using float16 and bfloat16 to float32, as this is typically required for stable training, and + only affect select PEFT tuners. If set to `False`, the dtypes will stay the same as those of the + corresponding layer. + + """ + # ensure that additional adapters also add the classifier layer to modules_to_save + if hasattr(peft_config, "modules_to_save"): + classifier_module_names = ["classifier", "score"] + if peft_config.modules_to_save is None: + peft_config.modules_to_save = classifier_module_names[:] + else: + peft_config.modules_to_save.extend(classifier_module_names) + + return super().add_adapter(adapter_name, peft_config, low_cpu_mem_usage=low_cpu_mem_usage) + + def forward( + self, + input_ids=None, + attention_mask=None, + inputs_embeds=None, + labels=None, + output_attentions=None, + output_hidden_states=None, + return_dict=None, + task_ids=None, + **kwargs, + ): + peft_config = self.active_peft_config + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + if not peft_config.is_prompt_learning: + with self._enable_peft_forward_hooks(**kwargs): + kwargs = {k: v for k, v in kwargs.items() if k not in self.special_peft_forward_args} + if peft_config.peft_type == PeftType.POLY: + kwargs["task_ids"] = task_ids + return self.base_model( + input_ids=input_ids, + attention_mask=attention_mask, + inputs_embeds=inputs_embeds, + labels=labels, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + **kwargs, + ) + + batch_size = _get_batch_size(input_ids, inputs_embeds) + if attention_mask is not None: + # concat prompt attention mask + prefix_attention_mask = torch.ones(batch_size, peft_config.num_virtual_tokens).to(attention_mask.device) + attention_mask = torch.cat((prefix_attention_mask, attention_mask), dim=1) + if kwargs.get("position_ids", None) is not None: + if peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + # Offset position_ids by num_virtual_tokens to account for the KV cache prefix + kwargs["position_ids"] = kwargs["position_ids"] + peft_config.num_virtual_tokens + else: + warnings.warn("Position ids are not supported for parameter efficient tuning. Ignoring position ids.") + kwargs["position_ids"] = None + kwargs.update( + { + "attention_mask": attention_mask, + "labels": labels, + "output_attentions": output_attentions, + "output_hidden_states": output_hidden_states, + "return_dict": return_dict, + } + ) + + if peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + return self._prefix_tuning_forward(input_ids=input_ids, **kwargs) + else: + if kwargs.get("token_type_ids", None) is not None: + kwargs["token_type_ids"] = torch.cat( + ( + torch.zeros(batch_size, peft_config.num_virtual_tokens).to(self.word_embeddings.weight.device), + kwargs["token_type_ids"], + ), + dim=1, + ).long() + if inputs_embeds is None: + inputs_embeds = self.word_embeddings(input_ids) + prompts = self.get_prompt(batch_size=batch_size, task_ids=task_ids) + prompts = prompts.to(inputs_embeds.dtype) + inputs_embeds = torch.cat((prompts, inputs_embeds), dim=1) + return self.base_model(inputs_embeds=inputs_embeds, **kwargs) + + def _prefix_tuning_forward( + self, + input_ids=None, + attention_mask=None, + inputs_embeds=None, + labels=None, + output_attentions=None, + output_hidden_states=None, + return_dict=None, + **kwargs, + ): + batch_size = _get_batch_size(input_ids, inputs_embeds) + past_key_values = self.get_prompt(batch_size) + fwd_params = list(inspect.signature(self.base_model.forward).parameters.keys()) + kwargs.update( + { + "input_ids": input_ids, + "attention_mask": attention_mask, + "inputs_embeds": inputs_embeds, + "output_attentions": output_attentions, + "output_hidden_states": output_hidden_states, + "return_dict": return_dict, + "past_key_values": past_key_values, + } + ) + if "past_key_values" in fwd_params: + return self.base_model(labels=labels, **kwargs) + else: + transformer_backbone_name = self.base_model.get_submodule(self.transformer_backbone_name) + fwd_params = list(inspect.signature(transformer_backbone_name.forward).parameters.keys()) + if "past_key_values" not in fwd_params: + raise ValueError("Model does not support past key values which are required for prefix tuning.") + outputs = transformer_backbone_name(**kwargs) + sequence_output = outputs[0] + if "dropout" in [name for name, _ in list(self.base_model.named_children())]: + sequence_output = self.base_model.dropout(sequence_output) + logits = self.base_model.get_submodule(self.cls_layer_name)(sequence_output) + + loss = None + if labels is not None: + loss_fct = CrossEntropyLoss() + loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) + + if not return_dict: + output = (logits,) + outputs[2:] + return ((loss,) + output) if loss is not None else output + + return TokenClassifierOutput( + loss=loss, + logits=logits, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + +class PeftModelForQuestionAnswering(PeftModel): + """ + Peft model for extractive question answering. + + Args: + model ([`~transformers.PreTrainedModel`]): Base transformer model. + peft_config ([`PeftConfig`]): Peft config. + adapter_name (`str`, *optional*): The name of the adapter, defaults to `"default"`. + autocast_adapter_dtype (`bool`, *optional*, defaults to `True`): + Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter weights + using float16 and bfloat16 to float32, as this is typically required for stable training, and only affect + select PEFT tuners. If set to `False`, the dtypes will stay the same as those of the corresponding layer. + + **Attributes**: + - **config** ([`~transformers.PretrainedConfig`]) -- The configuration object of the base model. + - **cls_layer_name** (`str`) -- The name of the classification layer. + + Example: + + ```py + >>> from transformers import AutoModelForQuestionAnswering + >>> from peft import PeftModelForQuestionAnswering, get_peft_config + + >>> config = { + ... "peft_type": "LORA", + ... "task_type": "QUESTION_ANS", + ... "inference_mode": False, + ... "r": 16, + ... "target_modules": ["query", "value"], + ... "lora_alpha": 32, + ... "lora_dropout": 0.05, + ... "fan_in_fan_out": False, + ... "bias": "none", + ... } + + >>> peft_config = get_peft_config(config) + >>> model = AutoModelForQuestionAnswering.from_pretrained("bert-base-cased") + >>> peft_model = PeftModelForQuestionAnswering(model, peft_config) + >>> peft_model.print_trainable_parameters() + trainable params: 592900 || all params: 108312580 || trainable%: 0.5473971721475013 + ``` + """ + + def __init__( + self, model: torch.nn.Module, peft_config: PeftConfig, adapter_name: str = "default", **kwargs + ) -> None: + super().__init__(model, peft_config, adapter_name, **kwargs) + + qa_module_names = ["qa_outputs"] + if hasattr(peft_config, "modules_to_save"): + if peft_config.modules_to_save is None: + peft_config.modules_to_save = qa_module_names[:] + else: + peft_config.modules_to_save.extend(qa_module_names) + + for name, _ in self.base_model.named_children(): + if any(module_name in name for module_name in self.modules_to_save): + self.cls_layer_name = name + break + + # to make sure classifier layer is trainable; this may add a new ModulesToSaveWrapper + _set_trainable( + self, + adapter_name, + module_names=getattr(peft_config, "modules_to_save", None), + inference_mode=peft_config.inference_mode, + ) + + def add_adapter( + self, + adapter_name: str, + peft_config: PeftConfig, + low_cpu_mem_usage: bool = False, + autocast_adapter_dtype: bool = True, + ) -> None: + """ + Add an adapter to the model based on the passed configuration. + + This adapter is not trained. To load a trained adapter, check out [`PeftModel.load_adapter`]. + + The name for the new adapter should be unique. + + The new adapter is not automatically set as the active adapter. Use [`PeftModel.set_adapter`] to set the active + adapter. + + Args: + adapter_name (`str`): + The name of the adapter to be added. + peft_config ([`PeftConfig`]): + The configuration of the adapter to be added. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the process when loading saved + adapters. Don't use this option when creating a new PEFT adapter for training. + autocast_adapter_dtype (`bool`, *optional*, defaults to `True`): + Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter + weights using float16 and bfloat16 to float32, as this is typically required for stable training, and + only affect select PEFT tuners. If set to `False`, the dtypes will stay the same as those of the + corresponding layer. + + """ + # ensure that additional adapters also add the classifier layer to modules_to_save + if hasattr(peft_config, "modules_to_save"): + qa_module_names = ["qa_outputs"] + if peft_config.modules_to_save is None: + peft_config.modules_to_save = qa_module_names[:] + else: + peft_config.modules_to_save.extend(qa_module_names) + + return super().add_adapter(adapter_name, peft_config, low_cpu_mem_usage=low_cpu_mem_usage) + + def forward( + self, + input_ids=None, + attention_mask=None, + token_type_ids=None, + position_ids=None, + inputs_embeds=None, + start_positions=None, + end_positions=None, + output_attentions=None, + output_hidden_states=None, + return_dict=None, + task_ids=None, + **kwargs, + ): + peft_config = self.active_peft_config + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + if not peft_config.is_prompt_learning: + if peft_config.peft_type == PeftType.POLY: + kwargs["task_ids"] = task_ids + + with self._enable_peft_forward_hooks(**kwargs): + kwargs = {k: v for k, v in kwargs.items() if k not in self.special_peft_forward_args} + return self.base_model( + input_ids=input_ids, + attention_mask=attention_mask, + inputs_embeds=inputs_embeds, + start_positions=start_positions, + end_positions=end_positions, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + **kwargs, + ) + + batch_size = _get_batch_size(input_ids, inputs_embeds) + if attention_mask is not None: + # concat prompt attention mask + prefix_attention_mask = torch.ones(batch_size, peft_config.num_virtual_tokens).to(attention_mask.device) + attention_mask = torch.cat((prefix_attention_mask, attention_mask), dim=1) + if kwargs.get("position_ids", None) is not None: + if peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + # Offset position_ids by num_virtual_tokens to account for the KV cache prefix + kwargs["position_ids"] = kwargs["position_ids"] + peft_config.num_virtual_tokens + else: + warnings.warn("Position ids are not supported for parameter efficient tuning. Ignoring position ids.") + kwargs["position_ids"] = None + kwargs.update( + { + "attention_mask": attention_mask, + "start_positions": start_positions, + "end_positions": end_positions, + "output_attentions": output_attentions, + "output_hidden_states": output_hidden_states, + "return_dict": return_dict, + } + ) + + if peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + return self._prefix_tuning_forward(input_ids=input_ids, **kwargs) + else: + if kwargs.get("token_type_ids", None) is not None: + kwargs["token_type_ids"] = torch.cat( + ( + torch.zeros(batch_size, peft_config.num_virtual_tokens).to(self.word_embeddings.weight.device), + kwargs["token_type_ids"], + ), + dim=1, + ).long() + if inputs_embeds is None: + inputs_embeds = self.word_embeddings(input_ids) + prompts = self.get_prompt(batch_size=batch_size) + prompts = prompts.to(inputs_embeds.dtype) + inputs_embeds = torch.cat((prompts, inputs_embeds), dim=1) + return self.base_model(inputs_embeds=inputs_embeds, **kwargs) + + def _prefix_tuning_forward( + self, + input_ids=None, + attention_mask=None, + inputs_embeds=None, + start_positions=None, + end_positions=None, + output_attentions=None, + output_hidden_states=None, + return_dict=None, + **kwargs, + ): + batch_size = _get_batch_size(input_ids, inputs_embeds) + past_key_values = self.get_prompt(batch_size) + fwd_params = list(inspect.signature(self.base_model.forward).parameters.keys()) + kwargs.update( + { + "input_ids": input_ids, + "attention_mask": attention_mask, + "inputs_embeds": inputs_embeds, + "output_attentions": output_attentions, + "output_hidden_states": output_hidden_states, + "return_dict": return_dict, + "past_key_values": past_key_values, + } + ) + if "past_key_values" in fwd_params: + return self.base_model(start_positions=start_positions, end_positions=end_positions, **kwargs) + else: + transformer_backbone_name = self.base_model.get_submodule(self.transformer_backbone_name) + fwd_params = list(inspect.signature(transformer_backbone_name.forward).parameters.keys()) + if "past_key_values" not in fwd_params: + raise ValueError("Model does not support past key values which are required for prefix tuning.") + outputs = transformer_backbone_name(**kwargs) + sequence_output = outputs[0] + if "dropout" in [name for name, _ in list(self.base_model.named_children())]: + sequence_output = self.base_model.dropout(sequence_output) + logits = self.base_model.get_submodule(self.cls_layer_name)(sequence_output) + start_logits, end_logits = logits.split(1, dim=-1) + start_logits = start_logits.squeeze(-1).contiguous() + end_logits = end_logits.squeeze(-1).contiguous() + + total_loss = None + if start_positions is not None and end_positions is not None: + # If we are on multi-GPU, split add a dimension + if len(start_positions.size()) > 1: + start_positions = start_positions.squeeze(-1) + if len(end_positions.size()) > 1: + end_positions = end_positions.squeeze(-1) + # sometimes the start/end positions are outside our model inputs, we ignore these terms + ignored_index = start_logits.size(1) + start_positions = start_positions.clamp(0, ignored_index) + end_positions = end_positions.clamp(0, ignored_index) + + loss_fct = CrossEntropyLoss(ignore_index=ignored_index) + start_loss = loss_fct(start_logits, start_positions) + end_loss = loss_fct(end_logits, end_positions) + total_loss = (start_loss + end_loss) / 2 + + if not return_dict: + output = (start_logits, end_logits) + outputs[2:] + return ((total_loss,) + output) if total_loss is not None else output + + return QuestionAnsweringModelOutput( + loss=total_loss, + start_logits=start_logits, + end_logits=end_logits, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + +class PeftModelForFeatureExtraction(PeftModel): + """ + Peft model for extracting features/embeddings from transformer models + + Args: + model ([`~transformers.PreTrainedModel`]): Base transformer model. + peft_config ([`PeftConfig`]): Peft config. + adapter_name (`str`, *optional*): The name of the adapter, defaults to `"default"`. + autocast_adapter_dtype (`bool`, *optional*, defaults to `True`): + Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter weights + using float16 and bfloat16 to float32, as this is typically required for stable training, and only affect + select PEFT tuners. If set to `False`, the dtypes will stay the same as those of the corresponding layer. + + **Attributes**: + - **config** ([`~transformers.PretrainedConfig`]) -- The configuration object of the base model. + + Example: + + ```py + >>> from transformers import AutoModel + >>> from peft import PeftModelForFeatureExtraction, get_peft_config + + >>> config = { + ... "peft_type": "LORA", + ... "task_type": "FEATURE_EXTRACTION", + ... "inference_mode": False, + ... "r": 16, + ... "target_modules": ["query", "value"], + ... "lora_alpha": 32, + ... "lora_dropout": 0.05, + ... "fan_in_fan_out": False, + ... "bias": "none", + ... } + >>> peft_config = get_peft_config(config) + >>> model = AutoModel.from_pretrained("bert-base-cased") + >>> peft_model = PeftModelForFeatureExtraction(model, peft_config) + >>> peft_model.print_trainable_parameters() + ``` + """ + + def __init__(self, model: torch.nn.Module, peft_config: PeftConfig, adapter_name: str = "default", **kwargs): + super().__init__(model, peft_config, adapter_name, **kwargs) + + def forward( + self, + input_ids=None, + attention_mask=None, + inputs_embeds=None, + output_attentions=None, + output_hidden_states=None, + return_dict=None, + task_ids=None, + **kwargs, + ): + peft_config = self.active_peft_config + if not peft_config.is_prompt_learning: + if peft_config.peft_type == PeftType.POLY: + kwargs["task_ids"] = task_ids + + with self._enable_peft_forward_hooks(**kwargs): + kwargs = {k: v for k, v in kwargs.items() if k not in self.special_peft_forward_args} + return self.base_model( + input_ids=input_ids, + attention_mask=attention_mask, + inputs_embeds=inputs_embeds, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + **kwargs, + ) + + batch_size = _get_batch_size(input_ids, inputs_embeds) + if attention_mask is not None: + # concat prompt attention mask + prefix_attention_mask = torch.ones(batch_size, peft_config.num_virtual_tokens).to(attention_mask.device) + attention_mask = torch.cat((prefix_attention_mask, attention_mask), dim=1) + + if kwargs.get("position_ids", None) is not None: + if peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + # Offset position_ids by num_virtual_tokens to account for the KV cache prefix + kwargs["position_ids"] = kwargs["position_ids"] + peft_config.num_virtual_tokens + else: + warnings.warn("Position ids are not supported for parameter efficient tuning. Ignoring position ids.") + kwargs["position_ids"] = None + if kwargs.get("token_type_ids", None) is not None: + warnings.warn("Token type ids are not supported for parameter efficient tuning. Ignoring token type ids") + kwargs["token_type_ids"] = None + kwargs.update( + { + "attention_mask": attention_mask, + "output_attentions": output_attentions, + "output_hidden_states": output_hidden_states, + "return_dict": return_dict, + } + ) + + if peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + # overwrite past_kv in kwargs + kwargs["past_key_values"] = self.get_prompt(batch_size) + return self.base_model(input_ids=input_ids, **kwargs) + else: + if inputs_embeds is None: + inputs_embeds = self.word_embeddings(input_ids) + prompts = self.get_prompt(batch_size=batch_size) + prompts = prompts.to(inputs_embeds.dtype) + inputs_embeds = torch.cat((prompts, inputs_embeds), dim=1) + return self.base_model(inputs_embeds=inputs_embeds, **kwargs) + + +@dataclass +class TunerLayerStatus: + name: str + module_type: str + enabled: bool + active_adapters: list[str] + merged_adapters: list[str] + requires_grad: dict[str, bool | Literal["irregular"]] + available_adapters: list[str] + devices: dict[str, list[str]] + quantization_backend: str | None + + +def get_layer_status(model: torch.nn.Module) -> list[TunerLayerStatus]: + """Get the status of each adapter layer in the model. + + This function returns a list of `TunerLayerStatus` dataclass instances, each of which contains the following + attributes: + + - `name` (`str`): + The name of the adapter layer, e.g. `model.encoder.block.0.layer.0.SelfAttention.q`. + - `module_type` (`str`): + The type of the adapter layer, e.g. `lora.Linear`. + - `enabled` (`bool`): + Whether the adapter layer is enabled. + - `active_adapters` (`list[str]`): + The names of the active adapters, if any, e.g. `["default"]`. + - `merged_adapters` (`list[str]`): + The names of the merged adapters, if any, e.g. `["default"]`. + - requires_grad : dict[str, bool | Literal["irregular"]] + The requires_grad status of the parameters for each adapter module. Ideally, it should be either `True` or + `False`. If the requires_grad status is not consistent across all parameters, the value will be set to + `"irregular"`. + - `available_adapters` (`list[str]`): + The names of the available adapters, e.g. `["default"]`. + - `devices` (`dict[str, list[str]]`): + The devices where the parameters of the given adapter are stored, e.g. `["cuda"]`. + - `quantization_backend` (`str` or `None`): + The name of the quantization backend, e.g. `"bnb 4bit"`, or `None` if not quantized. + + Args: + model ([Union[`~PeftModel`, `~transformers.PreTrainedModel`, `nn.Module`]]): + The model to get the adapter layer status from. + + Returns: + list[`peft.peft_model.TunerLayerStatus`]: + A list of dataclasses, each containing the status of the corresponding adapter layer. + + """ + if isinstance(model, PeftModel): + base_model = model.base_model + if not isinstance(base_model, BaseTuner): + raise TypeError( + "get_layer_status() got an invalid PeftModel instance; prefix tuning and adaption prompt are not " + "supported." + ) + else: + base_model = model + + layer_status: list[TunerLayerStatus] = [] + for name, module in base_model.named_modules(): + if not isinstance(module, (BaseTunerLayer, AuxiliaryTrainingWrapper)): + continue + if isinstance(module, TrainableTokensWrapper): + # Skip TrainableTokensWrapper, since it wraps TrainableTokensLayer, which is the actual PEFT layer we're + # interested in. + continue + + # determine if all submodules/parameters if this module require grad or not + mapping_requires_grad_list: dict[str, list[bool]] = collections.defaultdict(list) + for adapter_module_name in module.adapter_layer_names: + adapter_module = getattr(module, adapter_module_name) + if isinstance(adapter_module, torch.nn.ModuleDict): + for key, submodule in adapter_module.items(): + for param in submodule.parameters(): + mapping_requires_grad_list[key].append(param.requires_grad) + elif isinstance(adapter_module, torch.nn.ParameterDict): + for key, param in adapter_module.items(): + mapping_requires_grad_list[key].append(param.requires_grad) + else: + # strange, we don't know how to handle this, ignore for now + pass + + def check_irrgular(vals: list[bool]) -> bool | Literal["irregular"]: + if all(vals): + return True + if not any(vals): + return False + return "irregular" + + requires_grad = {key: check_irrgular(vals) for key, vals in mapping_requires_grad_list.items()} + + devices_dd = collections.defaultdict(list) + for adapter_module_name in module.adapter_layer_names + module.other_param_names: + adapter_module = getattr(module, adapter_module_name) + if isinstance(adapter_module, torch.nn.ModuleDict): + for key, submodule in adapter_module.items(): + devices_dd[key].extend([param.device.type for param in submodule.parameters()]) + elif isinstance(adapter_module, torch.nn.ParameterDict) or ( + adapter_module.__class__.__name__ == "BufferDict" + ): # VeRA + for key, param in adapter_module.items(): + devices_dd[key].append(param.device.type) + devices = {key: sorted(set(val)) for key, val in devices_dd.items()} + + quantization_backend = getattr(module, "quantization_backend", None) + quantization_backend_name = quantization_backend.backend_name if quantization_backend is not None else None + + status = TunerLayerStatus( + name=name, + module_type=repr(module).partition("(")[0], + enabled=not module.disable_adapters, + active_adapters=module.active_adapters, + merged_adapters=module.merged_adapters, + requires_grad=requires_grad, + available_adapters=sorted(module._get_available_adapters()), + devices=devices, + quantization_backend=quantization_backend_name, + ) + layer_status.append(status) + + if not layer_status: + raise ValueError( + "No adapter layers found in the model, please ensure that it's a PEFT model or that you have PEFT adapters " + "injected in the model." + ) + + return layer_status + + +@dataclass +class TunerModelStatus: + base_model_type: str + adapter_model_type: str + peft_types: dict[str, str] + trainable_params: int + total_params: int + num_adapter_layers: int + enabled: bool | Literal["irregular"] + active_adapters: list[str] | Literal["irregular"] + merged_adapters: list[str] | Literal["irregular"] + requires_grad: dict[str, bool | Literal["irregular"]] + available_adapters: list[str] + devices: dict[str, list[str]] + quantization_backend: str | None | Literal["irregular"] + + +def get_model_status(model: torch.nn.Module) -> TunerModelStatus: + """Get the status of tuners of the model. + + This function returns a `TunerModelStatus` dataclass instance, which contains the following attributes: + + - `base_model_type` (`str`): + The type of the base model, e.g. `T5Model`. + - `adapter_model_type` (`str`): + The type of the adapter model, e.g. `LoraModel`. + - `peft_types` (`dict[str, str]`): + The mapping of adapter name to adapter type, e.g. `{"default": "LORA"}`. + - `trainable_params` (`int`): + The number of trainable parameters in the model. + - `total_params` (`int`): + The total number of parameters in the model. + - `num_adapter_layers` (`int`): + The number of adapter layers in the model. + - `enabled` (`bool`, `Literal["irregular"]`): + Whether all adapter layers are enabled. If some are enabled and some are not, this will be `"irregular"`. This + means that your model is in an inconsistent state and might not work as expected. + - `active_adapters` (`list[str]`, `Literal["irregular"]`): + The names of the active adapters. If the active adapters are not consistent across all layers, this will be + `"irregular"`, which means that your model is in an inconsistent state and might not work as expected. + - `merged_adapters` (`list[str]`, `Literal["irregular"]`): + The names of the merged adapters. If the merged adapters are not consistent across all layers, this will be + `"irregular"`, which means that your model is in an inconsistent state and might not work as expected. + - `requires_grad` (`dict[str, bool | Literal["irregular"]]`): + Whether for the given adapter, all adapter layers have `requires_grad` set to `True` or `False`. If there is a + mix, this will be set to `"irregular"`, which means that your model is in an inconsistent state and might not + work as expected. + - `available_adapters` (`list[str]`): + The names of the available adapters, e.g. `["default"]`. + - `devices` (`dict[str, list[str]]`): + The devices where the parameters of the given adapter are stored, e.g. `["cuda"]`. + - `quantization_backend` (`str`, `None`, `Literal["irregular"]`): + The name of the quantization backend, e.g. `"bnb 4bit"`, or `None` if not quantized. If the backend is not + consistent across all layers, this will be `"irregular"`. + + Args: + model ([Union[`~PeftModel`, `~transformers.PreTrainedModel`, `nn.Module`]]): + The model to get the adapter layer status from. + + Returns: + `peft.peft_model.TunerModelStatus`: + A dataclass containing the status of the model. + + """ + if isinstance(model, PeftModel): + if not isinstance(model.base_model, BaseTuner): + raise TypeError( + "get_model_status() got an invalid PeftModel instance; prefix tuning and adaption prompt are not " + "supported." + ) + base_model_type = model.get_base_model().__class__.__name__ + trainable_params, total_params = model.get_nb_trainable_parameters() + base_model = model.base_model + peft_types = {key: str(config.peft_type).partition(".")[-1] for key, config in base_model.peft_config.items()} + adapter_model_type = base_model.__class__.__name__ + elif isinstance(model, PreTrainedModel): + base_model_type = model.__class__.__name__ + trainable_params, total_params = PeftModel.get_nb_trainable_parameters(model) + base_model = model + peft_types = {} + adapter_model_type = "None" + else: + base_model_type = "other" + trainable_params, total_params = PeftModel.get_nb_trainable_parameters(model) + base_model = model + peft_types = {} + adapter_model_type = "None" + + layer_status = get_layer_status(model) + num_adapter_layers = len(layer_status) + + enabled_set: set[bool] = {status.enabled for status in layer_status} # must be {True}, {False}, or {True, False} + enabled: bool | Literal["irregular"] + if len(enabled_set) == 1: + enabled = enabled_set.pop() + else: + enabled = "irregular" + + available_adapters: list[str] = sorted(set().union(*(status.available_adapters for status in layer_status))) + + # ideally, active adapters should be consistent across all layers of the model, but we cannot guarantee it + all_active_adapters: set[tuple[str, ...]] = {tuple(status.active_adapters) for status in layer_status} + active_adapters: list[str] | Literal["irregular"] + if not all_active_adapters: + active_adapters = [] + elif len(all_active_adapters) == 1: + active_adapters = list(all_active_adapters.pop()) + else: + active_adapters = "irregular" + + # Here we determine what adapters are merged. This is not trivial because multiple adapters can be merged or not at + # the same time. Some layers may only have adapter A, some only adapter B, so it's not as easy as just checking + # which adapters are merged on each layer. + + # First, determine all adapters that are merged on at least on module. + merged_all: set[str] = set() + for status in layer_status: + merged_all.update(status.merged_adapters) + + # Next, check if on any layer, on of these adapters is not merged. + merged_adapters: list[str] | Literal["irregular"] = sorted(merged_all) + for status in layer_status: + unmerged = set(status.available_adapters) - set(status.merged_adapters) + if unmerged & merged_all: + # there is overlap between unmerged adapters and adapters that should be merged + merged_adapters = "irregular" + break + + # check status of requires_grad + # first, merge the values for all layers + requires_grad_all: dict[str, list[bool | Literal["irregular"]]] = collections.defaultdict(list) + for status in layer_status: + for key, val in status.requires_grad.items(): + requires_grad_all[key].append(val) + + # then, check if the values are consistent + def check_irrgular(vals: list[bool | Literal["irregular"]]) -> bool | Literal["irregular"]: + if all(val is True for val in vals): + return True + if all(val is False for val in vals): + return False + return "irregular" + + requires_grad = {key: check_irrgular(vals) for key, vals in requires_grad_all.items()} + + devices_dd = collections.defaultdict(list) + for status in layer_status: + for key, val in status.devices.items(): + devices_dd[key].extend(val) + devices = {key: sorted(set(val)) for key, val in devices_dd.items()} + + # check quant backend consistency + quantization_backends_set: set[str | None] = {status.quantization_backend for status in layer_status} + quantization_backend: str | None | Literal["irregular"] + if len(quantization_backends_set) == 1: + quantization_backend = quantization_backends_set.pop() + else: + quantization_backend = "irregular" + + adapter_model_status = TunerModelStatus( + base_model_type=base_model_type, + adapter_model_type=adapter_model_type, + peft_types=peft_types, + trainable_params=trainable_params, + total_params=total_params, + num_adapter_layers=num_adapter_layers, + enabled=enabled, + active_adapters=active_adapters, + merged_adapters=merged_adapters, + requires_grad=requires_grad, + available_adapters=available_adapters, + devices=devices, + quantization_backend=quantization_backend, + ) + return adapter_model_status diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/py.typed b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4900a71aa8374c7495341c33e1dffa4fddc8ee08 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/__init__.py @@ -0,0 +1,171 @@ +# 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 .adalora import AdaLoraConfig, AdaLoraModel +from .adamss import AdamssConfig, AdamssModel +from .adaption_prompt import AdaptionPromptConfig, AdaptionPromptModel +from .beft import BeftConfig, BeftModel +from .boft import BOFTConfig, BOFTModel +from .c3a import C3AConfig, C3AModel +from .cartridge import CartridgeConfig, CartridgeEncoder +from .cpt import CPTConfig, CPTEmbedding +from .delora import DeloraConfig, DeloraModel +from .fourierft import FourierFTConfig, FourierFTModel +from .gralora import GraloraConfig, GraloraModel +from .hira import HiraConfig, HiraModel +from .hra import HRAConfig, HRAModel +from .ia3 import IA3Config, IA3Model +from .lily import LilyConfig, LilyModel +from .ln_tuning import LNTuningConfig, LNTuningModel +from .loha import LoHaConfig, LoHaModel +from .lokr import LoKrConfig, LoKrModel +from .lora import ( + ArrowConfig, + BdLoraConfig, + EvaConfig, + LoftQConfig, + LoraConfig, + LoraGAConfig, + LoraModel, + LoraRuntimeConfig, + MontecloraConfig, + VeloraConfig, + convert_to_lora, + create_arrow_model, + get_eva_state_dict, + initialize_lora_eva_weights, + preprocess_loraga, + save_as_lora, +) +from .miss import MissConfig, MissModel +from .mixed import MixedModel +from .multitask_prompt_tuning import MultitaskPromptEmbedding, MultitaskPromptTuningConfig, MultitaskPromptTuningInit +from .oft import OFTConfig, OFTModel +from .osf import OSFConfig, OSFModel +from .p_tuning import PromptEncoder, PromptEncoderConfig, PromptEncoderReparameterizationType +from .peanut import PeanutConfig, PeanutModel +from .poly import PolyConfig, PolyModel +from .prefix_tuning import PrefixEncoder, PrefixTuningConfig +from .prompt_tuning import PromptEmbedding, PromptTuningConfig, PromptTuningInit +from .psoft import PsoftConfig, PsoftModel +from .pvera import PveraConfig, PveraModel +from .randlora import RandLoraConfig, RandLoraModel +from .road import RoadConfig, RoadModel +from .shira import ShiraConfig, ShiraModel +from .tinylora import TinyLoraConfig, TinyLoraModel +from .trainable_tokens import TrainableTokensConfig, TrainableTokensModel +from .vblora import VBLoRAConfig, VBLoRAModel +from .vera import VeraConfig, VeraModel +from .waveft import WaveFTConfig, WaveFTModel +from .xlora import XLoraConfig, XLoraModel + + +__all__ = [ + "AdaLoraConfig", + "AdaLoraModel", + "AdamssConfig", + "AdamssModel", + "AdaptionPromptConfig", + "AdaptionPromptModel", + "ArrowConfig", + "BOFTConfig", + "BOFTModel", + "BdLoraConfig", + "BeftConfig", + "BeftModel", + "C3AConfig", + "C3AModel", + "CPTConfig", + "CPTEmbedding", + "CartridgeConfig", + "CartridgeEncoder", + "DeloraConfig", + "DeloraModel", + "EvaConfig", + "FourierFTConfig", + "FourierFTModel", + "GraloraConfig", + "GraloraModel", + "HRAConfig", + "HRAModel", + "HiraConfig", + "HiraModel", + "IA3Config", + "IA3Model", + "LNTuningConfig", + "LNTuningModel", + "LilyConfig", + "LilyModel", + "LoHaConfig", + "LoHaModel", + "LoKrConfig", + "LoKrModel", + "LoftQConfig", + "LoraConfig", + "LoraGAConfig", + "LoraModel", + "LoraRuntimeConfig", + "MissConfig", + "MissModel", + "MixedModel", + "MontecloraConfig", + "MultitaskPromptEmbedding", + "MultitaskPromptTuningConfig", + "MultitaskPromptTuningInit", + "OFTConfig", + "OFTModel", + "OSFConfig", + "OSFModel", + "PeanutConfig", + "PeanutModel", + "PolyConfig", + "PolyModel", + "PrefixEncoder", + "PrefixTuningConfig", + "PromptEmbedding", + "PromptEncoder", + "PromptEncoderConfig", + "PromptEncoderReparameterizationType", + "PromptTuningConfig", + "PromptTuningInit", + "PsoftConfig", + "PsoftModel", + "PveraConfig", + "PveraModel", + "RandLoraConfig", + "RandLoraModel", + "RoadConfig", + "RoadModel", + "ShiraConfig", + "ShiraModel", + "TinyLoraConfig", + "TinyLoraModel", + "TrainableTokensConfig", + "TrainableTokensModel", + "VBLoRAConfig", + "VBLoRAModel", + "VeloraConfig", + "VeraConfig", + "VeraModel", + "WaveFTConfig", + "WaveFTModel", + "XLoraConfig", + "XLoraModel", + "convert_to_lora", + "create_arrow_model", + "get_eva_state_dict", + "initialize_lora_eva_weights", + "preprocess_loraga", + "save_as_lora", +] diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/_buffer_dict.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/_buffer_dict.py new file mode 100644 index 0000000000000000000000000000000000000000..16e8fae5ac164ee952780fefc1e247f08ff54909 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/_buffer_dict.py @@ -0,0 +1,159 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +# Adapted from https://botorch.org/api/_modules/botorch/utils/torch.html + +# TODO: To be removed once (if) https://github.com/pytorch/pytorch/pull/37385 lands + +from __future__ import annotations + +import collections +from collections import OrderedDict + +import torch +from torch.nn import Module + + +class BufferDict(Module): + r""" + Holds buffers in a dictionary. + + BufferDict can be indexed like a regular Python dictionary, but buffers it contains are properly registered, and + will be visible by all Module methods. `torch.nn.BufferDict` is an **ordered** dictionary that respects + + * the order of insertion, and + * in `torch.nn.BufferDict.update`, the order of the merged `OrderedDict` or another `torch.nn.BufferDict` (the + argument to `torch.nn.BufferDict.update`). + + Note that `torch.nn.BufferDict.update` with other unordered mapping types (e.g., Python's plain `dict`) does not + preserve the order of the merged mapping. + + Args: + buffers (iterable, optional): + a mapping (dictionary) of (string : `torch.Tensor`) or an iterable of key-value pairs of type (string, + `torch.Tensor`) + + ```python + class MyModule(nn.Module): + def __init__(self): + super().__init__() + self.buffers = nn.BufferDict({"left": torch.randn(5, 10), "right": torch.randn(5, 10)}) + + def forward(self, x, choice): + x = self.buffers[choice].mm(x) + return x + ``` + """ + + def __init__(self, buffers=None, persistent: bool = False): + r""" + Args: + buffers (`dict`): + A mapping (dictionary) from string to `torch.Tensor`, or an iterable of key-value pairs of type + (string, `torch.Tensor`). + """ + super().__init__() + self.persistent = persistent + + if buffers is not None: + self.update(buffers) + + def __getitem__(self, key): + return self._buffers[key] + + def __setitem__(self, key, buffer): + self.register_buffer(key, buffer, persistent=self.persistent) + + def __delitem__(self, key): + del self._buffers[key] + + def __len__(self): + return len(self._buffers) + + def __iter__(self): + return iter(self._buffers.keys()) + + def __contains__(self, key): + return key in self._buffers + + def clear(self): + """Remove all items from the BufferDict.""" + self._buffers.clear() + + def pop(self, key): + r"""Remove key from the BufferDict and return its buffer. + + Args: + key (`str`): + Key to pop from the BufferDict + """ + v = self[key] + del self[key] + return v + + def keys(self): + r"""Return an iterable of the BufferDict keys.""" + return self._buffers.keys() + + def items(self): + r"""Return an iterable of the BufferDict key/value pairs.""" + return self._buffers.items() + + def values(self): + r"""Return an iterable of the BufferDict values.""" + return self._buffers.values() + + def update(self, buffers): + r""" + Update the `torch.nn.BufferDict` with the key-value pairs from a mapping or an iterable, overwriting existing + keys. + + Note: + If `buffers` is an `OrderedDict`, a `torch.nn.BufferDict`, or an iterable of key-value pairs, the order of + new elements in it is preserved. + + Args: + buffers (iterable): + a mapping (dictionary) from string to `torch.Tensor`, or an iterable of key-value pairs of type + (string, `torch.Tensor`). + """ + if not isinstance(buffers, collections.abc.Iterable): + raise TypeError( + "BuffersDict.update should be called with an " + "iterable of key/value pairs, but got " + type(buffers).__name__ + ) + + if isinstance(buffers, (OrderedDict, BufferDict)): + for key, buffer in buffers.items(): + self[key] = buffer + elif isinstance(buffers, collections.abc.Mapping): + for key, buffer in sorted(buffers.items()): + self[key] = buffer + else: + for j, p in enumerate(buffers): + if not isinstance(p, collections.abc.Iterable): + raise TypeError( + "BufferDict update sequence element #" + str(j) + " should be Iterable; is" + type(p).__name__ + ) + if not len(p) == 2: + raise ValueError( + "BufferDict update sequence element " + "#" + str(j) + " has length " + str(len(p)) + "; 2 is required" + ) + self[p[0]] = p[1] + + def extra_repr(self): + child_lines = [] + for k, p in self._buffers.items(): + size_str = "x".join(str(size) for size in p.size()) + device_type = p.device.type + device_str = "" if device_type == "cpu" else f" ({device_type.upper()} {p.get_device()})" + parastr = f"Buffer containing: [{torch.typename(p)} of size {size_str}{device_str}]" + child_lines.append(" (" + k + "): " + parastr) + tmpstr = "\n".join(child_lines) + return tmpstr + + def __call__(self, input): + raise RuntimeError("BufferDict should not be called.") diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adalora/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adalora/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f20fed9c1e6a779d5e9d3d2186bd758b6a70cdbb --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adalora/__init__.py @@ -0,0 +1,51 @@ +# 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.utils import register_peft_method + +from .config import AdaLoraConfig +from .gptq import SVDQuantLinear +from .layer import AdaLoraLayer, RankAllocator, SVDConv2d, SVDLinear +from .model import AdaLoraModel + + +__all__ = [ + "AdaLoraConfig", + "AdaLoraLayer", + "AdaLoraModel", + "RankAllocator", + "SVDConv2d", + "SVDLinear", + "SVDQuantLinear", +] + + +register_peft_method( + name="adalora", config_cls=AdaLoraConfig, model_cls=AdaLoraModel, prefix="lora_", is_mixed_compatible=True +) + + +def __getattr__(name): + if (name == "SVDLinear8bitLt") and is_bnb_available(): + from .bnb import SVDLinear8bitLt + + return SVDLinear8bitLt + + if (name == "SVDLinear4bit") and is_bnb_4bit_available(): + from .bnb import SVDLinear4bit + + return SVDLinear4bit + + raise AttributeError(f"module {__name__} has no attribute {name}") diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adalora/bnb.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adalora/bnb.py new file mode 100644 index 0000000000000000000000000000000000000000..52b43f0dff0e62785e216d8736088098f87a9857 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adalora/bnb.py @@ -0,0 +1,142 @@ +# 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 + +import torch + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available + +from .config import AdaLoraConfig +from .layer import AdaLoraLayer + + +if is_bnb_available(): + + class SVDLinear8bitLt(torch.nn.Module, AdaLoraLayer): + # Low-rank matrix for SVD-based adaptation + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + config: AdaLoraConfig, + r: int = 0, + lora_alpha: int = 1, + **kwargs, + ) -> None: + super().__init__() + AdaLoraLayer.__init__(self, base_layer) + # Freezing the pre-trained weight matrix + self.get_base_layer().weight.requires_grad = False + + self._active_adapter = adapter_name + self.update_layer(adapter_name, r, lora_alpha, config=config) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + # note: no check for self.merged because merging is not supported (yet) + 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 + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + if x.dtype != torch.float32: + x = x.float() + + lora_A = self.lora_A[active_adapter] + lora_B = self.lora_B[active_adapter] + lora_E = self.lora_E[active_adapter] + dropout = self.lora_dropout[active_adapter] + scaling = self.scaling[active_adapter] + ranknum = self.ranknum[active_adapter] + 1e-5 + + output = dropout(x) @ (lora_A * lora_E).T @ lora_B.T + if requires_conversion: + output = output.to(expected_dtype) + output = output * scaling / ranknum + # inplace operation on view is forbidden for MatMul8bitLtBackward, so avoid it + result = result + output + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "adalora." + rep + + +if is_bnb_4bit_available(): + + class SVDLinear4bit(torch.nn.Module, AdaLoraLayer): + # Low-rank matrix for SVD-based adaptation + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + config: AdaLoraConfig, + r: int = 0, + lora_alpha: int = 1, + **kwargs, + ) -> None: + super().__init__() + AdaLoraLayer.__init__(self, base_layer) + # Freezing the pre-trained weight matrix + self.get_base_layer().weight.requires_grad = False + + self._active_adapter = adapter_name + self.update_layer(adapter_name, r, lora_alpha, config=config) + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + # note: no check for self.merged because merging is not supported (yet) + result = self.base_layer(x, *args, **kwargs) + + if self.disable_adapters: + return result + + # 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] + lora_E = self.lora_E[active_adapter] + dropout = self.lora_dropout[active_adapter] + scaling = self.scaling[active_adapter] + ranknum = self.ranknum[active_adapter] + 1e-5 + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + x = self._cast_input_dtype(x, lora_A.dtype) + + output = dropout(x) @ (lora_A * lora_E).T @ lora_B.T + if requires_conversion: + output = output.to(expected_dtype) + output = output * scaling / ranknum + result += output + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "adalora." + rep diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adalora/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adalora/config.py new file mode 100644 index 0000000000000000000000000000000000000000..567108ac15d0785ca43b1eae95f644df00c97d39 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adalora/config.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. + +import warnings +from dataclasses import dataclass, field +from typing import Optional + +from peft.tuners.lora import LoraConfig +from peft.utils import PeftType + + +@dataclass +class AdaLoraConfig(LoraConfig): + """ + This is the configuration class to store the configuration of a [`AdaLoraModel`]. + + AdaLoRA has three phases defined by `tinit`, `tfinal` and `total_step`. + + The initial phase can be understood as a step for pre-training the adapters so that when reducing their rank, there + is already some information encoded that can be reduced instead of random matrices. This phase is defined by + supplying `tinit`. + + After the initial phase is over (`tinit` steps have passed) and the final phase has not begun, AdaLoRA reduces the + budget of how much rank each layer is allowed to have with each step. This is where the reduction of rank is + happening. This goes on until `total_step - tfinal` steps are reached. + + The last phase, beginning once `total_step - tfinal` steps are reached, does not change the layer ranks anymore but + fine-tunes the reduced-rank layers that resulted from the previous phase. + + A practical example: `tinit` is 10, `tfinal` is 20, `total_step` is 100. We spend 10 steps doing pre-training + without rank reduction because our budget is constant (init phase), then we spend 80 (100-20) steps in the + reduction phase where our budget decreases step-wise and, finally, 20 steps in the final fine-tuning stage without + reduction. + + Args: + target_r (`int`): The target average rank of incremental matrix. + init_r (`int`): The initial rank for each incremental matrix. + tinit (`int`): The steps of initial fine-tuning warmup. + tfinal (`int`): The number of steps of final fine-tuning. + deltaT (`int`): The time internval between two budget allocations. + beta1 (`float`): The hyperparameter of EMA for sensitivity smoothing. + beta2 (`float`): The hyperparameter of EMA for undertainty quantification. + orth_reg_weight (`float`): The coefficient of orthogonal regularization. + total_step (`int`): The total training steps that should be specified before training. + rank_pattern (`list`): The allocated rank for each weight matrix by RankAllocator. + """ + + target_r: int = field(default=8, metadata={"help": "Target Lora matrix dimension."}) + init_r: int = field(default=12, metadata={"help": "Initial Lora matrix dimension."}) + tinit: int = field(default=0, metadata={"help": "The steps of initial warmup."}) + tfinal: int = field(default=0, metadata={"help": "The steps of final warmup."}) + deltaT: int = field(default=1, metadata={"help": "Step interval of rank allocation."}) + beta1: float = field(default=0.85, metadata={"help": "Hyperparameter of EMA."}) + beta2: float = field(default=0.85, metadata={"help": "Hyperparameter of EMA."}) + orth_reg_weight: float = field(default=0.5, metadata={"help": "The orthogonal regularization coefficient."}) + total_step: Optional[int] = field(default=None, metadata={"help": "The total training steps."}) + rank_pattern: Optional[dict] = field(default=None, metadata={"help": "The saved rank pattern."}) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.ADALORA + + if self.use_dora: + raise ValueError(f"{self.peft_type} does not support DoRA.") + + if self.loftq_config: + raise ValueError(f"{self.peft_type} does not support LOFTQ.") + + 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 + ) + # if target_modules is a regex expression, then layers_to_transform should be None + if isinstance(self.target_modules, str) and self.layers_to_transform is not None: + raise ValueError("`layers_to_transform` cannot be used when `target_modules` is a str.") + + # 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. ") + + # Check if 'r' has been set to a non-default value + if self.r != 8: # 8 is the default value for 'r' in LoraConfig + warnings.warn( + "Note that `r` is not used in AdaLora and will be ignored." + "If you intended to set the initial rank, use `init_r` instead." + ) + + if self.total_step is None or self.total_step <= 0: + raise ValueError("AdaLoRA does not work when `total_step` is None, supply a value > 0.") + + if self.tinit >= (self.total_step - self.tfinal): + raise ValueError( + "The supplied schedule values don't allow for a budgeting phase. Decrease `tfinal`/`tinit` or " + "increase `total_step`." + ) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adalora/gptq.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adalora/gptq.py new file mode 100644 index 0000000000000000000000000000000000000000..cf7cb0ed533bbef7e5c6ef204136c4b68744707d --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adalora/gptq.py @@ -0,0 +1,71 @@ +# 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 .config import AdaLoraConfig +from .layer import AdaLoraLayer + + +class SVDQuantLinear(torch.nn.Module, AdaLoraLayer): + def __init__( + self, + base_layer, + adapter_name, + config: AdaLoraConfig, + r: int = 0, + lora_alpha: int = 1, + **kwargs, + ) -> None: + super().__init__() + AdaLoraLayer.__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) -> 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] + lora_E = self.lora_E[active_adapter] + dropout = self.lora_dropout[active_adapter] + scaling = self.scaling[active_adapter] + ranknum = self.ranknum[active_adapter] + 1e-5 + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + x = self._cast_input_dtype(x, torch.float32) + + output = (dropout(x) @ (lora_A * lora_E).T @ lora_B.T) * scaling / ranknum + # TODO: here, the dtype conversion is applied on the *whole expression*, + # not the intermediate result, unlike for SVDLinear8bitLT and + # SVDLinear4bit, is that correct? + if requires_conversion: + output = output.to(expected_dtype) + result += output + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "adalora." + rep diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adalora/layer.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adalora/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..4cc7a62f59eb08081cbe72dedb5cef7560099eb5 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adalora/layer.py @@ -0,0 +1,515 @@ +# 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 warnings +from typing import Any, Optional + +import packaging +import torch +import transformers +from torch import nn + +from peft.tuners.lora import LoraLayer +from peft.tuners.tuners_utils import check_adapters_to_merge +from peft.utils import transpose +from peft.utils.integrations import _skip_init_on_device + +from .config import AdaLoraConfig + + +if packaging.version.parse(transformers.__version__) >= packaging.version.parse("4.33.0"): + from transformers.integrations import deepspeed_config +else: + from transformers.deepspeed import deepspeed_config + + +class AdaLoraLayer(LoraLayer): + # List all names of layers that may contain adapter weights + # Note: ranknum doesn't need to be included as it is not an nn.Module + adapter_layer_names = ("lora_A", "lora_B", "lora_E", "lora_embedding_A", "lora_embedding_B") + # All names of other parameters that may contain adapter-related parameters + other_param_names = ("r", "lora_alpha", "scaling", "lora_dropout", "ranknum") + + def __init__(self, base_layer: nn.Module) -> None: + super().__init__(base_layer) + self.lora_E = nn.ParameterDict({}) + self.lora_A = nn.ParameterDict({}) + self.lora_B = nn.ParameterDict({}) + self.ranknum = nn.ParameterDict({}) + + def update_layer(self, adapter_name: str, r: int, lora_alpha: int, config: AdaLoraConfig, **kwargs) -> None: + lora_dropout = config.lora_dropout + init_lora_weights = config.init_lora_weights + inference_mode = config.inference_mode + if r < 0: + # note: r == 0 is allowed for AdaLora, see #1539 + raise ValueError(f"`r` should be a positive integer or 0, but the value passed is {r}") + + self.r[adapter_name] = r + self.lora_alpha[adapter_name] = lora_alpha + if lora_dropout > 0.0: + lora_dropout_layer = nn.Dropout(p=lora_dropout) + else: + lora_dropout_layer = nn.Identity() + + self.lora_dropout[adapter_name] = lora_dropout_layer + # Actual trainable parameters + # Right singular vectors + self.lora_A[adapter_name] = nn.Parameter(torch.randn(r, self.in_features)) + # Singular values + self.lora_E[adapter_name] = nn.Parameter(torch.randn(r, 1)) + # Left singular vectors + self.lora_B[adapter_name] = nn.Parameter(torch.randn(self.out_features, r)) + # The current rank. ranknum is deterministic (always set to float(r)) and is not saved + # in the adapter state_dict, so under low_cpu_mem_usage=True it can't be restored from a + # checkpoint and must stay off the meta device. Two places need to skip the meta dispatch: + # 1) creation, otherwise the Parameter is registered on meta from the start; + # 2) the subsequent _move_adapter_to_device_of_base_layer call, because moving the + # ParameterDict entry re-registers it via Module.__setattr__ → register_parameter, + # which inside init_empty_weights would send the tensor back to meta. + with _skip_init_on_device(): + self.ranknum[adapter_name] = nn.Parameter(torch.randn(1), requires_grad=False) + self.ranknum[adapter_name].data.fill_(float(r)) + self.ranknum[adapter_name].requires_grad = False + self.scaling[adapter_name] = lora_alpha if lora_alpha > 0 else float(r) + if init_lora_weights: + self.reset_lora_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_lora_parameters(self, adapter_name): + if adapter_name in self.lora_A.keys(): + nn.init.zeros_(self.lora_E[adapter_name]) + nn.init.normal_(self.lora_A[adapter_name], mean=0.0, std=0.02) + nn.init.normal_(self.lora_B[adapter_name], mean=0.0, std=0.02) + + +class SVDLinear(nn.Module, AdaLoraLayer): + # SVD-based adaptation by a dense layer + def __init__( + self, + base_layer: nn.Module, + adapter_name: str, + config: AdaLoraConfig, + r: int = 0, + lora_alpha: int = 1, + **kwargs, + ) -> None: + super().__init__() + AdaLoraLayer.__init__(self, base_layer) + # Freezing the pre-trained weight matrix + self.get_base_layer().weight.requires_grad = False + + self.fan_in_fan_out = config.fan_in_fan_out + self._active_adapter = adapter_name + self.update_layer(adapter_name, r, lora_alpha, config=config) + + 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: + base_layer = self.get_base_layer() + if active_adapter in self.lora_A.keys(): + 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: + """ + 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 in self.lora_A.keys(): + self.get_base_layer().weight.data -= self.get_delta_weight(active_adapter) + + def get_delta_weight(self, adapter) -> torch.Tensor: + return ( + transpose(self.lora_B[adapter] @ (self.lora_A[adapter] * self.lora_E[adapter]), self.fan_in_fan_out) + * self.scaling[adapter] + / (self.ranknum[adapter] + 1e-5) + ) + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> 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) + 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] + lora_E = self.lora_E[active_adapter] + dropout = self.lora_dropout[active_adapter] + scaling = self.scaling[active_adapter] + ranknum = self.ranknum[active_adapter] + 1e-5 + + x = self._cast_input_dtype(x, lora_A.dtype) + result += (dropout(x) @ (lora_A * lora_E).T @ lora_B.T) * scaling / ranknum + + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "adalora." + rep + + +class SVDConv2d(nn.Module, AdaLoraLayer): + # SVD-based adaptation by a Conv2d layer + def __init__( + self, + base_layer: nn.Module, + adapter_name: str, + config: AdaLoraConfig, + r: int = 0, + lora_alpha: int = 1, + **kwargs, + ) -> None: + super().__init__() + AdaLoraLayer.__init__(self, base_layer) + self.get_base_layer().weight.requires_grad = False + self._active_adapter = adapter_name + self.update_layer(adapter_name, r, lora_alpha, config=config) + + def update_layer(self, adapter_name: str, r: int, lora_alpha: int, config: AdaLoraConfig, **kwargs) -> None: + lora_dropout = config.lora_dropout + init_lora_weights = config.init_lora_weights + inference_mode = config.inference_mode + if r < 0: + raise ValueError(f"`r` should be a positive integer or 0, but the value passed is {r}") + + self.r[adapter_name] = r + self.lora_alpha[adapter_name] = lora_alpha + if lora_dropout > 0.0: + lora_dropout_layer = nn.Dropout(p=lora_dropout) + else: + lora_dropout_layer = nn.Identity() + self.lora_dropout[adapter_name] = lora_dropout_layer + + base = self.get_base_layer() + k = base.kernel_size[0] * base.kernel_size[1] + # Right singular vectors: (r, in_channels * kH * kW) + self.lora_A[adapter_name] = nn.Parameter(torch.randn(r, self.in_features * k)) + # Singular values: (r, 1) + self.lora_E[adapter_name] = nn.Parameter(torch.randn(r, 1)) + # Left singular vectors: (out_channels, r) + self.lora_B[adapter_name] = nn.Parameter(torch.randn(self.out_features, r)) + # Current rank — see note in AdaLoraLayer.update_layer about _skip_init_on_device. + with _skip_init_on_device(): + self.ranknum[adapter_name] = nn.Parameter(torch.randn(1), requires_grad=False) + self.ranknum[adapter_name].data.fill_(float(r)) + self.ranknum[adapter_name].requires_grad = False + self.scaling[adapter_name] = lora_alpha if lora_alpha > 0 else float(r) + if init_lora_weights: + self.reset_lora_parameters(adapter_name) + + 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: + return + + for active_adapter in adapter_names: + base_layer = self.get_base_layer() + if active_adapter in self.lora_A.keys(): + if safe_merge: + 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: + """ + 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 in self.lora_A.keys(): + self.get_base_layer().weight.data -= self.get_delta_weight(active_adapter) + + def get_delta_weight(self, adapter) -> torch.Tensor: + delta = ( + self.lora_B[adapter] + @ (self.lora_A[adapter] * self.lora_E[adapter]) + * self.scaling[adapter] + / (self.ranknum[adapter] + 1e-5) + ) + return delta.reshape(self.get_base_layer().weight.shape) + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> 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) + 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] + lora_E = self.lora_E[active_adapter] + dropout = self.lora_dropout[active_adapter] + scaling = self.scaling[active_adapter] + ranknum = self.ranknum[active_adapter] + 1e-5 + + x = self._cast_input_dtype(x, lora_A.dtype) + base = self.get_base_layer() + delta_w = (lora_B @ (lora_A * lora_E) * scaling / ranknum).reshape(base.weight.shape) + # Use in-place add so result keeps its original dtype (matches SVDLinear); + # otherwise result would be upcast to lora_A.dtype and break subsequent fp16/bf16 ops. + result += nn.functional.conv2d( + dropout(x), + delta_w, + stride=base.stride, + padding=base.padding, + dilation=base.dilation, + groups=base.groups, + ) + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "adalora." + rep + + +class RankAllocator: + """ + The RankAllocator for AdaLoraModel. Paper: https://openreview.net/pdf?id=lq62uWRJjiY + + Args: + config ([`AdaLoraConfig`]): The configuration of the AdaLora model. + model: the model that we apply AdaLoRA to. + + """ + + def __init__(self, model, peft_config, adapter_name): + self.peft_config = peft_config + self.adapter_name = adapter_name + self.beta1 = peft_config.beta1 + self.beta2 = peft_config.beta2 + assert self.beta1 > 0 and self.beta1 < 1 + assert self.beta2 > 0 and self.beta2 < 1 + + self.reset_ipt() + self._set_budget_scheduler(model) + + def set_total_step(self, total_step): + self.peft_config.total_step = total_step + + def reset_ipt(self): + self.ipt = {} + self.exp_avg_ipt = {} + self.exp_avg_unc = {} + + def _set_budget_scheduler(self, model): + self.init_bgt = 0 + self.name_set = set() + for n, p in model.named_parameters(): + if f"lora_A.{self.adapter_name}" in n: + self.init_bgt += p.size(0) + self.name_set.add(n.replace("lora_A", "%s")) + self.name_set = sorted(self.name_set) + # The total final rank budget + self.target_bgt = self.peft_config.target_r * len(self.name_set) + + def budget_schedule(self, step: int): + tinit = self.peft_config.tinit + tfinal = self.peft_config.tfinal + total_step = self.peft_config.total_step + # Initial warmup + if step <= tinit: + budget = self.init_bgt + mask_ind = False + # Final fine-tuning + elif step > total_step - tfinal: + budget = self.target_bgt + mask_ind = True + else: + # Budget decreasing with a cubic scheduler + mul_coeff = 1 - (step - tinit) / (total_step - tfinal - tinit) + budget = int((self.init_bgt - self.target_bgt) * (mul_coeff**3) + self.target_bgt) + mask_ind = step % self.peft_config.deltaT == 0 + return budget, mask_ind + + def update_ipt(self, model): + # Update the sensitivity and uncertainty for every weight + for n, p in model.named_parameters(): + if "lora_" in n and self.adapter_name in n: + if n not in self.ipt: + self.ipt[n] = torch.zeros_like(p) + self.exp_avg_ipt[n] = torch.zeros_like(p) + self.exp_avg_unc[n] = torch.zeros_like(p) + with torch.no_grad(): + if deepspeed_config() is not None: + import deepspeed + + grad = deepspeed.utils.safe_get_full_grad(p) + self.ipt[n] = (p * grad).abs().detach() + else: + self.ipt[n] = (p * p.grad).abs().detach() + # Sensitivity smoothing + self.exp_avg_ipt[n] = self.beta1 * self.exp_avg_ipt[n] + (1 - self.beta1) * self.ipt[n] + # Uncertainty quantification + self.exp_avg_unc[n] = ( + self.beta2 * self.exp_avg_unc[n] + (1 - self.beta2) * (self.ipt[n] - self.exp_avg_ipt[n]).abs() + ) + + def _element_score(self, n): + return self.exp_avg_ipt[n] * self.exp_avg_unc[n] + + def _combine_ipt(self, ipt_E, ipt_AB): + ipt_AB = ipt_AB.sum(dim=1, keepdim=False) + sum_ipt = ipt_E.view(-1) + ipt_AB.view(-1) + return sum_ipt + + def mask_to_budget(self, model, budget): + value_ipt = {} + vector_ipt = {} + triplet_ipt = {} + # Get the importance score for A, E, B + for n, p in model.named_parameters(): + if f"lora_A.{self.adapter_name}" in n: + entry_ipt = self._element_score(n) + comb_ipt = torch.mean(entry_ipt, dim=1, keepdim=True) + name_m = n.replace("lora_A", "%s") + if name_m not in vector_ipt: + vector_ipt[name_m] = [comb_ipt] + else: + vector_ipt[name_m].append(comb_ipt) + if f"lora_B.{self.adapter_name}" in n: + entry_ipt = self._element_score(n) + comb_ipt = torch.mean(entry_ipt, dim=0, keepdim=False).view(-1, 1) + name_m = n.replace("lora_B", "%s") + if name_m not in vector_ipt: + vector_ipt[name_m] = [comb_ipt] + else: + vector_ipt[name_m].append(comb_ipt) + if f"lora_E.{self.adapter_name}" in n: + entry_ipt = self._element_score(n) + name_m = n.replace("lora_E", "%s") + value_ipt[name_m] = entry_ipt + + all_score = [] + # Calculate the score for each triplet + for name_m in vector_ipt: + ipt_E = value_ipt[name_m] + ipt_AB = torch.cat(vector_ipt[name_m], dim=1) + sum_ipt = self._combine_ipt(ipt_E, ipt_AB) + name_E = name_m % "lora_E" + triplet_ipt[name_E] = sum_ipt.view(-1, 1) + all_score.append(sum_ipt.view(-1)) + + # Get the threshold by ranking ipt + mask_threshold = torch.kthvalue( + torch.cat(all_score), + k=self.init_bgt - budget, + )[0].item() + + rank_pattern = {} + # Mask the unimportant triplets + with torch.no_grad(): + for n, p in model.named_parameters(): + if f"lora_E.{self.adapter_name}" in n: + p.masked_fill_(triplet_ipt[n] <= mask_threshold, 0.0) + rank_pattern[n] = (~(triplet_ipt[n] <= mask_threshold)).view(-1).tolist() + return rank_pattern + + def update_and_allocate(self, model, global_step, force_mask=False): + # # Update the importance score and allocate the budget + if global_step < self.peft_config.total_step - self.peft_config.tfinal: + self.update_ipt(model) + budget, mask_ind = self.budget_schedule(global_step) + # Allocate the budget according to importance scores + if mask_ind or force_mask: + rank_pattern = self.mask_to_budget(model, budget) + else: + rank_pattern = None + return budget, rank_pattern + + def mask_using_rank_pattern(self, model, rank_pattern): + # Mask the unimportant triplets + is_adapter_name_truncated = False + if self.adapter_name not in next(iter(rank_pattern.keys())): + is_adapter_name_truncated = True + + with torch.no_grad(): + for n, p in model.named_parameters(): + if f"lora_E.{self.adapter_name}" in n: + key = n if not is_adapter_name_truncated else n.replace(f".{self.adapter_name}", "") + mask = torch.Tensor(rank_pattern[key]).unsqueeze(-1).to(p.device) + p.masked_fill_(~mask.bool(), 0.0) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adalora/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adalora/model.py new file mode 100644 index 0000000000000000000000000000000000000000..7937ab77913cc2207d2bc61210fe377c365ac864 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adalora/model.py @@ -0,0 +1,349 @@ +# 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 warnings + +import torch +from transformers.pytorch_utils import Conv1D + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available +from peft.tuners.lora import LoraConfig, LoraModel +from peft.tuners.tuners_utils import BaseTunerLayer, get_device_map +from peft.utils import ( + TRANSFORMERS_MODELS_TO_ADALORA_TARGET_MODULES_MAPPING, + _freeze_adapter, + _get_submodules, + get_gptqmodel_quant_linear, + get_quantization_config, +) +from peft.utils.integrations import gather_params_ctx + +from .gptq import SVDQuantLinear +from .layer import AdaLoraLayer, RankAllocator, SVDConv2d, SVDLinear + + +class AdaLoraModel(LoraModel): + """ + Creates AdaLoRA (Adaptive LoRA) model from a pretrained transformers model. Paper: + https://openreview.net/forum?id=lq62uWRJjiY + + Args: + model ([`transformers.PreTrainedModel`]): The model to be adapted. + config ([`AdaLoraConfig`]): The configuration of the AdaLora 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 AdaLora model. + + Example: + ```py + >>> from transformers import AutoModelForSeq2SeqLM + >>> from peft import AdaLoraConfig, get_peft_model + + >>> config = AdaLoraConfig( + ... peft_type="ADALORA", + ... task_type="SEQ_2_SEQ_LM", + ... init_r=12, + ... lora_alpha=32, + ... target_modules=["q", "v"], + ... lora_dropout=0.01, + ... total_step=1000, + ... ) + >>> model = AutoModelForSeq2SeqLM.from_pretrained("t5-base") + >>> adalora_model = get_peft_model(model, config) + ``` + + **Attributes**: + - **model** ([`transformers.PreTrainedModel`]) -- The model to be adapted. + - **peft_config** ([`AdaLoraConfig`]): The configuration of the AdaLora model. + """ + + # Note: don't redefine prefix or tuner_layer_cls here, it should be inherited from LoraModel + target_module_mapping = TRANSFORMERS_MODELS_TO_ADALORA_TARGET_MODULES_MAPPING + + def __init__(self, model, config, adapter_name, **kwargs): + super().__init__(model, config, adapter_name, **kwargs) + + traininable_mode_counter = 0 + for peft_config in self.peft_config.values(): + if not peft_config.inference_mode: + traininable_mode_counter += 1 + + if traininable_mode_counter > 1: + raise ValueError( + "AdaLoraModel supports only 1 trainable adapter. " + "When using multiple adapters, set inference_mode to True for all adapters except the one you want to train." + ) + + if self.peft_config[adapter_name].inference_mode: + _freeze_adapter(self.model, adapter_name) + else: + self.trainable_adapter_name = adapter_name + self.rankallocator = RankAllocator(self.model, self.peft_config[adapter_name], self.trainable_adapter_name) + + def _check_new_adapter_config(self, config: LoraConfig) -> 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) + + traininable_mode_counter = 0 + for config_ in self.peft_config.values(): + if not config_.inference_mode: + traininable_mode_counter += 1 + + if traininable_mode_counter > 1: + raise ValueError( + f"{self.__class__.__name__} supports only 1 trainable adapter. " + "When using multiple adapters, set inference_mode to True for all adapters except the one " + "you want to train." + ) + + def _create_and_replace( + self, + lora_config, + adapter_name, + target, + target_name, + parent, + current_key, + ): + kwargs = { + "r": lora_config.init_r, + "lora_alpha": lora_config.lora_alpha, + "loaded_in_8bit": getattr(self.model, "is_loaded_in_8bit", False), + "loaded_in_4bit": getattr(self.model, "is_loaded_in_4bit", False), + } + if (kwargs["loaded_in_8bit"] or kwargs["loaded_in_4bit"]) and not is_bnb_available(): + raise ImportError( + "To use AdaLora with 8-bit quantization, please install the `bitsandbytes` package. " + "You can install it with `pip install bitsandbytes`." + ) + + quantization_config = get_quantization_config(self.model, method="gptq") + if quantization_config is not None: + kwargs["gptq_quantization_config"] = quantization_config + + # If it is not an AdaLoraLayer, create a new module, else update it with new adapters + if not isinstance(target, AdaLoraLayer): + device_map = get_device_map(self.model) + new_module = self._create_new_module(lora_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, + lora_config.init_r, + lora_config.lora_alpha, + config=lora_config, + ) + + @staticmethod + def _create_new_module(lora_config, adapter_name, target, device_map=None, **kwargs): + # avoid eager bnb import + if is_bnb_available(): + import bitsandbytes as bnb + + from .bnb import SVDLinear8bitLt + if is_bnb_4bit_available(): + from .bnb import SVDLinear4bit + + gptq_quantization_config = kwargs.get("gptq_quantization_config", None) + + QuantLinear = get_gptqmodel_quant_linear(gptq_quantization_config, device_map=device_map) + + loaded_in_8bit = kwargs.pop("loaded_in_8bit", False) + loaded_in_4bit = kwargs.pop("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): + kwargs.update( + { + "has_fp16_weights": target_base_layer.state.has_fp16_weights, + "threshold": target_base_layer.state.threshold, + "index": target_base_layer.index, + } + ) + new_module = SVDLinear8bitLt(target, adapter_name, config=lora_config, **kwargs) + elif 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 = SVDLinear4bit(target, adapter_name, config=lora_config, **fourbit_kwargs) + elif QuantLinear is not None and isinstance(target, QuantLinear): + new_module = SVDQuantLinear(target, adapter_name, config=lora_config, **kwargs) + else: + if isinstance(target_base_layer, torch.nn.Linear): + if lora_config.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." + ) + lora_config.fan_in_fan_out = False + elif isinstance(target_base_layer, Conv1D): + if not lora_config.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." + ) + lora_config.fan_in_fan_out = True + elif not isinstance(target_base_layer, torch.nn.Conv2d): + raise ValueError( + f"Target module {target} is not supported. " + f"Currently, only `torch.nn.Linear`, `Conv1D`, and `torch.nn.Conv2d` are supported." + ) + if isinstance(target_base_layer, torch.nn.Conv2d): + new_module = SVDConv2d(target, adapter_name, config=lora_config, **kwargs) + else: + new_module = SVDLinear(target, adapter_name, config=lora_config, **kwargs) + + return new_module + + def forward(self, *args, **kwargs): + outputs = self.model.forward(*args, **kwargs) + + if (getattr(outputs, "loss", None) is not None) and isinstance(outputs.loss, torch.Tensor): + # Calculate the orthogonal regularization + orth_reg_weight = self.peft_config[self.trainable_adapter_name].orth_reg_weight + + if orth_reg_weight <= 0: + raise ValueError("orth_reg_weight should be greater than 0. ") + + regu_loss = 0 + num_param = 0 + for n, p in self.model.named_parameters(): + if ("lora_A" in n or "lora_B" in n) and self.trainable_adapter_name in n: + if p.shape == torch.Size([0]): + with gather_params_ctx(p, fwd_module=self): + para_cov = p @ p.T if "lora_A" in n else p.T @ p + else: + para_cov = p @ p.T if "lora_A" in n else p.T @ p + I = torch.eye(*para_cov.size(), out=torch.empty_like(para_cov)) # noqa: E741 + I.requires_grad = False + num_param += 1 + regu_loss += torch.norm(para_cov - I, p="fro") + if num_param > 0: + regu_loss = regu_loss / num_param + else: + regu_loss = 0 + outputs.loss += orth_reg_weight * regu_loss + return outputs + + def resize_modules_by_rank_pattern(self, rank_pattern, adapter_name): + lora_config = self.peft_config[adapter_name] + for name, rank_idx in rank_pattern.items(): + if isinstance(rank_idx, list): + rank = sum(rank_idx) + elif isinstance(rank_idx, torch.Tensor): + rank_idx = rank_idx.view(-1) + rank = rank_idx.sum().item() + else: + raise TypeError("Unexpected type of rank_idx") + key = ".".join(name.split(".")[0:-2]) if adapter_name in name else ".".join(name.split(".")[0:-1]) + _, target, _ = _get_submodules(self.model, key) + lora_E_weights = target.lora_E[adapter_name][rank_idx] + lora_A_weights = target.lora_A[adapter_name][rank_idx] + lora_B_weights = target.lora_B[adapter_name][:, rank_idx] + ranknum = target.ranknum[adapter_name] + target.update_layer( + adapter_name, + rank, + lora_config.lora_alpha, + config=lora_config, + ) + with torch.no_grad(): + if rank > 0: + target.lora_E[adapter_name].copy_(lora_E_weights) + target.lora_A[adapter_name].copy_(lora_A_weights) + target.lora_B[adapter_name].copy_(lora_B_weights) + # The scaling is exactly as the previous + target.ranknum[adapter_name].copy_(ranknum) + + def resize_state_dict_by_rank_pattern(self, rank_pattern, state_dict, adapter_name): + for name, rank_idx in rank_pattern.items(): + rank = sum(rank_idx) + prefix = ".".join(name.split(".")[0:-2]) if adapter_name in name else ".".join(name.split(".")[0:-1]) + for layer in ["lora_E", "lora_A", "lora_B"]: + key = f"base_model.model.{prefix}.{layer}.{adapter_name}" + if layer != "lora_B": + state_dict[key] = ( + state_dict[key][rank_idx] if rank != state_dict[key].shape[0] else state_dict[key] + ) + else: + state_dict[key] = ( + state_dict[key][:, rank_idx] if rank != state_dict[key].shape[1] else state_dict[key] + ) + return state_dict + + def update_and_allocate(self, global_step): + """ + This method updates Adalora budget and mask. + + This should be called in every training step after `loss.backward()` and before `zero_grad()`. + + `tinit`, `tfinal` and `deltaT` are handled with in the method. + + Args: + global_step (`int`): The current training step, it is used to calculate adalora budget. + + Example: + + ```python + >>> loss = model(**input).loss + >>> loss.backward() + >>> optimizer.step() + >>> model.base_model.update_and_allocate(i_step) + >>> optimizer.zero_grad() + ``` + """ + lora_config = self.peft_config[self.trainable_adapter_name] + # Update the importance score and allocate the budget + if global_step < lora_config.total_step - lora_config.tfinal: + _, rank_pattern = self.rankallocator.update_and_allocate(self.model, global_step) + if rank_pattern: + lora_config.rank_pattern = rank_pattern + # Finalize the budget allocation + elif global_step == lora_config.total_step - lora_config.tfinal: + _, rank_pattern = self.rankallocator.update_and_allocate(self.model, global_step, force_mask=True) + # for some reason, this freezes the trainable parameters and nothing gets updates + # self.resize_modules_by_rank_pattern(rank_pattern, self.trainable_adapter_name) + lora_config.rank_pattern = rank_pattern + self.rankallocator.reset_ipt() + # Currently using inefficient way to mask the unimportant weights using the rank pattern + # due to problem mentioned above + elif global_step > lora_config.total_step - lora_config.tfinal: + self.rankallocator.mask_using_rank_pattern(self.model, lora_config.rank_pattern) + # Pass the function and do forward propagation + else: + return + + def add_weighted_adapter(self, *args, **kwargs): + """This method is not supported for AdaLoRA, use LoRA instead.""" + raise TypeError(f"{self.__class__.__name__} does not support add_weighted_adapter method.") diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adamss/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adamss/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6aa764b8789b893938851c6add0d62b49e0fecfa --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adamss/__init__.py @@ -0,0 +1,32 @@ +# Copyright 2026-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 AdamssConfig +from .layer import AdamssLayer, Linear +from .model import AdamssModel + + +__all__ = [ + "AdamssConfig", + "AdamssLayer", + "AdamssModel", + "Linear", +] + +# Register Adamss as a PEFT method +register_peft_method( + name="adamss", config_cls=AdamssConfig, model_cls=AdamssModel, prefix="adamss_", is_mixed_compatible=False +) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adamss/asa_callback.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adamss/asa_callback.py new file mode 100644 index 0000000000000000000000000000000000000000..0e9e2947a7013fd00665a5783c0d216a54e65a38 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adamss/asa_callback.py @@ -0,0 +1,90 @@ +# Copyright 2026-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. + +""" +ASA (Adaptive Subspace Allocation) Callback for HuggingFace Trainer. + +This is a thin wrapper around [`AdamssModel.update_and_allocate`]. All ASA logic (importance accumulation, global top-K +masking, importance reset) lives in [`AdamssModel.update_and_allocate`] so that users with custom training loops can +call it directly without needing this callback. + +Important: + To avoid circular imports between peft and transformers, this callback is NOT exported from the top-level `peft` + package. Import it directly: + + ```python + from peft.tuners.adamss.asa_callback import AdamssAsaCallback + ``` +""" + +from transformers import TrainerCallback, TrainerControl, TrainerState, TrainingArguments + + +class AdamssAsaCallback(TrainerCallback): + """ + Trainer callback for Adaptive Subspace Allocation (ASA). + + This callback delegates to [`AdamssModel.update_and_allocate`] on every optimizer step so that ASA "just works" + with HuggingFace `Trainer`. + + All ASA parameters (`asa_target_subspaces`, `init_warmup`, `final_warmup`, `mask_interval`, etc.) are read from the + [`AdamssConfig`] that was used to create the model – there is nothing to configure on the callback itself. + + For custom training loops **without** Trainer, call `model.base_model.update_and_allocate(global_step)` directly + instead. + + Example: + + ```python + from peft import AdamssConfig, get_peft_model + from peft.tuners.adamss.asa_callback import AdamssAsaCallback + from transformers import Trainer + + config = AdamssConfig( + r=100, + num_subspaces=10, + subspace_rank=3, + use_asa=True, + asa_target_subspaces=5, + init_warmup=50, + final_warmup=1000, + mask_interval=100, + ) + model = get_peft_model(base_model, config) + + trainer = Trainer( + model=model, + callbacks=[AdamssAsaCallback()], + ..., + ) + trainer.train() + ``` + """ + + def on_optimizer_step( + self, + args: TrainingArguments, + state: TrainerState, + control: TrainerControl, + **kwargs, + ): + """Called after optimizer.step() – delegates to model.update_and_allocate().""" + model = kwargs.get("model") + if model is not None: + # Resolve to the AdamssModel (works for both PeftModel and raw base_model) + base_model = getattr(model, "base_model", model) + if hasattr(base_model, "update_and_allocate"): + base_model.update_and_allocate(state.global_step) + + return super().on_optimizer_step(args=args, state=state, control=control) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adamss/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adamss/config.py new file mode 100644 index 0000000000000000000000000000000000000000..0a041c6651fa51aca35c95615c89bcd0dccb3421 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adamss/config.py @@ -0,0 +1,340 @@ +# Copyright 2026-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 AdamssConfig(PeftConfig): + """ + Configuration class for Adamss (Adaptive Multi-Subspaces) method. + + AdaMSS is a parameter-efficient fine-tuning method that decomposes weight matrices using SVD and clusters the + decomposed space into multiple trainable subspaces. It learns low-rank updates within these subspaces while keeping + the original weights frozen. + + Args: + r (`int`): + Total rank for SVD decomposition (denoted as R in the paper). This determines how many singular vectors are + used to represent the weight matrix before clustering. Higher values capture more information from the + original weights but require more computation and memory. Lower values provide stronger regularization. + Typical values range from 50 to 500. Default is 100. + + num_subspaces (`int`): + Number of subspaces (K) to cluster the SVD-decomposed space into. Each subspace learns independent low-rank + updates. Increasing this value allows finer-grained adaptation but increases the number of trainable + parameters proportionally. When using ASA (Adaptive Subspace Allocation), this determines the initial + number of subspaces before pruning. Typical values range from 3 to 10. Default is 5. + + subspace_rank (`int`): + The rank (r_i) for each trainable subspace. This controls the capacity of each subspace to learn + adaptations. Higher values increase expressiveness but also increase trainable parameters. Total trainable + parameters scale as O(num_subspaces * subspace_rank * (in_dim + out_dim) / num_subspaces). For most tasks, + values of 1-4 work well. Default is 1. + + target_modules (`Optional[Union[list[str], str]]`): + The names of the modules to apply AdaMSS to. If specified, only these modules will be adapted. Can be a + list of exact module names or a regex expression. For example, `['q_proj', 'v_proj']` for attention layers, + or `'.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'` for regex matching. + + modules_to_save (`Optional[list[str]]`): + List of modules apart from AdaMSS layers to be set as trainable and saved in the final checkpoint. These + modules will be fully fine-tuned (not just low-rank). Required for randomly initialized heads like + `classifier` or `score` in classification tasks. + + init_weights (`Literal["orthogonal"]`): + Initialization method for AdaMSS trainable weights. Currently only "orthogonal" is supported, which uses + orthogonal initialization for the B matrices (output projection). The A matrices are initialized to zero to + ensure the model starts from the pretrained weights. Set to None to skip initialization when loading from a + checkpoint. Default is "orthogonal". + + layers_to_transform (`Optional[Union[list[int], int]]`): + Specific layer indices to apply AdaMSS to. If specified, only these layers will be adapted, useful for + experimenting with which layers benefit most from adaptation. Can be a single integer or a list of + integers. + + layers_pattern (`Optional[Union[list[str], str]]`): + Pattern to match layer names when `layers_to_transform` is specified. Used to extract layer indices from + module names that don't follow the common pattern. + + use_asa (`bool`): + Whether to enable Adaptive Subspace Allocation (ASA). When enabled, ASA dynamically prunes less important + subspaces during training based on gradient information, reducing the effective number of parameters while + maintaining performance. Requires integration with a training callback. Default is False. + + asa_target_subspaces (`int`): + Target total number of active subspaces across all layers when ASA is enabled. ASA will progressively prune + subspaces until this target is reached. Lower values result in more aggressive pruning and fewer trainable + parameters. Should be less than `num_subspaces * num_target_modules`. Typical values range from 20 to 100 + depending on model size. Default is 50. + + init_warmup (`int`): + Number of training steps to wait before starting ASA pruning. During warmup, all subspaces remain active to + allow importance scores to stabilize. Higher values give more time for accurate importance estimation but + delay pruning. Typical values range from 50 to 200. Default is 50. + + final_warmup (`int`): + Training step at which ASA completes pruning and reaches `asa_target_subspaces` active subspaces. The + pruning is distributed between `init_warmup` and `final_warmup`. Should be set based on total training + steps; typically 1/3 to 1/2 of total training steps. Default is 1000. + + mask_interval (`int`): + Number of training steps between ASA mask updates. Lower values allow more frequent adaptation but increase + overhead. Higher values provide more stable importance estimates between updates. Typical values range from + 50 to 200. Default is 100. + + asa_importance_beta (`float`): + Exponential moving average (EMA) coefficient for smoothing subspace importance scores. Higher values + (closer to 1.0) give more weight to historical importance, providing stability. Lower values make + importance more responsive to recent gradients. Typical values range from 0.8 to 0.95. Default is 0.85. + + asa_uncertainty_beta (`float`): + EMA coefficient for smoothing importance uncertainty estimates. Controls how quickly uncertainty adapts to + gradient variance. Similar to asa_importance_beta, higher values provide more stable estimates. Typical + values range from 0.8 to 0.95. Default is 0.85. + + asa_schedule_exponent (`float`): + Schedule exponent controlling the decay rate from total subspaces to `asa_target_subspaces` during ASA + warmup. Higher values result in faster initial pruning (more aggressive early reduction), while lower + values provide a more gradual, linear-like decay. The formula is: current_active_subspaces = + asa_target_subspaces + (asa_total_subspaces - asa_target_subspaces) * (progress ** exponent). Typical + values range from 1.0 (linear) to 5.0 (aggressive). Default is 3.0. + + use_dynamic_rank (`bool`): + Whether to dynamically determine subspace ranks based on singular value magnitudes. When True, each + subspace's rank is determined by counting singular values above a threshold, allowing different subspaces + to have different effective ranks. When False, all subspaces use the fixed `subspace_rank`. Default is + False. + + svd_threshold (`float`): + Threshold ratio for dynamic rank selection, only used when `use_dynamic_rank=True`. A singular value is + considered significant if it exceeds `threshold * max_singular_value`. Higher values result in lower + effective ranks (more aggressive truncation). Typical values range from 0.05 to 0.2. Default is 0.1 (10% of + max). + """ + + r: int = field( + default=100, + metadata={ + "help": ( + "Total rank for SVD decomposition (R in the paper). Higher values capture more " + "information but require more computation. The actual rank is clamped to " + "min(r, in_features, out_features). Typical values: 50-500. Default: 100." + ) + }, + ) + num_subspaces: int = field( + default=5, + metadata={ + "help": ( + "Number of subspaces (K) to cluster the SVD space into. Each subspace learns " + "independent low-rank updates. Increasing this allows finer-grained adaptation " + "but increases trainable parameters. Typical values: 3-10. Default: 5." + ) + }, + ) + subspace_rank: int = field( + default=1, + metadata={ + "help": ( + "Rank (r_i) for each trainable subspace. Higher values increase expressiveness " + "but also increase parameters. For most tasks, values of 1-4 work well. Default: 1." + ) + }, + ) + 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 AdaMSS. " + "For example, ['q_proj', 'v_proj'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'. " + "For Vision Transformers, typically ['query', 'value']." + ) + }, + ) + init_weights: Optional[Literal["orthogonal"]] = field( + default="orthogonal", + metadata={ + "help": ( + "Initialization method for AdaMSS trainable weights. Currently only 'orthogonal' " + "is supported, which uses orthogonal initialization for B matrices. A matrices " + "are initialized to zero to start from pretrained weights. Set to None to skip " + "initialization when loading from a checkpoint. Default: 'orthogonal'." + ) + }, + ) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": ( + "List of modules apart from AdaMSS 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." + ) + }, + ) + layers_to_transform: Optional[Union[list[int], int]] = field( + default=None, + metadata={ + "help": ( + "Specific layer indices to apply AdaMSS to. If specified, only these layers will " + "be adapted, useful for experimenting with which layers benefit most. Can be a " + "single integer or a list of integers. Default: None (adapt all matching layers)." + ) + }, + ) + layers_pattern: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": ( + "Pattern to match layer names when `layers_to_transform` is specified. Used to " + "extract layer indices from module names that don't follow common patterns." + ) + }, + ) + # ASA (Adaptive Subspace Allocation) parameters + use_asa: bool = field( + default=False, + metadata={ + "help": ( + "Whether to enable Adaptive Subspace Allocation (ASA). When enabled, ASA dynamically " + "prunes less important subspaces during training based on gradient information, " + "reducing parameters while maintaining performance. Requires a training callback. " + "Default: False." + ) + }, + ) + asa_target_subspaces: int = field( + default=50, + metadata={ + "help": ( + "Target total number of active subspaces across all layers when ASA is enabled. " + "ASA progressively prunes subspaces until this target is reached. Lower values " + "result in more aggressive pruning. Typical values: 20-100. Default: 50." + ) + }, + ) + init_warmup: int = field( + default=50, + metadata={ + "help": ( + "Training steps to wait before starting ASA pruning. During warmup, all subspaces " + "remain active to allow importance scores to stabilize. Higher values give more " + "time for accurate estimation. Typical values: 50-200. Default: 50." + ) + }, + ) + final_warmup: int = field( + default=1000, + metadata={ + "help": ( + "Training step at which ASA completes pruning and reaches asa_target_subspaces. " + "Should be set based on total training steps; typically 1/3 to 1/2 of total steps. " + "Default: 1000." + ) + }, + ) + mask_interval: int = field( + default=100, + metadata={ + "help": ( + "Training steps between ASA mask updates. Lower values allow more frequent " + "adaptation but increase overhead. Higher values provide more stable estimates. " + "Typical values: 50-200. Default: 100." + ) + }, + ) + asa_importance_beta: float = field( + default=0.85, + metadata={ + "help": ( + "EMA coefficient for smoothing subspace importance scores during ASA. Higher " + "values (closer to 1.0) give more weight to historical importance, providing " + "stability. Lower values make importance more responsive to recent gradients. " + "Typical values: 0.8-0.95. Default: 0.85." + ) + }, + ) + asa_uncertainty_beta: float = field( + default=0.85, + metadata={ + "help": ( + "EMA coefficient for smoothing importance uncertainty estimates during ASA. " + "Controls how quickly uncertainty adapts to gradient variance. Higher values " + "provide more stable estimates. Typical values: 0.8-0.95. Default: 0.85." + ) + }, + ) + asa_schedule_exponent: float = field( + default=3.0, + metadata={ + "help": ( + "Schedule exponent controlling the decay rate from total subspaces to " + "asa_target_subspaces. Higher values result in faster initial pruning (aggressive " + "early reduction), lower values provide gradual linear-like decay. Formula: " + "current_active_subspaces = asa_target_subspaces + (total - target) * (progress ** exponent). " + "Typical values: 1.0 (linear) to 5.0 (aggressive). Default: 3.0." + ) + }, + ) + # Dynamic rank selection parameters + use_dynamic_rank: bool = field( + default=False, + metadata={ + "help": ( + "Whether to dynamically determine subspace ranks based on singular value magnitudes. " + "When True, each subspace's rank is determined by counting singular values above " + "a threshold, allowing different subspaces to have different effective ranks. " + "When False (default), all subspaces use the fixed subspace_rank. Default: False." + ) + }, + ) + svd_threshold: float = field( + default=0.1, + metadata={ + "help": ( + "Threshold ratio for dynamic rank selection (only used when use_dynamic_rank=True). " + "A singular value is significant if it exceeds threshold * max_singular_value. " + "Higher values result in lower effective ranks (more aggressive truncation). " + "Typical values: 0.05-0.2. Default: 0.1 (10% of max)." + ) + }, + ) + + def __post_init__(self): + self.peft_type = PeftType.ADAMSS + self.target_modules = ( + set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules + ) + super().__post_init__() + + # Normalize init_weights: convert False to None for backward compatibility + if self.init_weights is False: + self.init_weights = None + + # Validate initialization method + if self.init_weights not in ["orthogonal", None]: + raise ValueError(f"init_weights must be 'orthogonal' or None, got {self.init_weights}") + + # Early check for scikit-learn availability + try: + import sklearn # noqa: F401 + except ImportError: + raise ImportError("scikit-learn is required for AdaMSS. Please install it with: pip install scikit-learn") diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adamss/layer.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adamss/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..2a0ba296b3bb59f564a52ea7da63a55fd12472d7 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adamss/layer.py @@ -0,0 +1,668 @@ +# Copyright 2026-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.nn.functional as F +from torch import nn + +from peft.tuners._buffer_dict import BufferDict +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge + +from .config import AdamssConfig +from .utils import clustering_Z, get_trainable_subspaces, seg_locations, slice_pca + + +class AdamssLayer(BaseTunerLayer): + """ + Base Adamss layer that stores adapter-specific information. + """ + + # All names of layers that may contain adapter weights (trainable or frozen) + # Use ModuleDict for proper state_dict key format that PEFT's save/load can handle + # Only include trainable parameter containers here (not buffers) + # adamss_newB is a buffer (frozen), not a trainable parameter + adapter_layer_names = ("adamss_A", "adamss_B") + # other_param_names specifies additional non-tensor metadata + other_param_names = ( + "num_subspaces", + "train_subspace_index", + "seg_result", + "scatter_index", + "exp_avg_ipt_A", + "exp_avg_ipt_B", + "exp_avg_unc_A", + "exp_avg_unc_B", + ) + + def __init__(self, base_layer: nn.Module, **kwargs) -> None: + self.base_layer = base_layer + # Adapter-specific attributes + # Use ModuleDict containing ParameterList for proper state_dict keys (e.g., adamss_A.default.0) + self.adamss_A = nn.ModuleDict({}) # Will contain ParameterList per adapter + self.adamss_B = nn.ModuleDict({}) # Will contain ParameterList per adapter + # Use BufferDict for frozen projection matrix (keys like adamss_newB.default) + self.adamss_newB = BufferDict(persistent=True) + self.num_subspaces = {} + self.train_subspace_index = {} + self.seg_result = {} + self.scatter_index = {} + # ASA importance tracking (per-adapter lists indexed by subspace) + self.exp_avg_ipt_A = {} + self.exp_avg_ipt_B = {} + self.exp_avg_unc_A = {} + self.exp_avg_unc_B = {} + self._disable_adapters = False + self.merged_adapters = [] + + def reset_importance(self, adapter_name: str) -> None: + """ + Clear stored importance stats for an adapter. + + Called after each masking interval to restart EMA accumulation for the next importance scoring window. Without + the reset the scores from early training steps would dominate later masking decisions. + """ + if adapter_name in self.exp_avg_ipt_A: + n = len(self.exp_avg_ipt_A[adapter_name]) + self.exp_avg_ipt_A[adapter_name] = [None] * n + self.exp_avg_ipt_B[adapter_name] = [None] * n + self.exp_avg_unc_A[adapter_name] = [None] * n + self.exp_avg_unc_B[adapter_name] = [None] * n + + def update_importance( + self, adapter_name: str, importance_beta: float = 0.85, uncertainty_beta: float = 0.85 + ) -> None: + """ + Update importance scores using current gradients. + + Called by [`AdamssModel.update_and_allocate`] (which is in turn called by [`AdamssAsaCallback`] when using + HuggingFace `Trainer`). + + Args: + adapter_name: Name of the adapter to update importance for. + importance_beta: EMA coefficient for importance averaging (0.8-0.95 typical). + uncertainty_beta: EMA coefficient for uncertainty averaging (0.8-0.95 typical). + """ + if adapter_name not in self.exp_avg_ipt_A: + return + if adapter_name not in self.adamss_A: + return + + param_list_A = self.adamss_A[adapter_name] + param_list_B = self.adamss_B[adapter_name] + + ipt_A = self.exp_avg_ipt_A[adapter_name] + ipt_B = self.exp_avg_ipt_B[adapter_name] + unc_A = self.exp_avg_unc_A[adapter_name] + unc_B = self.exp_avg_unc_B[adapter_name] + + for i in range(self.num_subspaces[adapter_name]): + for param_list, ipt_list, unc_list in [ + (param_list_A, ipt_A, unc_A), + (param_list_B, ipt_B, unc_B), + ]: + param = param_list[i] + if param.grad is not None: + if ipt_list[i] is None: + ipt_list[i] = torch.zeros_like(param, requires_grad=False) + unc_list[i] = torch.zeros_like(param, requires_grad=False) + + # Calculate importance: |w * g| + ipt = (param * param.grad).abs().detach() + + # Update uncertainty BEFORE updating importance (matches adamss_pkg) + diff = (ipt - ipt_list[i]).abs() + unc_list[i].mul_(uncertainty_beta).add_(diff, alpha=1 - uncertainty_beta) + + # Then update importance + ipt_list[i].mul_(importance_beta).add_(ipt, alpha=1 - importance_beta) + + def update_layer( + self, + adapter_name: str, + r: int, + config: AdamssConfig, + **kwargs, + ) -> None: + """ + Update layer with Adamss adapter. + + This method initializes the Adamss decomposition for the weight matrix using SVD, clustering, and QR + initialization. + """ + num_subspaces = config.num_subspaces + subspace_rank = config.subspace_rank + init_weights = config.init_weights + use_asa = config.use_asa + inference_mode = config.inference_mode + use_dynamic_rank = config.use_dynamic_rank + svd_threshold = config.svd_threshold + + # Get the base weight info + weight = self.get_base_layer().weight + bias = self.get_base_layer().bias + device = weight.device + dtype = weight.dtype + _, in_features = weight.shape + + # Adjust in_features for bias column + if bias is not None: + in_features += 1 + + # Prepare weight tensor (add bias as extra column if present) + if bias is not None: + weight_with_bias = torch.cat((weight, bias.unsqueeze(1)), dim=1) + else: + weight_with_bias = weight + + # Reshape to 4D tensor for slice_pca: (1, 1, out_features, in_features) + weight_tensor = weight_with_bias.unsqueeze(0).unsqueeze(0).to(torch.float32).to(device) + + # Perform SVD decomposition with diagnostics in case of failure + try: + res = slice_pca(weight_tensor, r, device, torch.float32) + except Exception as e: + raise RuntimeError( + f"slice_pca raised an exception for layer {adapter_name} (shape={tuple(weight_tensor.shape)}, dtype={weight_tensor.dtype}, device={device}): {e}" + ) from e + + VVT, UU = res + + # Cluster the column space + cluster_idx, effective_num_subspaces = clustering_Z(UU[0, 0, :, :], num_subspaces, 10) + + # Get segment locations + seg_result = seg_locations(cluster_idx) + + # Get trainable subspace indices + train_subspace_index = get_trainable_subspaces(effective_num_subspaces) + + # Store metadata + self.num_subspaces[adapter_name] = effective_num_subspaces + self.train_subspace_index[adapter_name] = train_subspace_index + self.seg_result[adapter_name] = seg_result + + # Store projection matrix in BufferDict (frozen, device-aware) + self.adamss_newB[adapter_name] = VVT[0, 0, :, :].detach().to(dtype) + + # Use user-specified subspace_rank + rank_per_subspace = subspace_rank + + # Initialize trainable subspace parameters + # Collect parameters in lists, then create ParameterList for proper state_dict keys + A_params = [] + B_params = [] + + for i in range(self.num_subspaces[adapter_name]): + subspace_idx = train_subspace_index[i] + seg_indices = seg_result[subspace_idx] + + # Extract subspace data: use ALL r columns from SVD (not just r/K) + # This matches adamss_pkg where A matrices have shape (rank_i, r) + subspace_data = UU[0, 0, seg_indices, :r] + # subspace_data shape: (len(seg_indices), r) + + # Determine actual rank based on configuration + if use_dynamic_rank: + # Compute Gram matrix Z = subspace_data @ subspace_data.T + Z_row = subspace_data @ subspace_data.T # (len(seg_indices), len(seg_indices)) + + # Compute SVD to get row space decomposition + _U_row, S_row, _V_row = torch.svd_lowrank(Z_row, q=min(Z_row.shape), niter=2) + + # Dynamic rank selection using SVD threshold + # Dynamically determine actual rank using configurable threshold + # Following adamss_pkg: num_ii_jj = min((S > threshold * S[0]).sum().item(), args.adamss_ri) + threshold_mask = S_row > svd_threshold * S_row[0] + actual_rank = min(threshold_mask.sum().item(), subspace_rank, len(S_row)) + + # Handle edge case: ensure at least rank 1 + if actual_rank == 0: + actual_rank = 1 + + else: + # Fixed rank: match adamss_pkg behavior exactly + # adamss_pkg uses: num_ii_jj = min(len(seg_result[indx]), args.adamss_ri) + actual_rank = min(len(seg_indices), subspace_rank) + + # Ensure at least rank 1 + if actual_rank == 0: + actual_rank = 1 + + # Initialize A using QR decomposition to match adamss_pkg exactly + # adamss_pkg: Q, R = torch.linalg.qr((UU[seg_result[indx],:]).T @ A[i], mode='reduced') + # where A[i] is U from SVD of subspace Gram matrix + + # First, compute Gram matrix for this subspace + Z_subspace = subspace_data @ subspace_data.T # (len(seg_indices), len(seg_indices)) + + # SVD of Gram matrix to get A_intermediate + U_gram, _S_gram, _ = torch.svd_lowrank(Z_subspace, q=min(Z_subspace.shape[0], actual_rank), niter=2) + A_intermediate = U_gram[:, :actual_rank] # (len(seg_indices), actual_rank) + + # Now apply QR decomposition: (UU[seg_indices, :r]).T @ A_intermediate + # UU[0, 0, seg_indices, :r] is subspace_data with shape (len(seg_indices), r) + matrix_for_qr = subspace_data.T @ A_intermediate # (r, actual_rank) + Q, _R = torch.linalg.qr(matrix_for_qr, mode="reduced") + + # A_init is Q.T to match adamss_pkg + A_init = Q.T.contiguous() # (actual_rank, r) + + # Initialize B matrix + # When init_weights='orthogonal', use zeros for identity operation (standard training init) + # When init_weights=None/False, use random values so adapter produces non-zero effect + if init_weights == "orthogonal": + # Zero initialization - adapter produces identity at start + # Note: A parameters may not update in step 1 since ∂Loss/∂A ∝ B and B=0 + # But after step 1, B becomes non-zero and A will get gradients in step 2+ + B_init = torch.zeros(len(seg_indices), actual_rank, dtype=dtype, device=device) + else: + # Random initialization for testing - produces non-zero adapter output + B_init = torch.randn(len(seg_indices), actual_rank, dtype=dtype, device=device) * 0.01 + + # Collect A and B parameters + A_params.append(nn.Parameter(A_init.to(dtype))) + B_params.append(nn.Parameter(B_init.to(dtype))) + + # Create ParameterLists and store in ModuleDict + # This creates state_dict keys like 'adamss_A.default.0', 'adamss_A.default.1', etc. + self.adamss_A[adapter_name] = nn.ParameterList(A_params) + self.adamss_B[adapter_name] = nn.ParameterList(B_params) + + # Initialize ASA tracking if enabled + if use_asa: + n = effective_num_subspaces + self.exp_avg_ipt_A[adapter_name] = [None] * n + self.exp_avg_ipt_B[adapter_name] = [None] * n + self.exp_avg_unc_A[adapter_name] = [None] * n + self.exp_avg_unc_B[adapter_name] = [None] * n + + # Hooks are not used; importance is updated explicitly via update_importance + # to match adamss_pkg behavior (using accumulated gradients). + + # Compute scatter_index for forward pass + self.scatter_index[adapter_name] = torch.cat( + [ + self.seg_result[adapter_name][self.train_subspace_index[adapter_name][i]] + for i in range(self.num_subspaces[adapter_name]) + ], + dim=0, + ).long() + + # Move adapter to device of base layer (important for low_cpu_mem_usage support) + self._move_adapter_to_device_of_base_layer(adapter_name) + + # Set requires_grad via parent class set_adapter (works with ParameterList) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + +class Linear(nn.Module, AdamssLayer): + """ + Adamss-adapted Linear layer. + """ + + def __init__( + self, + base_layer: nn.Module, + adapter_name: str, + r: int, + config: AdamssConfig, + **kwargs, + ) -> None: + super().__init__() + AdamssLayer.__init__(self, base_layer, **kwargs) + + # Set in_features and out_features from base layer (required for PEFT compatibility) + self.in_features = base_layer.in_features + self.out_features = base_layer.out_features + + # Initialize the adapter + self.update_layer( + adapter_name, + r, + config=config, + **kwargs, + ) + self._active_adapter = adapter_name + self.dtype = base_layer.weight.dtype + + def _load_from_state_dict( + self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs + ): + """Handle shape mismatches that arise when loading checkpoints. + + AdaMSS B parameter shapes depend on KMeans clustering of the weight matrix. KMeans uses a fixed `random_state` + so results should be deterministic, but this override acts as a safety net in case sklearn changes clustering + behaviour across versions. It detects shape mismatches and replaces placeholder parameters with + correctly-shaped tensors before the default `load_state_dict` logic runs. + """ + for key, value in state_dict.items(): + if not key.startswith(prefix): + continue + local_key = key[len(prefix) :] + parts = local_key.split(".") + try: + # Use get_submodule for the parent path + parent_path = ".".join(parts[:-1]) + target = self.get_submodule(parent_path) if parent_path else self + last = parts[-1] + if last.isdigit(): + current = target[int(last)] + else: + current = getattr(target, last) + except (AttributeError, IndexError, KeyError): + continue + + if isinstance(current, (torch.Tensor, nn.Parameter)) and current.shape != value.shape: + new_param = nn.Parameter(torch.empty_like(value), requires_grad=current.requires_grad) + if last.isdigit(): + target[int(last)] = new_param + else: + setattr(target, last, new_param) + + super()._load_from_state_dict( + state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs + ) + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + """ + Forward pass with Adamss adaptation. + """ + previous_dtype = x.dtype + + if self._disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + # Adapter weights are already merged into base_layer.weight, + # so just call base_layer directly (no adapter delta needed). + result = self.base_layer(x, *args, **kwargs) + else: + # Cast input to layer dtype + x = x.to(self.dtype) + + # Add bias column only when the base layer has a bias + # (update_layer concatenates bias into newB only when bias is not None) + if self.get_base_layer().bias is not None: + if x.dim() == 2: + ones = torch.ones(x.shape[0], 1, device=x.device, dtype=self.dtype) + else: # x.dim() == 3 or more + ones = torch.ones(*x.shape[:-1], 1, device=x.device, dtype=self.dtype) + newx = torch.cat((x, ones), dim=-1) + else: + newx = x + + # Base output from the frozen original weight + result = self.base_layer(x, *args, **kwargs) + + # Iterate over all active adapters and add their deltas + for active_adapter in self.active_adapters: + if active_adapter not in self.adamss_A: + continue + + # Project input into low-rank space + projected = F.linear(newx, self.adamss_newB[active_adapter].to(self.dtype)) # (..., r) + + # Apply A and B transformations per subspace + # TODO: if all subspaces have equal output dimensions, this loop could + # be replaced with a batched matmul/einsum for better performance. + # Currently B_i shapes vary per subspace (clustering-dependent), so we loop. + subspace_chunks = [] + for i in range(self.num_subspaces[active_adapter]): + A_i = self.adamss_A[active_adapter][i].to(self.dtype) # (ri, r) + B_i = self.adamss_B[active_adapter][i].to(self.dtype) # (seg_len_i, ri) + subspace_out = F.linear(projected, A_i) # (..., ri) + subspace_out = F.linear(subspace_out, B_i) # (..., seg_len_i) + subspace_chunks.append(subspace_out) + + # Concatenate subspace results and scatter to output dimension order + adapter_delta = torch.cat(subspace_chunks, dim=-1) + scatter_index_tensor = self.scatter_index[active_adapter].to(adapter_delta.device) + + if adapter_delta.dim() == 2: + index = scatter_index_tensor.unsqueeze(0).expand(adapter_delta.shape[0], -1) + adapter_delta = torch.zeros( + adapter_delta.shape[0], + result.shape[-1], + device=adapter_delta.device, + dtype=adapter_delta.dtype, + ).scatter(1, index, adapter_delta) + else: + index = scatter_index_tensor.unsqueeze(0).unsqueeze(0).expand(*adapter_delta.shape[:-1], -1) + adapter_delta = torch.zeros( + *adapter_delta.shape[:-1], + result.shape[-1], + device=adapter_delta.device, + dtype=adapter_delta.dtype, + ).scatter(-1, index, adapter_delta) + + result = result + adapter_delta + + # Cast back to original dtype + return result.to(previous_dtype) + + 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. 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. + """ + 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.adamss_A: + 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() + orig_dtype = orig_weight.dtype + delta_weight = self.get_delta_weight(active_adapter) + orig_weight += delta_weight.to(orig_dtype) + + if not torch.isfinite(orig_weight).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = orig_weight + + # Also update bias if present + if base_layer.bias is not None: + orig_bias = base_layer.bias.data.clone() + delta_bias = self.get_delta_bias(active_adapter) + orig_bias += delta_bias.to(orig_dtype) + if not torch.isfinite(orig_bias).all(): + raise ValueError( + f"NaNs detected in the merged bias. The adapter {active_adapter} seems to be broken" + ) + base_layer.bias.data = orig_bias + else: + delta_weight = self.get_delta_weight(active_adapter) + base_layer.weight.data += delta_weight + + # Also update bias if present + if base_layer.bias is not None: + delta_bias = self.get_delta_bias(active_adapter) + base_layer.bias.data += delta_bias + + 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 in self.adamss_A: + base_layer = self.get_base_layer() + weight = base_layer.weight + orig_dtype = weight.dtype + delta_weight = self.get_delta_weight(active_adapter) + weight.data -= delta_weight.to(orig_dtype) + + # Also update bias if present + if base_layer.bias is not None: + delta_bias = self.get_delta_bias(active_adapter) + base_layer.bias.data -= delta_bias.to(orig_dtype) + + def get_delta_weight(self, adapter_name: str) -> torch.Tensor: + """ + Compute the delta weight for the given adapter. + + For AdaMSS, the forward computes: + result = newx @ resW.T + scatter(newx @ newB.T @ A.T @ B.T) + + Since resW = original_weight_with_bias, the delta is just the adapter path: + delta = scatter(B @ A @ newB) + + We extract the weight portion (excluding bias column) as the delta to add to the base layer's weight. + + Args: + adapter_name (str): The name of the adapter for which the delta weight should be computed. + """ + device = self.get_base_layer().weight.device + dtype = self.get_base_layer().weight.dtype + base_weight = self.get_base_layer().weight + + # Get buffers + newB = self.adamss_newB[adapter_name] # Shape: (r, in_features + 1) + + # Get parameter lists + param_list_A = self.adamss_A[adapter_name] + param_list_B = self.adamss_B[adapter_name] + + # 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 + cast_to_fp32 = device.type == "cpu" and dtype in (torch.float16, torch.bfloat16) + compute_dtype = torch.float32 if cast_to_fp32 else dtype + + newB = newB.to(device).to(compute_dtype) + + # Compute the adapter contribution (scattered B @ A @ newB) + # delta_weight has shape (out_features, in_features + 1) + out_features = base_weight.shape[0] + in_features_plus_1 = newB.shape[1] + + # Initialize delta weight for the adapter path only + delta_weight = torch.zeros(out_features, in_features_plus_1, device=device, dtype=compute_dtype) + + # Compute the transformation for each subspace + # For subspace i: contribution = B_i @ A_i @ newB + # where A_i has shape (rank_i, r), B_i has shape (seg_len_i, rank_i) + chunks = [] + for i in range(self.num_subspaces[adapter_name]): + A_i = param_list_A[i].to(device).to(compute_dtype) # Shape: (rank_i, r) + B_i = param_list_B[i].to(device).to(compute_dtype) # Shape: (seg_len_i, rank_i) + + # B_i @ A_i @ newB gives shape (seg_len_i, in_features+1) + chunk = B_i @ A_i @ newB + chunks.append(chunk) + + # Concatenate chunks and scatter to correct positions + if chunks: + combined = torch.cat(chunks, dim=0) # Shape: (total_seg_len, in_features+1) + # Use scatter_index for assignment + scatter_idx = self.scatter_index[adapter_name].to(delta_weight.device) + delta_weight[scatter_idx] = combined + + # Extract just the weight portion + if self.get_base_layer().bias is not None: + # delta_weight[:, :-1] is the weight delta (exclude bias column) + output_tensor = delta_weight[:, :-1] # Shape: (out_features, in_features) + else: + # No bias column to strip + output_tensor = delta_weight # Shape: (out_features, in_features) + + if cast_to_fp32: + output_tensor = output_tensor.to(dtype=dtype) + + return output_tensor + + def get_delta_bias(self, adapter_name: str) -> torch.Tensor: + """ + Compute the bias delta for the given adapter. + + This is the last column of the adapter path contribution (B @ A @ newB). + + Args: + adapter_name (str): The name of the adapter for which the bias delta should be computed. + """ + device = self.get_base_layer().weight.device + dtype = self.get_base_layer().weight.dtype + base_weight = self.get_base_layer().weight + + # Get buffers + newB = self.adamss_newB[adapter_name] # Shape: (r, in_features + 1) + + # Get parameter lists + param_list_A = self.adamss_A[adapter_name] + param_list_B = self.adamss_B[adapter_name] + + cast_to_fp32 = device.type == "cpu" and dtype in (torch.float16, torch.bfloat16) + compute_dtype = torch.float32 if cast_to_fp32 else dtype + + newB = newB.to(device).to(compute_dtype) + + out_features = base_weight.shape[0] + in_features_plus_1 = newB.shape[1] + + # Initialize delta weight for the adapter path only + delta_weight = torch.zeros(out_features, in_features_plus_1, device=device, dtype=compute_dtype) + + # Compute the transformation for each subspace + chunks = [] + for i in range(self.num_subspaces[adapter_name]): + A_i = param_list_A[i].to(device).to(compute_dtype) + B_i = param_list_B[i].to(device).to(compute_dtype) + chunk = B_i @ A_i @ newB + chunks.append(chunk) + + if chunks: + combined = torch.cat(chunks, dim=0) + scatter_idx = self.scatter_index[adapter_name].to(delta_weight.device) + delta_weight[scatter_idx] = combined + + # Extract the bias portion (last column) + if self.get_base_layer().bias is None: + # No bias — return zeros + output_tensor = torch.zeros(base_weight.shape[0], device=device, dtype=compute_dtype) + else: + output_tensor = delta_weight[:, -1] # Shape: (out_features,) + + if cast_to_fp32: + output_tensor = output_tensor.to(dtype=dtype) + + return output_tensor + + def __repr__(self) -> str: + rep = super().__repr__() + return "adamss." + rep diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adamss/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adamss/model.py new file mode 100644 index 0000000000000000000000000000000000000000..3646203c232a0d38e3cb2a88accc3a9e8518ca1e --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adamss/model.py @@ -0,0 +1,279 @@ +# Copyright 2026-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 typing import Optional + +import torch +from torch import nn + +from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer, check_target_module_exists +from peft.utils import ( + TRANSFORMERS_MODELS_TO_ADAMSS_TARGET_MODULES_MAPPING, +) + +from .config import AdamssConfig +from .layer import AdamssLayer, Linear + + +class AdamssModel(BaseTuner): + """ + Creates Adamss (Adaptive Multi-Subspaces) model from a pretrained model. + + The method decomposes weight matrices using SVD and clusters the decomposed space into multiple trainable subspaces + for parameter-efficient fine-tuning. + + Args: + model (`torch.nn.Module`): The model to be adapted. + config (`AdamssConfig`): The configuration of the Adamss model. + adapter_name (`str`): The name of the adapter, defaults to `"default"`. + + Returns: + `torch.nn.Module`: The Adamss model. + + Example: + ```python + >>> from transformers import AutoModelForImageClassification + >>> from peft import AdamssConfig, get_peft_model + + >>> config = AdamssConfig( + ... r=500, + ... num_subspaces=5, + ... target_modules=["query", "value"], + ... ) + + >>> model = AutoModelForImageClassification.from_pretrained("google/vit-base-patch16-224") + >>> adamss_model = get_peft_model(model, config) + ``` + + **Attributes**: + - **model** ([`~torch.nn.Module`]) -- The model to be adapted. + - **peft_config** ([`AdamssConfig`]): The configuration of the Adamss model. + """ + + prefix: str = "adamss_" + tuner_layer_cls = (AdamssLayer,) + target_module_mapping = TRANSFORMERS_MODELS_TO_ADAMSS_TARGET_MODULES_MAPPING + + def __init__( + self, model, config, adapter_name, low_cpu_mem_usage: bool = False, state_dict: Optional[dict] = None + ) -> None: + # Initialize ASA tracking before BaseTuner injects adapters so attribute exists. + self._asa_total_subspaces = {} + super().__init__(model, config, adapter_name, low_cpu_mem_usage=low_cpu_mem_usage, state_dict=state_dict) + + @staticmethod + def _check_target_module_exists(adamss_config, key): + """Helper to check if target module matches the pattern.""" + return check_target_module_exists(adamss_config, key) + + def _create_and_replace( + self, + adamss_config: AdamssConfig, + adapter_name: str, + target: nn.Module, + target_name: str, + parent: nn.Module, + current_key: str, + **optional_kwargs, + ): + """ + Create and replace target module with Adamss-adapted module. + """ + if current_key is None: + raise ValueError("Current Key shouldn't be `None`") + + # Check if already an Adamss layer + if isinstance(target, AdamssLayer): + target.update_layer( + adapter_name, + adamss_config.r, + config=adamss_config, + ) + # set_adapter is called inside update_layer, but we need to handle + # the case where adapter is not in active_adapters + if adapter_name not in self.active_adapters: + # Ensure the new adapter is frozen if not active + target.set_adapter(self.active_adapters, inference_mode=adamss_config.inference_mode) + else: + # Create new Adamss layer + new_module = self._create_new_module(adamss_config, adapter_name, target, **optional_kwargs) + self._record_asa_total_subspaces(adapter_name, adamss_config, new_module) + # requires_grad is handled inside _create_new_module via set_adapter + self._replace_module(parent, target_name, new_module, target) + + def _record_asa_total_subspaces(self, adapter_name: str, adamss_config: AdamssConfig, module: AdamssLayer) -> None: + """Track total subspaces per adapter so the ASA schedule matches adamss_pkg.""" + if not hasattr(module, "num_subspaces"): + return + layer_num_subspaces = module.num_subspaces.get(adapter_name, 0) + if layer_num_subspaces is None or layer_num_subspaces <= 0: + return + prev_total = self._asa_total_subspaces.get(adapter_name, 0) + self._asa_total_subspaces[adapter_name] = prev_total + layer_num_subspaces + + def _create_new_module( + self, + adamss_config: AdamssConfig, + adapter_name: str, + target: nn.Module, + **kwargs, + ) -> nn.Module: + """ + Create a new Adamss module based on the target module type. + """ + 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, + r=adamss_config.r, + config=adamss_config, + **kwargs, + ) + else: + raise TypeError( + f"Target module {target} is not supported. Currently, only `torch.nn.Linear` is supported." + ) + + return new_module + + def update_and_allocate(self, global_step: int) -> None: + """ + Update importance scores and apply ASA masking (if enabled). + + This method should be called in **every** training step after ``loss.backward()`` and before + ``optimizer.zero_grad()`` when ASA is enabled. Internally it: + + 1. Accumulates importance scores via EMA every step during the warmup period. + 2. At mask intervals, applies global top-K masking and resets importance. + + This is the single entry point for ASA – using the :class:`AdamssAsaCallback` with HuggingFace ``Trainer`` + simply delegates to this method. For custom training loops, call this directly instead of the callback. + + Args: + global_step (`int`): The current training step. + + Example:: + + for step, batch in enumerate(dataloader): + loss = model(**batch).loss loss.backward() optimizer.step() model.base_model.update_and_allocate(step) + optimizer.zero_grad() + """ + for adapter_name in self.active_adapters: + config = self.peft_config[adapter_name] + if not config.use_asa: + continue + + within_warmup = config.init_warmup <= global_step <= config.final_warmup + + # --- collect ASA layers once --- + asa_layers = [ + m for m in self.model.modules() if isinstance(m, AdamssLayer) and adapter_name in m.exp_avg_ipt_A + ] + if not asa_layers: + continue + + # Step 1: accumulate importance EVERY step during warmup + if within_warmup: + for module in asa_layers: + module.update_importance(adapter_name, config.asa_importance_beta, config.asa_uncertainty_beta) + + # Step 2: at mask intervals → schedule, global mask, then reset + is_mask_interval = global_step % config.mask_interval == 0 + if within_warmup and is_mask_interval: + current_target = self._schedule_threshold(global_step, config) + if current_target is not None: + self._global_mask_to_target(current_target, adapter_name, asa_layers) + + # Reset importance AFTER masking for fresh accumulation + for module in asa_layers: + module.reset_importance(adapter_name) + + def _schedule_threshold(self, step: int, config) -> Optional[int]: + """Calculate current target subspaces based on warmup schedule.""" + total = self._asa_total_subspaces.get(next(iter(self.active_adapters), "default"), 0) + if total == 0: + total = self._get_asa_total_subspaces() + if total == 0: + return None + + if step < config.init_warmup: + return None + elif step <= config.final_warmup: + mul_coeff = 1.0 - (step - config.init_warmup) / (config.final_warmup - config.init_warmup) + mul_coeff = max(0.0, min(1.0, mul_coeff)) + exponent = getattr(config, "asa_schedule_exponent", 3.0) + return int(config.asa_target_subspaces + (total - config.asa_target_subspaces) * (mul_coeff**exponent)) + else: + return config.asa_target_subspaces + + def _get_asa_total_subspaces(self) -> int: + """Get total number of subspaces from model (sum across all layers).""" + total = 0 + for module in self.model.modules(): + if isinstance(module, AdamssLayer) and module.num_subspaces: + total += next(iter(module.num_subspaces.values())) + return total + + def _global_mask_to_target(self, target_subspaces: int, adapter_name: str, asa_layers: list) -> None: + """ + Apply **global** top-K masking across all layers. + + Collects importance scores from every subspace in every layer, ranks them globally, and keeps only the top + ``target_subspaces`` active. + """ + # 1. Collect (module, subspace_idx, score) for every subspace + subspace_scores: list[tuple] = [] + for module in asa_layers: + n_subspaces = module.num_subspaces.get(adapter_name, 0) + ipt_A = module.exp_avg_ipt_A[adapter_name] + ipt_B = module.exp_avg_ipt_B[adapter_name] + unc_A = module.exp_avg_unc_A[adapter_name] + unc_B = module.exp_avg_unc_B[adapter_name] + + for i in range(n_subspaces): + if ipt_A[i] is None or ipt_B[i] is None: + continue + score = (ipt_A[i] * unc_A[i]).mean() + (ipt_B[i] * unc_B[i]).mean() + subspace_scores.append((module, i, score)) + + if not subspace_scores: + return + + # 2. Compute global threshold via kth-value + all_scores = torch.stack([s[2] for s in subspace_scores]) + if target_subspaces >= len(subspace_scores): + threshold = float("-inf") + else: + threshold = -torch.kthvalue(-all_scores, target_subspaces)[0].item() + + # 3. Apply masking + for module, idx, score in subspace_scores: + is_active = float(score) > threshold + param_A = module.adamss_A[adapter_name] + param_B = module.adamss_B[adapter_name] + if idx < len(param_A): + param_A[idx].requires_grad = is_active + if not is_active: + param_A[idx].grad = None + if idx < len(param_B): + param_B[idx].requires_grad = is_active + if not is_active: + param_B[idx].grad = None diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adamss/utils.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adamss/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7e20c95c5c120297df05ac6ac7261f221da5cae4 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adamss/utils.py @@ -0,0 +1,121 @@ +# Copyright 2026-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 + + +def slice_pca(tensor, r, device, dtype=torch.float32): + """ + Perform slice-wise PCA (SVD) on 4D tensor. + + Args: + tensor: 4D tensor of shape (B, C, H, W) + r: rank for low-rank approximation + device: computation device + dtype: data type + + Returns: + VVT: Right singular vectors (B, C, r, W) UU: Left singular vectors (B, C, H, r) + """ + tensor = tensor.to(device) + B, C, H, W = tensor.shape + + # Clamp r to the minimum dimension to avoid SVD errors + # SVD rank cannot exceed min(H, W) + effective_r = min(r, H, W) + + UU = torch.zeros(B, C, H, effective_r, dtype=dtype, device=device) + VVT = torch.zeros(B, C, effective_r, W, dtype=dtype, device=device) + + for i in range(B): + for j in range(C): + U, _, V = torch.svd_lowrank(tensor[i, j, :, :], q=effective_r, niter=2, M=None) + UU[i, j, :, :] = U[:, 0:effective_r] + VVT[i, j, :, :] = V[:, 0:effective_r].T + # Return computed matrices (important: ensure callers receive VVT and UU) + return VVT, UU + + +def clustering_Z(VT, num_subspaces, iternum): + """ + Cluster the rows of VT into K subspaces using K-Means. + + Args: + VT: Matrix to cluster (rows are clustered) + num_subspaces: Number of clusters (subspaces) + iternum: Maximum iterations for K-Means + + Returns: + cluster_idx: Cluster assignments as a ``torch.LongTensor`` effective_num_subspaces: Actual number of subspaces + used (``int``) + + Note: + This function requires scikit-learn to be installed. Install it with: pip install scikit-learn + """ + # Local import with helpful error message + try: + from sklearn.cluster import KMeans + except ImportError: + raise ImportError( + "scikit-learn is required for AdaMSS initialization. Please install it with: pip install scikit-learn" + ) + + # Move to numpy for sklearn compatibility + # Note: We do NOT normalize row vectors here to match the original adamss_pkg behavior. + # Although normalization is generally recommended for cosine-similarity-like clustering, + # the reference implementation clusters raw singular vectors. + vt = VT.detach().cpu().numpy().astype("float32") + + # Auto-clamp num_subspaces to available samples (output dimensions) + # Cannot cluster n samples into more than n clusters + effective_num_subspaces = min(num_subspaces, vt.shape[0]) + + kmeans = KMeans( + n_clusters=effective_num_subspaces, init="random", n_init=1, max_iter=iternum, random_state=123456789 + ) + idx = kmeans.fit_predict(vt) + + return torch.from_numpy(idx).long(), effective_num_subspaces + + +def seg_locations(index): + """ + Segment indices into locations based on cluster assignments. + + Args: + index: Cluster assignments as a ``torch.LongTensor`` + + Returns: + location: Dict mapping cluster id to ``torch.LongTensor`` of row indices. + Clusters are ordered by their smallest index so that KMeans label permutations do not affect downstream + ordering. + """ + K = int(index.max().item()) + 1 + location = {} + for i in range(K): + location[i] = torch.where(index == i)[0] + return location + + +def get_trainable_subspaces(num_subspaces): + """ + Get all trainable subspace indices. + + Args: + num_subspaces: Number of subspaces + + Returns: + List of trainable subspace indices (``list[int]``) + """ + return list(range(num_subspaces)) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adaption_prompt/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adaption_prompt/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..68882a222625eedc770d28816a3a0646964739bb --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adaption_prompt/__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 AdaptionPromptConfig +from .layer import AdaptedAttention +from .model import AdaptionPromptModel + + +__all__ = ["AdaptedAttention", "AdaptionPromptConfig", "AdaptionPromptModel"] + +register_peft_method(name="adaption_prompt", config_cls=AdaptionPromptConfig, model_cls=AdaptionPromptModel) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adaption_prompt/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adaption_prompt/config.py new file mode 100644 index 0000000000000000000000000000000000000000..4a9f780383d425fb551e2635017de9eaac3c2b81 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adaption_prompt/config.py @@ -0,0 +1,88 @@ +# 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 collections import namedtuple +from dataclasses import dataclass, field + +from peft.config import PeftConfig +from peft.utils import PeftType + +from .utils import gpt2_compute_query_states, llama_compute_query_states + + +@dataclass +class AdaptionPromptConfig(PeftConfig): + """Stores the configuration of an [`AdaptionPromptModel`].""" + + target_modules: str = field( + default=None, metadata={"help": "Name of the attention submodules to insert adaption prompts into."} + ) + adapter_len: int = field(default=None, metadata={"help": "Number of adapter tokens to insert"}) + adapter_layers: int = field(default=None, metadata={"help": "Number of adapter layers (from the top)"}) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.ADAPTION_PROMPT + + @property + def is_adaption_prompt(self) -> bool: + """Return True if this is an adaption prompt config.""" + return True + + +# Contains the config that is specific to a transformers model type. +ModelTypeConfig = namedtuple( + "ModelTypeConfig", ["compute_query_states", "target_modules", "k_proj_layer", "v_proj_layer", "o_proj_layer"] +) + +# Mapping of transformers model types to their specific configuration. +TRANSFORMERS_MODEL_CONFIG = { + "llama": ModelTypeConfig( + compute_query_states=llama_compute_query_states, + target_modules="self_attn", + k_proj_layer="k_proj", + v_proj_layer="v_proj", + o_proj_layer="o_proj", + ), + "mistral": ModelTypeConfig( # same as llama, + compute_query_states=llama_compute_query_states, + target_modules="self_attn", + k_proj_layer="k_proj", + v_proj_layer="v_proj", + o_proj_layer="o_proj", + ), + "gpt2": ModelTypeConfig( # piggybacking of off the prior definitions, GPTs attention calculation is different + compute_query_states=gpt2_compute_query_states, + target_modules="attn", + k_proj_layer="c_attn", + v_proj_layer=None, + o_proj_layer=None, + ), +} + + +def prepare_config( + peft_config: AdaptionPromptConfig, + model, +) -> AdaptionPromptConfig: + """Prepare the config based on the llama model type.""" + if model.config.model_type not in TRANSFORMERS_MODEL_CONFIG: + raise ValueError(f"Unsupported model type for adaption prompt: '{model.config.model_type}'.") + + model_config = TRANSFORMERS_MODEL_CONFIG[model.config.model_type] + + if peft_config.target_modules is None: + peft_config.target_modules = model_config.target_modules + + return peft_config diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adaption_prompt/layer.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adaption_prompt/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..f64067ad19c20023676fd33eb05454c0708b619b --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adaption_prompt/layer.py @@ -0,0 +1,223 @@ +# 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 Optional, Union + +import torch +import torch.nn.functional as F +from torch import nn + +from .config import TRANSFORMERS_MODEL_CONFIG + + +class _BaseAdaptedAttention(nn.Module): + """Base module, which defines adaption prompts for multiple model types.""" + + def __init__(self, model_type: str, adapter_len: int, model, target_dtype=torch.float32): + """ + Initialize object. + + Args: + model_type: The transformer model type. This is used to retrieve the right method to + compute query states. + adapter_len: The length of the adaption prompt to insert. + model: The original transformer attention module that is being wrapped. + """ + if isinstance(model, _BaseAdaptedAttention): + raise TypeError("Unable to stack multiple adaption prompts") + super().__init__() + self.model_type = model_type + self.model = model + self.adapter_len = adapter_len + # Assume all parameters of the attention model we are wrapping are on the same device. + + device = next(model.parameters()).device + # Don't think this was specified in the paper, but we follow the official repo which used an Embedding + # which initializes the tokens with standard normal values. + # https://github.com/ZrrSkywalker/LLaMA-Adapter/blob/41c3546fe1997ab8a65809dc8d8f9252b19d9faf/llama/model.py#L234 + # (bsz, adapter_len, hidden_size) + + hidden_size = self.model.config.hidden_size + self.num_heads = self.model.config.num_attention_heads + + self.adaption_prompt = nn.Parameter( + torch.empty(1, adapter_len, hidden_size, device=device, dtype=target_dtype).normal_() + ) + # Initialize the gate to 0 as this is "zero-init". + self.adaption_gate = nn.Parameter(torch.zeros(1, device=device, dtype=target_dtype)) + + +class AdaptedAttentionGPT(_BaseAdaptedAttention): + """This module wraps a GPT2Attention module and injects adaption prompts""" + + def __init__(self, model_type, adapter_len, model): + target_dtype = ( + model.c_proj.weight.dtype if model.c_proj.weight.dtype not in [torch.int8, torch.uint8] else torch.float32 + ) + super().__init__(model_type, adapter_len, model, target_dtype=target_dtype) + + def forward( + self, + hidden_states: Optional[tuple[torch.FloatTensor]], + layer_past: Optional[tuple[torch.Tensor]] = None, + attention_mask: Optional[torch.FloatTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.Tensor] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + use_cache: Optional[bool] = False, + output_attentions: Optional[bool] = False, + **kwargs, + ) -> tuple[Union[torch.Tensor, tuple[torch.Tensor]], ...]: + attn_outputs = self.model( + hidden_states=hidden_states, + attention_mask=attention_mask, + head_mask=head_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + use_cache=use_cache, + output_attentions=output_attentions, + **kwargs, + ) + """ + Forward pass for the adapter which wraps the GPT2Attention module + """ + + attn_output = attn_outputs[0] + add_outputs = attn_outputs[1:] + + c_attn_layer = TRANSFORMERS_MODEL_CONFIG[self.model_type].k_proj_layer + + bsz = attn_output.shape[0] + q_len = attn_output.shape[1] + embed_dim = attn_output.shape[2] + + _, key, value = getattr(self.model, c_attn_layer)(self.adaption_prompt).split(embed_dim, dim=2) + + adapter_k = ( + key.view(1, self.adapter_len, self.num_heads, self.model.head_dim).repeat(bsz, 1, 1, 1).transpose(1, 2) + ) + adapter_v = ( + value.view(1, self.adapter_len, self.num_heads, self.model.head_dim).repeat(bsz, 1, 1, 1).transpose(1, 2) + ) + # recompute query state since it is not returned by GPT2 forward + compute_query_states = TRANSFORMERS_MODEL_CONFIG[self.model_type].compute_query_states + query_states = compute_query_states( + self.model, hidden_states=hidden_states, encoder_hidden_states=encoder_hidden_states + ) + + previous_dtype = query_states.dtype + + scores = torch.matmul(query_states, adapter_k.transpose(2, 3).to(previous_dtype)) / math.sqrt( + self.model.head_dim + ) + # Upcast attention to fp32 + # (bsz, num_heads, q_len, adapter_len) + scores = self.adaption_gate * F.softmax(scores, dim=-1, dtype=torch.float32).to(previous_dtype) + # (bsz, q_len, num_heads * head_dim) + adapter_output = torch.matmul(scores, adapter_v).transpose(1, 2).reshape(bsz, q_len, -1) + + # Add adaption prompt output to original output. + hidden_state = attn_output + adapter_output + + # Restore original dtype. + hidden_state = hidden_state.to(previous_dtype) + + # add additional attention outputs (attention and cross attention) + output = (hidden_state,) + add_outputs + return output + + +class AdaptedAttention(_BaseAdaptedAttention): + """This module wraps a LLamaAttention module and injects adaption prompts.""" + + def __init__(self, model_type, adapter_len, model): + target_dtype = ( + model.q_proj.weight.dtype if model.q_proj.weight.dtype not in [torch.int8, torch.uint8] else torch.float32 + ) + super().__init__(model_type, adapter_len, model, target_dtype=target_dtype) + + def forward(self, **kwargs): + """ + Forward pass for the adapter which wraps the original LlamaAttention module. + + "Official" paper implementation: + https://github.com/ZrrSkywalker/LLaMA-Adapter/blob/41c3546fe1997ab8a65809dc8d8f9252b19d9faf/llama/model.py#L141 + + Args: + kwargs: See the original LlamaAttention module. + """ + if kwargs.get("output_attention", False): + raise NotImplementedError("output_attention is not currently supported.") + + output, *_ = self.model(**kwargs) + bsz = output.shape[0] + q_len = output.shape[1] + embed_dim = output.shape[2] + k_proj_layer = TRANSFORMERS_MODEL_CONFIG[self.model_type].k_proj_layer + v_proj_layer = TRANSFORMERS_MODEL_CONFIG[self.model_type].v_proj_layer + o_proj_layer = TRANSFORMERS_MODEL_CONFIG[self.model_type].o_proj_layer + factor = ( + self.model.k_proj.in_features // self.model.k_proj.out_features + ) # Mistral has different input and output dimension for k_proj and v_proj layers + + if k_proj_layer == v_proj_layer: + _, key, value = getattr(self.model, k_proj_layer)(self.adaption_prompt).split(embed_dim, dim=2) + else: + key = getattr(self.model, k_proj_layer)(self.adaption_prompt) + value = getattr(self.model, v_proj_layer)(self.adaption_prompt) + + num_heads = self.model.config.num_attention_heads + # (bsz, num_key_value_heads, adapter_len, head_dim) + adapter_k = ( + key.view(1, self.adapter_len, (num_heads // factor), self.model.head_dim) + .repeat(bsz, 1, 1, 1) + .transpose(1, 2) + ) + adapter_v = ( + value.view(1, self.adapter_len, (num_heads // factor), self.model.head_dim) + .repeat(bsz, 1, 1, 1) + .transpose(1, 2) + ) + # Below is taken from https://github.com/huggingface/transformers/blob/e547458c43dfdbbb8f6a7757237e234c44e20a8f/src/transformers/models/mistral/modeling_mistral.py#L181 + # (bsz, num_heads, adapter_len, head_dim) + adapter_k = torch.repeat_interleave(adapter_k, repeats=factor, dim=1) + adapter_v = torch.repeat_interleave(adapter_v, repeats=factor, dim=1) + # Recompute query states. + compute_query_states = TRANSFORMERS_MODEL_CONFIG[self.model_type].compute_query_states + # (bsz, num_heads, q_len, head_dim) + query_states = compute_query_states(model=self.model, **kwargs) + + previous_dtype = query_states.dtype + + # (bsz, num_heads, q_len, adapter_len) + scores = torch.matmul(query_states, adapter_k.transpose(2, 3).to(previous_dtype)) / math.sqrt( + self.model.head_dim + ) + # Upcast attention to fp32 + # (bsz, num_heads, q_len, adapter_len) + scores = self.adaption_gate * F.softmax(scores, dim=-1, dtype=torch.float32).to(previous_dtype) + # (bsz, q_len, num_heads * head_dim) + adapter_output = torch.matmul(scores, adapter_v).transpose(1, 2).reshape(bsz, q_len, -1) + + # (bsz, q_len, hidden_size) + if o_proj_layer is not None: + adapter_output = getattr(self.model, o_proj_layer)(adapter_output) + + # Add adaption prompt output to original output. + output = output + adapter_output + + # Restore original dtype. + output = output.to(previous_dtype) + return output, *_ diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adaption_prompt/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adaption_prompt/model.py new file mode 100644 index 0000000000000000000000000000000000000000..4e76ce6c2f5938a0404c6bc9dc3adede59da89d2 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adaption_prompt/model.py @@ -0,0 +1,171 @@ +# 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 torch import nn + +from peft.utils import _freeze_adapter, _get_submodules + +from .config import AdaptionPromptConfig, prepare_config +from .layer import AdaptedAttention, AdaptedAttentionGPT +from .utils import is_adaption_prompt_trainable + + +class AdaptionPromptModel(nn.Module): + """ + Implements adaption prompts as described in https://huggingface.co/papers/2303.16199. + + The top L attention modules are replaced with AdaptedAttention modules that wrap the original ones, but insert + trainable prompts with gates (for zero init). + + Notes on the multi-adapter pattern: + - We store the states of different adapters by keeping a dictionary of AdaptedAttention modules indexed by adapter + name. + - Every time we switch adapters, we remove the modules of the currently active adapter from the model, store them + in the dictionary, and replace them with the modules of the new adapter. + - To avoid duplicated and potentially inconsistent state, the currently active adapter is always removed from the + dictionary. + - Disabling the adapter would also result in the modules being removed from the model. + """ + + def __init__(self, model, configs: dict, adapter_name: str): + super().__init__() + self.model = model + # Store adapter configs by name. + self.peft_config: dict[str, AdaptionPromptConfig] = {} + # Store lists of the parents of the affected attention modules by adapter name. + # We keep references to the parents so we can swap the adapters in-and-out of the model. + self._parents: dict[str, list[nn.Module]] = {} + # Store lists of cached AdaptedAttention modules by name. + self._cached_adapters: dict[str, list] = {} + # The name of the currently active adapter. + self._active_adapter = None + # Whether the adapter is enabled. + self._enabled = True + self.forward = self.model.forward + self.add_adapter(adapter_name, configs[adapter_name]) + self._mark_only_adaption_prompts_as_trainable(self.model) + + def add_adapter(self, adapter_name: str, config: AdaptionPromptConfig) -> None: + """Add an adapter with the given name and config.""" + config = prepare_config(config, self.model) + if adapter_name in self.peft_config: + raise ValueError(f"Adapter with name '{adapter_name}' already exists.") + + parents = [] + for name, _ in self.model.named_modules(): + if name.endswith(f".{config.target_modules}"): + par, _, _ = _get_submodules(self.model, name) + parents.append(par) + if len(parents) < config.adapter_layers: + raise ValueError( + f"Config specifies more adapter layers '{config.adapter_layers}' than the model has '{len(parents)}'." + ) + # Note that if the target modules are not in Sequential, ModuleList, or + # some other PyTorch ordered container, the behavior is undefined as we + # assume here that the order of the modules is the same as the order of + # the transformer decoder layers. + parents = parents[-config.adapter_layers :] + self._parents[adapter_name] = parents + + # It is only None during initialization. + # If it is disabled, we don't have to remove the modules. + if self._active_adapter is not None and self._enabled: + self._remove_adapted_attentions(self._active_adapter) + self._active_adapter = adapter_name + self.peft_config[adapter_name] = config + self._create_adapted_attentions(config, parents) + if not self._enabled: + self._remove_adapted_attentions(self._active_adapter) + + if config.inference_mode: + _freeze_adapter(self.model, adapter_name) + + def set_adapter(self, adapter_name: str, inference_mode: bool = False) -> None: + """Set the model to use the adapter with the given name.""" + if inference_mode: + raise ValueError("inference_mode is not supported for AdaptionPromptModel.") + if self._active_adapter == adapter_name: + return + if adapter_name not in self.peft_config: + raise ValueError(f"Adapter with name '{adapter_name}' does not exist.") + + if self._enabled: + self._remove_adapted_attentions(self._active_adapter) + self._set_adapted_attentions(adapter_name) + + self._active_adapter = adapter_name + + def enable_adapter_layers(self): + """Enable adapter layers by swapping in cached AdaptedAttention modules.""" + self._enabled = True + self._set_adapted_attentions(self._active_adapter) + + def disable_adapter_layers(self): + """Disable adapter layers by swapping out AdaptedAttention modules.""" + self._enabled = False + self._remove_adapted_attentions(self._active_adapter) + + def _create_adapted_attentions(self, config: AdaptionPromptConfig, parents: list[nn.Module]) -> None: + """Wrap LlamaAttention modules with newly created AdaptedAttention modules.""" + for par in parents: + if self.model.config.model_type == "gpt2": + attn = AdaptedAttentionGPT( + model_type=self.model.config.model_type, + adapter_len=config.adapter_len, + model=getattr(par, config.target_modules), + ) + + else: + attn = AdaptedAttention( + model_type=self.model.config.model_type, + adapter_len=config.adapter_len, + model=getattr(par, config.target_modules), + ) + setattr(par, config.target_modules, attn) + + def _set_adapted_attentions(self, adapter_name: str) -> None: + """Replace LlamaAttention modules with cached AdaptedAttention modules.""" + cached = self._cached_adapters[adapter_name] + del self._cached_adapters[adapter_name] + config = self.peft_config[adapter_name] + for i, par in enumerate(self._parents[adapter_name]): + setattr(par, config.target_modules, cached[i]) + + def _remove_adapted_attentions(self, adapter_name: str) -> None: + """Remove AdaptedAttention modules from the model and store them in the cache.""" + config = self.peft_config[adapter_name] + adapted_attentions = [] + for par in self._parents[adapter_name]: + attn = getattr(par, config.target_modules) + adapted_attentions.append(attn) + setattr(par, config.target_modules, attn.model) + self._cached_adapters[adapter_name] = adapted_attentions + + def _mark_only_adaption_prompts_as_trainable(self, model: nn.Module) -> None: + """Freeze all parameters of the model except the adaption prompts.""" + for n, p in model.named_parameters(): + if not is_adaption_prompt_trainable(n): + p.requires_grad = False + + def __getattr__(self, name: str): + """Forward missing attributes to the wrapped module.""" + try: + return super().__getattr__(name) # defer to nn.Module's logic + except AttributeError: + # This is necessary as e.g. causal models have various methods that we + # don't want to re-implement here. + if name == "model": # see #1892: prevent infinite recursion if class is not initialized + raise + return getattr(self.model, name) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adaption_prompt/utils.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adaption_prompt/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..35af28e0d78b7b8968410d45d4ae440e24e3fa52 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adaption_prompt/utils.py @@ -0,0 +1,154 @@ +# 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 inspect +from typing import Optional + +import torch +from torch import nn + + +def llama_rotate_half(x: torch.Tensor) -> torch.Tensor: + """ + Rotate half the hidden dims of the input. + + This function was duplicated verbatim from: + https://github.com/huggingface/transformers/blob/1de8ce9ee1191ba761a593ac15d9ccbf5851bfc5/src/transformers/models/llama/modeling_llama.py#L126 + + This was done to eliminate the Llama transformers implementation as a dependency of this file. Note that some other + functions were also adapted from the transformers implementation but were modified. + """ + x1 = x[..., : x.shape[-1] // 2] + x2 = x[..., x.shape[-1] // 2 :] + return torch.cat((-x2, x1), dim=-1) + + +def llama_apply_rotary_pos_emb(q, cos, sin, position_ids): + """ + Apply rotary position embedding to query states in the Llama model. + + This function was adapted from: + https://github.com/huggingface/transformers/blob/1de8ce9ee1191ba761a593ac15d9ccbf5851bfc5/src/transformers/models/llama/modeling_llama.py#L133 + + It was modified to remove unnecessary processing of key states. The method is compatible with transformers <= + 4.34.2 and also with the latest version (>=4.35). + """ + # In previous transformers version cos/sin cached had a shape of 4D + if len(cos.shape) == 4: + gather_indices = position_ids[:, None, :, None] # [bs, 1, seq_len, 1] + gather_indices = gather_indices.repeat(1, cos.shape[1], 1, cos.shape[3]) + cos = torch.gather(cos.repeat(gather_indices.shape[0], 1, 1, 1), 2, gather_indices) + sin = torch.gather(sin.repeat(gather_indices.shape[0], 1, 1, 1), 2, gather_indices) + # In the new version, it is 2D so we fall back to the new implementation + # https://github.com/huggingface/transformers/blame/eef7ea98c31a333bacdc7ae7a2372bde772be8e4/src/transformers/models/llama/modeling_llama.py#L222-L226 + else: + cos = cos[position_ids].unsqueeze(1) + sin = sin[position_ids].unsqueeze(1) + q_embed = (q * cos) + (llama_rotate_half(q) * sin) + return q_embed + + +def llama_compute_query_states(model: nn.Module, **kwargs) -> torch.Tensor: + """ + Compute query states for Llama models specifically. They need to be recomputed as the forward() method of the + original LlamaModel in the transformers library does not return them. See the related discussion in the PR: + https://github.com/huggingface/peft/pull/268 + """ + hidden_states = kwargs.get("hidden_states") + position_ids = kwargs.get("position_ids") + past_key_value = kwargs.get("past_key_value") + bsz, q_len, _ = hidden_states.size() + num_heads = model.config.num_attention_heads + query_states = model.q_proj(hidden_states).view(bsz, q_len, num_heads, model.head_dim).transpose(1, 2) + + factor = model.k_proj.in_features // model.k_proj.out_features + value_states = model.v_proj(hidden_states).view(bsz, q_len, (num_heads // factor), model.head_dim).transpose(1, 2) + + seq_len = q_len + + if past_key_value is not None: + if isinstance(past_key_value, tuple): + # for transformers <= 4.35 + seq_len += past_key_value[0].shape[-2] + else: + # since transformers 4.36, this is a DynamicCache instance + seq_len += past_key_value.get_seq_length(model.layer_idx) + + # model.rotary_emb is deprecated and will be removed in transformers > 4.47.0. Instead, the position embeddings are + # passed via the kwargs + if "position_embeddings" in kwargs: + cos, sin = kwargs["position_embeddings"] + cos = cos.unsqueeze(1) + sin = sin.unsqueeze(1) + return (query_states * cos) + (llama_rotate_half(query_states) * sin) + + # For transformers > 4.37.2 `position_ids` became a required arguments in the rotary embedding's forward pass. + if "position_ids" not in inspect.signature(model.rotary_emb.forward).parameters: + # TODO we assume that position_ids is not None here, not sure if that is safe but the old code also did that + cos, sin = model.rotary_emb(value_states, seq_len=seq_len) + return llama_apply_rotary_pos_emb(query_states, cos, sin, position_ids) + + past_seen_tokens = 0 + if position_ids is None: + # Compute position_ids, since they are required for transformers > 4.37.2 + if past_key_value is None: + new_cache_positions = torch.arange(q_len, q_len + q_len, device=value_states.device) + else: + past_seen_tokens = past_key_value.get_usable_length(q_len, model.layer_idx) + new_cache_positions = torch.arange(past_seen_tokens, past_seen_tokens + q_len, device=value_states.device) + position_ids = new_cache_positions.unsqueeze(0) + + rotary_emb_kwargs = {"position_ids": position_ids} + # The `seq_len` argument has been officially removed in transformers >= 4.39.0 + if "seq_len" in inspect.signature(model.rotary_emb.forward).parameters: + rotary_emb_kwargs["seq_len"] = q_len + past_seen_tokens + + cos, sin = model.rotary_emb(value_states, **rotary_emb_kwargs) + + # For batched inference unsqueeze it on the correct dim + # since: https://github.com/huggingface/transformers/pull/29109 + if len(cos.shape) == 3: + cos = cos.unsqueeze(1) + sin = sin.unsqueeze(1) + + return (query_states * cos) + (llama_rotate_half(query_states) * sin) + + +def gpt2_compute_query_states( + model: nn.Module, + hidden_states: Optional[tuple[torch.FloatTensor]], + encoder_hidden_states: Optional[torch.Tensor] = None, +) -> torch.Tensor: + """ + Compute query states for GPT2 models. They need to be recomputed as the forward() method of the GPT@ in the + transformers library does not return them. See the related discussion in the PR: + """ + if encoder_hidden_states is not None: + if not hasattr(model, "q_attn"): + raise ValueError( + f"If `{model.__class__.__name__}` is used as cross attention, the weights `q_attn` must be defined. " + f"Please make sure to instantiate it with `GPT2Attention(..., is_cross_attention=True)`." + ) + query_states = model.q_attn(hidden_states) + else: + query_states, _, _ = model.c_attn(hidden_states).split(model.split_size, dim=2) + + shape_q = (*query_states.shape[:-1], -1, model.head_dim) + query_states = query_states.view(shape_q).transpose(1, 2) + + return query_states + + +def is_adaption_prompt_trainable(params: str) -> bool: + """Return True if module is trainable under adaption prompt fine-tuning.""" + return params.split(".")[-1].startswith("adaption_") diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/beft/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/beft/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..185f8f5f2ed04c6b392db9f7a877e0f9185fde21 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/beft/__init__.py @@ -0,0 +1,24 @@ +# Copyright 2026-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 BeftConfig +from .layer import BeftLayer, Linear +from .model import BeftModel + + +__all__ = ["BeftConfig", "BeftLayer", "BeftModel", "Linear"] +register_peft_method(name="beft", config_cls=BeftConfig, model_cls=BeftModel, is_mixed_compatible=True) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/beft/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/beft/config.py new file mode 100644 index 0000000000000000000000000000000000000000..e6c8328b5b58c4426aa0d4a8d4cfc14f35fa3a3c --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/beft/config.py @@ -0,0 +1,73 @@ +# Copyright 2026-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 BeftConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`BeftModel`]. + + Args: + 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 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. + modules_to_save (`Optional[List[str]]`): + List of modules apart from BEFT layers to be set as trainable and saved in the final checkpoint. + init_weights (`bool`): + Whether to initialize the vectors in the BEFT layers, defaults to `True`. Setting this to `False` is + discouraged. + """ + + 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 BEFT." + "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'." + "If 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." + ), + }, + ) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": "List of modules apart from BEFT 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 vectors in the BEFT layers."}, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.BEFT + self.target_modules = ( + set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules + ) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/beft/layer.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/beft/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..66665294aeecfd75ee44014decc5c12362d5cb5f --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/beft/layer.py @@ -0,0 +1,166 @@ +# Copyright 2026-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 Any, Optional + +import torch +from torch import nn + +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge + +from .config import BeftConfig + + +class BeftLayer(BaseTunerLayer): + # All names of layers that may contain adapter weights + adapter_layer_names = ("beft_bias",) + + def __init__(self, base_layer: nn.Module, **kwargs) -> None: + self.base_layer = base_layer + self.beft_bias = nn.ParameterDict({}) + # 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 TypeError(f"Unsupported layer type {type(base_layer)}") + self.in_features = in_features + self.out_features = out_features + + def update_layer(self, adapter_name: str, config: BeftConfig, **kwargs): + base_layer = self.get_base_layer() + if base_layer.bias is None: + warnings.warn( + "Detected that the base layer has no bias term. " + "Note you cannot merge the BEFT adapter into the base layer." + ) + init_weights = config.init_weights + inference_mode = config.inference_mode + weight = torch.randn((1, self.out_features)) + self.beft_bias[adapter_name] = nn.Parameter(weight) + if init_weights: + self.reset_beft_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_beft_parameters(self, adapter_name): + if adapter_name in self.beft_bias.keys(): + nn.init.constant_(self.beft_bias[adapter_name], 0.0) + + +class Linear(nn.Module, BeftLayer): + # BEFT implemented in a dense layer + def __init__( + self, + base_layer: nn.Module, + adapter_name: str, + config: BeftConfig, + **kwargs, + ) -> None: + super().__init__() + BeftLayer.__init__(self, base_layer) + self._active_adapter = adapter_name + self.update_layer(adapter_name, config=config) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter bias into the base bias + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original bias and check for NaNs before + merging the bias. 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.beft_bias.keys(): + base_layer = self.get_base_layer() + + if base_layer.bias is None: + raise ValueError(f"Base layer has no bias, cannot merge bias adapter {active_adapter}") + + orig_dtype = base_layer.bias.data.dtype + beft_bias = self.beft_bias[active_adapter].data + + if safe_merge: + output_bias = (base_layer.bias.data + beft_bias.squeeze()).clone() + + if not torch.isfinite(output_bias).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.bias.data = output_bias.to(orig_dtype) + else: + base_layer.bias.data.add_(beft_bias.squeeze()).to(orig_dtype) + + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base bias. + """ + 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.beft_bias.keys(): + base_layer = self.get_base_layer() + + if base_layer.bias is None: + raise ValueError(f"Base layer has no bias, cannot unmerge bias adapter {active_adapter}") + + orig_dtype = base_layer.bias.data.dtype + # minus BEFT bias. + beft_bias = self.beft_bias[active_adapter].data + base_layer.bias.data = (base_layer.bias.data - beft_bias.squeeze()).to(orig_dtype) + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> 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: + beft_bias = None + for active_adapter in self.active_adapters: + if active_adapter not in self.beft_bias.keys(): + continue + current_bias = self.beft_bias[active_adapter].flatten() + if beft_bias is None: + beft_bias = current_bias + else: + beft_bias = beft_bias + current_bias + + result = self.base_layer(x, *args, **kwargs) + if beft_bias is not None: + orig_dtype = result.dtype + result = (result + beft_bias).to(orig_dtype) + + return result diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/beft/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/beft/model.py new file mode 100644 index 0000000000000000000000000000000000000000..ea041a94fa1ed952e24360ce9051970157c22624 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/beft/model.py @@ -0,0 +1,103 @@ +# Copyright 2026-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 + +from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer +from peft.utils import ( + TRANSFORMERS_MODELS_TO_BEFT_TARGET_MODULES_MAPPING, +) + +from .layer import BeftLayer, Linear + + +class BeftModel(BaseTuner): + """ + Creates a Infused Adapter by only fine-tuning the added bias terms of value projections from a pretrained + transformers model in low-training-data regimes (BEFT). The method is described in detail in + https://arxiv.org/abs/2509.15974 + + Args: + model ([`~transformers.PreTrainedModel`]): The model to be adapted. + config ([`BeftConfig`]): The configuration of the (BEFT) 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 (BEFT) model. + + Example: + + ```py + >>> from transformers import AutoModelForSeq2SeqLM + >>> from peft import BeftModel, BeftConfig + + >>> config = BeftConfig( + ... peft_type="Beft", + ... task_type="SEQ_2_SEQ_LM", + ... target_modules=["v"], + ... ) + + >>> model = AutoModelForSeq2SeqLM.from_pretrained("t5-base") + >>> beft_model = BeftModel(model, config, adapter_name="default") + ``` + + **Attributes**: + - **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted. + - **peft_config** ([`BeftConfig`]): The configuration of the (BEFT) model. + """ + + prefix: str = "beft_" + tuner_layer_cls = BeftLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_BEFT_TARGET_MODULES_MAPPING + + @staticmethod + def _create_new_module(beft_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): + new_module = Linear(target, adapter_name, config=beft_config, **kwargs) + else: + raise TypeError( + f"Target module {target} is not supported. Currently, only `torch.nn.Linear` is supported." + ) + return new_module + + def _create_and_replace( + self, + beft_config, + adapter_name, + target, + target_name, + parent, + current_key, + ): + kwargs = {} + + if isinstance(target, BeftLayer): + target.update_layer( + adapter_name, + config=beft_config, + ) + else: + new_module = self._create_new_module(beft_config, adapter_name, target, **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) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/boft/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/boft/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c84b8358da8fc52d3f332c195f22b8b9620c665f --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/boft/__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 BOFTConfig +from .layer import BOFTLayer +from .model import BOFTModel + + +__all__ = ["BOFTConfig", "BOFTLayer", "BOFTModel"] + +register_peft_method(name="boft", config_cls=BOFTConfig, model_cls=BOFTModel) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/boft/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/boft/config.py new file mode 100644 index 0000000000000000000000000000000000000000..1715cc5bc65c190d3ba4dd160707d3fb0c93307a --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/boft/config.py @@ -0,0 +1,160 @@ +# 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. + +# The implementation is based on "Parameter-Efficient Orthogonal Finetuning +# via Butterfly Factorization" (https://huggingface.co/papers/2311.06243) in ICLR 2024. + +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 BOFTConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`BOFTModel`]. + + Args: + boft_block_size (`int`): BOFT block size across different layers. + boft_block_num (`int`): Number of BOFT blocks per injected layer. + boft_n_butterfly_factor (`int`): Number of butterfly factors across different layers. + target_modules (`Union[List[str],str]`): The names of the modules to apply the adapter 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. + boft_dropout (`float`): + The multiplicative dropout probability, by setting OFT blocks to identity during training, similar to the + dropout layer in LoRA. + 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 for BOFT. Can be 'none', 'all' or 'boft_only'. If 'all' or 'boft_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 BOFT layers to be set as trainable + and saved in the final checkpoint. + layers_to_transform (`Union[List[int],int]`): + The layer indexes to transform, if this argument is specified, it will apply the BOFT transformations on + the layer indexes that are specified in this list. If a single integer is passed, it will apply the BOFT + 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` 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'`. + """ + + boft_block_size: int = field( + default=4, + metadata={ + "help": "BOFT block size across different layers.", + "note": "You can only specify either boft_block_size or boft_block_num, but not both simultaneously, because boft_block_size x boft_block_num = layer dimension.", + }, + ) + boft_block_num: int = field( + default=0, + metadata={ + "help": "Number of BOFT blocks per injected layer.", + "note": "You can only specify either boft_block_size or boft_block_num, but not both simultaneously, because boft_block_size x boft_block_num = layer dimension.", + }, + ) + boft_n_butterfly_factor: int = field( + default=1, + metadata={ + "help": "Number of butterfly factors.", + "note": ( + "for example, boft_n_butterfly_factor=2, the effective block size of OFT becomes twice as big and the number of blocks become half.", + "note: for boft_n_butterfly_factor=1, BOFT is the same as vanilla OFT.", + ), + }, + ) + 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 BOFT.", + "example": "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 BOFT."}, + ) + boft_dropout: float = field( + default=0.0, + metadata={ + "help": "BOFT multiplicative dropout, randomly setting blocks of OFT to be identity matrix, similar to the dropout layer in LoRA." + }, + ) + 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: str = field(default="none", metadata={"help": "Bias type for BOFT. Can be 'none', 'all' or 'boft_only'"}) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": "List of modules apart from BOFT layers to be set as trainable and saved in the final checkpoint. ", + "note": ( + "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 BOFT 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'`." + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.BOFT + 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.boft_block_size == 0 and self.boft_block_num == 0: + raise ValueError( + f"Either `boft_block_size` or `boft_block_num` must be non-zero. Currently, boft_block_size = {self.boft_block_size} and boft_block_num = {self.boft_block_num}." + ) + if not (self.boft_block_size != 0) ^ (self.boft_block_num != 0): + raise ValueError( + f"You can only specify either boft_block_size ({self.boft_block_size}) or boft_block_num ({self.boft_block_num}), but not both simultaneously, because boft_block_size x boft_block_num == in_features." + ) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/boft/fbd/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/boft/fbd/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/boft/fbd/fbd_cuda.cpp b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/boft/fbd/fbd_cuda.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d63111b04083f3b1359aba0a9de9656060a4d515 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/boft/fbd/fbd_cuda.cpp @@ -0,0 +1,28 @@ +#include +#include +#include +#include + +std::vector forward_fast_block_diag_cuda( + at::Tensor input); + +std::vector forward_fast_block_diag( + at::Tensor input + ) { + return forward_fast_block_diag_cuda(input); +} + +std::vector backward_fast_block_diag_cuda( + at::Tensor grad_output, + at::Tensor input); +std::vector backward_fast_block_diag( + at::Tensor grad_output, + at::Tensor input + ) { + return backward_fast_block_diag_cuda(grad_output, input); +} + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + m.def("forward", &forward_fast_block_diag, "FAST BLOCK DIAG (CUDA)"); + m.def("backward", &backward_fast_block_diag, "FAST BLOCK DIAG backward (CUDA)"); +} diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/boft/fbd/fbd_cuda_kernel.cu b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/boft/fbd/fbd_cuda_kernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..9f307455349e6ea8067d47ebf8a39b98ba452d09 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/boft/fbd/fbd_cuda_kernel.cu @@ -0,0 +1,109 @@ +// Author: Yao Feng +// Date: 2023/08 +// Description: cuda kernel for fast block diag + +#include + +#include +#include +#include + +namespace{ +template +__global__ void forward_fast_block_diag_cuda_kernel( + const scalar_t* __restrict__ input, //[z, N, b, b] + scalar_t* output, //[z, Nxb, Nxb] + int z, int N, int b + ) { + + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= z*N*b*b) { + return; + } + const int zi = i/(N*b*b); + const int Ni = (i%(N*b*b))/(b*b); + const int x = ((i%(N*b*b))%(b*b))/b; + const int y = ((i%(N*b*b))%(b*b))%b; + + output[zi*N*b*N*b + (Ni*b+x)*N*b + Ni*b + y] = input[zi*N*b*b + Ni*b*b + x*b + y]; + +} + +template +__global__ void backward_fast_block_diag_cuda_kernel( + const scalar_t* __restrict__ grad_output, + scalar_t* grad_input, + int z, int N, int b + ) { + + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= z*N*b*b) { + return; + } + const int zi = i/(N*b*b); + const int Ni = (i%(N*b*b))/(b*b); + const int x = ((i%(N*b*b))%(b*b))/b; + const int y = ((i%(N*b*b))%(b*b))%b; + + grad_input[zi*N*b*b + Ni*b*b + x*b + y] = grad_output[zi*N*b*N*b + (Ni*b+x)*N*b + Ni*b + y]; + +} // namespace +} + +std::vector forward_fast_block_diag_cuda( + at::Tensor input + ){ + const auto z = input.size(0); + const auto N = input.size(1); + const auto b = input.size(2); + + // print(channel_size) + const int threads = 512; + const dim3 blocks_1 ((z*N*b*b - 1) / threads +1); + // initlaize output + auto output = at::zeros({z, N*b, N*b}, input.options()); + + AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.type(), "forward_fast_block_diag1", ([&] { + forward_fast_block_diag_cuda_kernel<<>>( + input.data_ptr(), + output.data_ptr(), + z, N, b); + })); + + + cudaError_t err = cudaGetLastError(); + if (err != cudaSuccess) + printf("Error in forward_fast_block_diag_cuda_kernel: %s\n", cudaGetErrorString(err)); + + return {output}; +} + +std::vector backward_fast_block_diag_cuda( + at::Tensor grad_output, + at::Tensor input + ){ + + const auto z = input.size(0); + const auto N = input.size(1); + const auto b = input.size(2); + + // print(channel_size) + const int threads = 512; + const dim3 blocks_1 ((z*N*b*b - 1) / threads +1); + + // initialize grad input + auto grad_input = at::zeros_like(input); + + AT_DISPATCH_FLOATING_TYPES_AND_HALF(grad_output.type(), "backward_fast_block_diag", ([&] { + backward_fast_block_diag_cuda_kernel<<>>( + grad_output.data_ptr(), + grad_input.data_ptr(), + z, N, b); + })); + + cudaError_t err = cudaGetLastError(); + if (err != cudaSuccess) + printf("Error in backward_fast_block_diag_cuda_kernel: %s\n", cudaGetErrorString(err)); + + return {grad_input}; +} diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/boft/layer.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/boft/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..febf80c2c8f0c378b2069d934aa1bd5246926b8d --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/boft/layer.py @@ -0,0 +1,1001 @@ +# 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. + +# The implementation is based on "Parameter-Efficient Orthogonal Finetuning +# via Butterfly Factorization" (https://huggingface.co/papers/2311.06243) in ICLR 2024. + +from __future__ import annotations + +import math +import os +import warnings +from contextlib import contextmanager +from typing import Any, Optional + +import torch +import torch.nn.functional as F +from torch import nn +from torch.autograd import Function + +from peft.tuners.tuners_utils import BaseTunerLayer, _get_in_out_features, check_adapters_to_merge +from peft.utils import quantization_extra_repr, resolve_quantization_backend + +from .config import BOFTConfig + + +_FBD_CUDA = None + + +# this function is a 1:1 copy from accelerate +@contextmanager +def patch_environment(**kwargs): + """ + A context manager that will add each keyword argument passed to `os.environ` and remove them when exiting. + + Will convert the values in `kwargs` to strings and upper-case all the keys. + + Example: + + ```python + >>> import os + >>> from accelerate.utils import patch_environment + + >>> with patch_environment(FOO="bar"): + ... print(os.environ["FOO"]) # prints "bar" + >>> print(os.environ["FOO"]) # raises KeyError + ``` + """ + existing_vars = {} + for key, value in kwargs.items(): + key = key.upper() + if key in os.environ: + existing_vars[key] = os.environ[key] + os.environ[key] = str(value) + + yield + + for key in kwargs: + key = key.upper() + if key in existing_vars: + # restore previous value + os.environ[key] = existing_vars[key] + else: + os.environ.pop(key, None) + + +def get_fbd_cuda(): + global _FBD_CUDA + + if _FBD_CUDA is not None: + return _FBD_CUDA + + # This import initializes cuda context and should thus be local, see issue 1877 + from torch.utils.cpp_extension import load + + curr_dir = os.path.dirname(__file__) + # need ninja to build the extension + try: + with patch_environment(CC="gcc", CXX="gcc"): + fbd_cuda = load( + name="fbd_cuda", + sources=[f"{curr_dir}/fbd/fbd_cuda.cpp", f"{curr_dir}/fbd/fbd_cuda_kernel.cu"], + verbose=True, + # build_directory='/tmp/' # for debugging + ) + # extra_cuda_cflags = ['-std=c++14', '-ccbin=$$(which gcc-7)']) # cuda10.2 is not compatible with gcc9. Specify gcc 7 + except Exception as e: + warnings.warn(f"Failed to load the CUDA extension: {e}, check if ninja is available.") + warnings.warn("Setting boft_n_butterfly_factor to 1 to speed up the finetuning process.") + fbd_cuda = None + + _FBD_CUDA = fbd_cuda + return _FBD_CUDA + + +class FastBlockDiag(Function): + """ + Implements a custom autograd Function for a fast block diagonal operation using CUDA. + + This function is optimized for 4D tensors where the last two dimensions are equal, representing block diagonal + matrices for efficient computation on CUDA devices. + """ + + @staticmethod + def forward(ctx, input): + """ + The forward method for FastBlockDiag. + + Computes the block diagonal operation on the input tensor using a CUDA-optimized function. This method assumes + that the input is a 4D tensor where the last two dimensions are equal, which represent the blocks to be + diagonalized. + + Parameters: + ctx: A context object that can be used to stash information for backward computation. + input (Tensor): The input tensor of shape (N, D, H, H), where `N` is the batch size, + `D` represents one additional dimension (In BOFT, the number of BOFT blocks), and `H` is the + size of the square blocks along the last two dimensions (In BOFT, the block size). + + Returns: + Tensor: The resulting tensor after applying the block diagonal operation, + will have the shape (N, DxH, DxH). + """ + output = get_fbd_cuda().forward(input)[0] + ctx.save_for_backward(input) + return output + + @staticmethod + def backward(ctx, grad_output): + (input,) = ctx.saved_tensors + grad_input = get_fbd_cuda().backward(grad_output, input)[0] + return grad_input + + +class MultiplicativeDropoutLayer(nn.Module): + """ + Implements the multiplicative dropout layer for BOFT. + """ + + 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 (N, D, H, H), where `N` is the batch size, `D` represents + one additional dimension (In BOFT, the number of BOFT blocks), and `H` is the size of the square + blocks along the last two dimensions (In BOFT, the block size). + """ + if self.training: + # 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!") + + N, D, H, _ = x.shape + + # Randomly select one from N + n_random = torch.randint(0, N, (1,)).item() + + # Create a mask with 1s for matrices to be replaced with identity and 0s otherwise + num_to_replace = int(self.p * D) + num_zeros = D - num_to_replace + + # Generate a flat tensor with desired number of 1s and 0s + mask = torch.cat([torch.ones(num_to_replace, device=x.device), torch.zeros(num_zeros, device=x.device)]) + + # Shuffle and reshape the mask + mask = mask[torch.randperm(D)].view(1, D, 1, 1) + + full_mask = torch.zeros(N, D, 1, 1, device=x.device) + full_mask[n_random] = mask + + # Use the mask to combine original matrices and identity matrices + eye_matrix = torch.eye(H, device=x.device).repeat(N, D, 1, 1) + x = (1 - full_mask) * x + full_mask * eye_matrix + return x + + +class BOFTLayer(BaseTunerLayer): + """ + Implements the BOFT layer. + """ + + # All names of layers that may contain (trainable) adapter weights + adapter_layer_names = ("boft_R", "boft_s") + # All names of other parameters that may contain adapter-related parameters + other_param_names = ("boft_block_size", "boft_block_num", "boft_dropout") + + def __init__(self, base_layer: nn.Module, **kwargs) -> None: + """ + Initializes the BOFT 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.quantization_backend = resolve_quantization_backend( + self.get_base_layer(), get_apply_tensor_subclass=kwargs.get("get_apply_tensor_subclass") + ) + self.boft_block_size = {} + self.boft_block_num = {} + self.boft_dropout = nn.ModuleDict({}) + self.boft_R = nn.ParameterDict({}) + self.boft_s = nn.ParameterDict({}) + # 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() + + in_features, out_features = _get_in_out_features(base_layer) + if (in_features is None) or (out_features is None): + raise TypeError(f"Unsupported layer type {type(base_layer)}") + + 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 BOFT 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.boft_R.keys(): + continue + + warnings.warn("Scaling operation for BOFT 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.boft_R.keys(): + continue + + warnings.warn("Unscaling operation for BOFT not supported! Keeping scale to 1.") + + def update_layer( + self, + adapter_name: str, + config: BOFTConfig, + **kwargs, + ): + """ + Update the linear layer with trainable BOFT weights. Override for other layer types. + """ + boft_block_size = config.boft_block_size + boft_block_num = config.boft_block_num + boft_n_butterfly_factor = config.boft_n_butterfly_factor + boft_dropout = config.boft_dropout + init_weights = config.init_weights + inference_mode = config.inference_mode + + # Attempt to load the CUDA extension during model initialization + if not get_fbd_cuda(): + self.fbd_cuda_available = False + # If the CUDA extension is not available, set the butterfly factor to 1 to speed up the finetuning process + boft_n_butterfly_factor = 1 + else: + self.fbd_cuda_available = True + + # to be consistent with the paper notation + boft_n_butterfly_factor = boft_n_butterfly_factor - 1 + if boft_n_butterfly_factor < 0: + raise ValueError( + f"You can only specify boft_n_butterfly_factor {boft_n_butterfly_factor + 1} to be a positive integer number." + ) + + # Initialize the MultiplicativeDropoutLayer for boft_dropout > 0.0. + if boft_dropout > 0.0: + boft_dropout_layer = MultiplicativeDropoutLayer(p=boft_dropout) + else: + boft_dropout_layer = nn.Identity() + self.boft_dropout.update(nn.ModuleDict({adapter_name: boft_dropout_layer})) + + if boft_block_size == 0 and boft_block_num != 0: + if self.in_features % boft_block_num != 0: + raise ValueError( + f"in_features ({self.in_features}) must be divisible by boft_block_num ({boft_block_num})!" + ) + + if boft_n_butterfly_factor != 0: + if boft_n_butterfly_factor > int(math.log2(boft_block_num)): + raise ValueError( + f"Invalid combination of boft_n_butterfly_factor ({boft_n_butterfly_factor + 1}) and boft_block_num ({boft_block_num})!" + ) + if boft_block_num % (2**boft_n_butterfly_factor) != 0: + raise ValueError( + f"boft_block_num ({boft_block_num}) must be a multiple of 2 raised to the power of boft_n_butterfly_factor ({boft_n_butterfly_factor + 1})!" + ) + + boft_block_size = int(self.in_features // boft_block_num) + + elif boft_block_size != 0 and boft_block_num == 0: + if self.in_features % boft_block_size != 0: + raise ValueError( + f"in_features ({self.in_features}) must be divisible by boft_block_size ({boft_block_size})!" + ) + + if boft_n_butterfly_factor != 0: + if self.in_features < (boft_block_size * (2**boft_n_butterfly_factor)): + raise ValueError( + f"Invalid combination of in_features ({self.in_features}), boft_n_butterfly_factor ({boft_n_butterfly_factor + 1}) and boft_block_size ({boft_block_size})!" + ) + if self.in_features % (boft_block_size * (2**boft_n_butterfly_factor)) != 0: + raise ValueError( + f"Invalid combination of in_features ({self.in_features}), boft_n_butterfly_factor ({boft_n_butterfly_factor + 1}) and boft_block_size ({boft_block_size})!" + ) + + boft_block_num = int(self.in_features // boft_block_size) + + else: + raise ValueError( + "Something went wrong, please report this error: https://github.com/huggingface/peft/issues" + ) + + # In OFT you can specify the number of blocks to be 1 + if boft_n_butterfly_factor != 0: + if boft_block_num % 2 != 0: + raise ValueError(f"boft_block_num ({boft_block_num}) must be an even number!") + + if boft_block_size % 2 != 0: + raise ValueError(f"boft_block_size ({boft_block_size}) must be an even number!") + + # If there is no butterfly factor, then permutation matrix P will be an identity matrix. + P = torch.empty((boft_n_butterfly_factor + 1, self.in_features, self.in_features)) + for i in range(boft_n_butterfly_factor + 1): + perm = self.block_butterfly_perm( + self.in_features, int(boft_block_num / (2 ** (i))), int(boft_block_size / 2), boft_n_butterfly_factor + ) + perm_mat = self.perm2mat(perm) + P[i] = perm_mat + + self.register_buffer("boft_P", P, persistent=False) + + self.boft_R[adapter_name] = nn.Parameter( + torch.zeros(boft_n_butterfly_factor + 1, boft_block_num, boft_block_size, boft_block_size) + ) + self.boft_s[adapter_name] = nn.Parameter(torch.ones(int(self.out_features), 1)) + + self.reset_boft_parameters(adapter_name, init_weights) + + # set the boft block size and number + self.boft_block_size[adapter_name] = boft_block_size + self.boft_block_num[adapter_name] = boft_block_num + + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def reset_boft_parameters(self, adapter_name, init_weights): + """ + Reset the BOFT parameters. + """ + if init_weights is False: + nn.init.normal_(self.boft_R[adapter_name], mean=0.0, std=0.1) + nn.init.normal_(self.boft_s[adapter_name], mean=1.0, std=0.1) + return + + if adapter_name in self.boft_R.keys(): + if init_weights is True: + # initialize R to zero + nn.init.zeros_(self.boft_R[adapter_name]) + nn.init.ones_(self.boft_s[adapter_name]) + else: + raise ValueError(f"Unknown initialization {init_weights=}") + + def perm2mat(self, indices): + """ + Convert permutation indices to permutation matrix. + + Args: + indices: A list of indices representing the permutation. + """ + # Number of indices determines the size of the square matrix + n = len(indices) + + # Initialize a matrix of zeros + perm_mat = torch.zeros((n, n)) + + # Set the 1s according to the indices + for i, idx in enumerate(indices): + perm_mat[i, idx] = 1 + + return perm_mat + + def block_butterfly_perm(self, n, b, r=3, n_butterfly_factor=1): + """ + Define the permutation matrix for the block butterfly permutation. + + Args: + n: size of the permutation matrix + b: desired number of blocks after multiplying with the permutation matrix + r: base block size of the block diagonal matrix, e.g. 2x2, 3x3, 5x5 etc. + """ + + if n_butterfly_factor == 0: + return torch.arange(n) + + if b * r * 2 > n: + raise ValueError("Invalid number of blocks!") + + block_size = int(n // b) + indices = torch.arange(n) + + def sort_block(b, r): + step = b / r + initial_order = torch.arange(b) + sorted_order = torch.empty(b, dtype=torch.long) + + evens = torch.arange(0, step, 2) + odds = torch.arange(1, step, 2) + sorted_seq = torch.cat((evens, odds), dim=0) + for i, pos in enumerate(sorted_seq): + sorted_order[int(i * r) : int(i * r + r)] = initial_order[int(pos * r) : int(pos * r + r)] + return sorted_order + + sorted_order = sort_block(block_size, r) + + for i in range(0, n, block_size): + block_end = i + block_size + tmp_indices = indices[i:block_end] + indices[i:block_end] = tmp_indices[sorted_order] + return indices + + def cayley_batch(self, data): + """ + 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, r, c = data.shape + # Ensure the input matrix is skew-symmetric + skew_mat = 0.5 * (data - data.transpose(1, 2)) + id_mat = torch.eye(r, device=data.device).unsqueeze(0).expand(b, r, c) + + # Perform the Cayley parametrization, must be in float32 + Q = torch.linalg.solve(id_mat + skew_mat, id_mat - skew_mat, left=False) + + return Q.to(data.dtype) + + +class Linear(nn.Module, BOFTLayer): + """ + BOFT implemented in a dense layer. + """ + + def __init__( + self, + base_layer, + adapter_name: str, + config: BOFTConfig, + is_target_conv_1d_layer: bool = False, + **kwargs, + ) -> None: + super().__init__() + BOFTLayer.__init__(self, base_layer, **kwargs) + self.fan_in_fan_out = config.fan_in_fan_out + + self._active_adapter = adapter_name + + self.update_layer(adapter_name, config=config) + 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.boft_R.keys(): + orig_weight = self.get_base_weight().clone() + orig_dtype = orig_weight.dtype + if safe_merge: + # Note that safe_merge will be slower than the normal merge + # because of the copy operation. + butterfly_oft_mat, boft_s = self.get_delta_weight(active_adapter) + orig_weight = torch.transpose(orig_weight, 0, 1) + orig_weight = torch.mm(butterfly_oft_mat, orig_weight.to(butterfly_oft_mat.dtype)) + orig_weight = torch.transpose(orig_weight, 0, 1) + orig_weight = orig_weight * boft_s + + if not torch.isfinite(orig_weight).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + self.set_base_weight(orig_weight.contiguous().to(orig_dtype)) + else: + butterfly_oft_mat, boft_s = self.get_delta_weight(active_adapter) + orig_weight = torch.transpose(orig_weight, 0, 1) + orig_weight = torch.mm(butterfly_oft_mat, orig_weight.to(butterfly_oft_mat.dtype)) + orig_weight = torch.transpose(orig_weight, 0, 1) + orig_weight = orig_weight * boft_s + + self.set_base_weight(orig_weight.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 + + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter in self.boft_R.keys(): + butterfly_oft_mat, boft_s = self.get_delta_weight(active_adapter) + + orig_weight = self.get_base_weight().clone() + orig_dtype = orig_weight.dtype + orig_weight = torch.transpose(orig_weight, 0, 1) + orig_weight = torch.mm(butterfly_oft_mat.t(), orig_weight.to(butterfly_oft_mat.dtype)) + orig_weight = torch.transpose(orig_weight, 0, 1) + + self.set_base_weight((orig_weight * (1 / boft_s)).to(orig_dtype)) + + def get_delta_weight(self, adapter) -> tuple[torch.Tensor, 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. + """ + boft_R = self.boft_R[adapter] + boft_s = self.boft_s[adapter] + + N, D, H, _ = boft_R.shape + boft_R = boft_R.view(N * D, H, H) + orth_rotate_butterfly = self.cayley_batch(boft_R) + orth_rotate_butterfly = orth_rotate_butterfly.view(N, D, H, H) + if self.fbd_cuda_available: + block_diagonal_butterfly = FastBlockDiag.apply(orth_rotate_butterfly) + else: + orth_rotate_butterfly = orth_rotate_butterfly.squeeze(0) + block_diagonal_butterfly = torch.block_diag(*torch.unbind(orth_rotate_butterfly)) + block_diagonal_butterfly = block_diagonal_butterfly.unsqueeze(0) + + boft_P = self.boft_P.to(block_diagonal_butterfly.device, block_diagonal_butterfly.dtype) + butterfly_oft_mat_batch = torch.bmm(block_diagonal_butterfly, boft_P.permute(0, 2, 1)) + butterfly_oft_mat_batch = torch.bmm(boft_P, butterfly_oft_mat_batch) + butterfly_oft_mat = butterfly_oft_mat_batch[0] + + for i in range(1, butterfly_oft_mat_batch.shape[0]): + butterfly_oft_mat = butterfly_oft_mat_batch[i] @ butterfly_oft_mat + + return butterfly_oft_mat, boft_s + + 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: + boft_rotation = torch.eye(self.in_features, device=x.device, dtype=previous_dtype) + boft_scale = torch.ones((int(self.out_features), 1), device=x.device, dtype=previous_dtype) + + for active_adapter in self.active_adapters: + if active_adapter not in self.boft_R.keys(): + continue + boft_R = self.boft_R[active_adapter] + boft_s = self.boft_s[active_adapter] + dropout = self.boft_dropout[active_adapter] + + N, D, H, _ = boft_R.shape + boft_R = boft_R.view(N * D, H, H) + orth_rotate_butterfly = self.cayley_batch(boft_R) + orth_rotate_butterfly = orth_rotate_butterfly.view(N, D, H, H) + orth_rotate_butterfly = dropout(orth_rotate_butterfly) + if self.fbd_cuda_available: + block_diagonal_butterfly = FastBlockDiag.apply(orth_rotate_butterfly) + else: + orth_rotate_butterfly = orth_rotate_butterfly.squeeze(0) + block_diagonal_butterfly = torch.block_diag(*torch.unbind(orth_rotate_butterfly)) + block_diagonal_butterfly = block_diagonal_butterfly.unsqueeze(0) + + # The BOFT author's cayley_batch, dropout and FastBlockDiag ONLY return fp32 outputs. + boft_P = self.boft_P.to(x) + block_diagonal_butterfly = block_diagonal_butterfly.to(x) + butterfly_oft_mat_batch = torch.bmm(block_diagonal_butterfly, boft_P.permute(0, 2, 1)) + butterfly_oft_mat_batch = torch.bmm(boft_P, butterfly_oft_mat_batch) + butterfly_oft_mat = butterfly_oft_mat_batch[0] + + for i in range(1, butterfly_oft_mat_batch.shape[0]): + butterfly_oft_mat = butterfly_oft_mat_batch[i] @ butterfly_oft_mat + + boft_rotation = butterfly_oft_mat @ boft_rotation + boft_scale = boft_s * boft_scale + + boft_rotation = boft_rotation.to(previous_dtype) + x_rotated = x @ boft_rotation + + result = self.base_layer(x_rotated, *args, **kwargs) + bias = self.base_layer.bias + if bias is not None: + result = result - bias + result = result * boft_scale.squeeze(-1) + if bias is not None: + result = result + bias + + result = result.to(previous_dtype) + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "boft." + rep + + def extra_repr(self) -> str: + return quantization_extra_repr(self) + + +class Conv2d(nn.Module, BOFTLayer): + """ + BOFT implemented in a Conv2d layer. + """ + + def __init__( + self, + base_layer: nn.Module, + adapter_name: str, + config: BOFTConfig, + **kwargs, + ) -> None: + super().__init__() + BOFTLayer.__init__(self, base_layer) + + self._active_adapter = adapter_name + self.update_layer(adapter_name, config=config) + + def update_layer( + self, + adapter_name: str, + config: BOFTConfig, + **kwargs, + ): + """ + Update the conv2d layer with trainable BOFT weights. + """ + boft_block_size = config.boft_block_size + boft_block_num = config.boft_block_num + boft_n_butterfly_factor = config.boft_n_butterfly_factor + boft_dropout = config.boft_dropout + init_weights = config.init_weights + inference_mode = config.inference_mode + + # Attempt to load the CUDA extension during model initialization + if not get_fbd_cuda(): + self.fbd_cuda_available = False + # If the CUDA extension is not available, set the butterfly factor to 1 to speed up the finetuning process + boft_n_butterfly_factor = 1 + else: + self.fbd_cuda_available = True + + # to be consistent with the paper notation + boft_n_butterfly_factor = boft_n_butterfly_factor - 1 + if boft_n_butterfly_factor < 0: + raise ValueError( + f"You can only specify boft_n_butterfly_factor {boft_n_butterfly_factor + 1} to be a positive integer number." + ) + + # Initialize the MultiplicativeDropoutLayer for boft_dropout > 0.0. + if boft_dropout > 0.0: + boft_dropout_layer = MultiplicativeDropoutLayer(p=boft_dropout) + else: + boft_dropout_layer = nn.Identity() + self.boft_dropout.update(nn.ModuleDict({adapter_name: boft_dropout_layer})) + + # layer information from the base layer + base_layer = self.get_base_layer() + conv_filter_dim = self.in_features * base_layer.kernel_size[0] * base_layer.kernel_size[0] + + # Initialize the BOFT parameters. + if boft_block_size == 0 and boft_block_num != 0: + if conv_filter_dim % boft_block_num != 0: + raise ValueError( + f"Convolutional kernel dimension ({conv_filter_dim}) must be divisible by boft_block_num ({boft_block_num})!" + ) + + if boft_n_butterfly_factor != 0: + if boft_n_butterfly_factor > int(math.log2(boft_block_num)): + raise ValueError( + f"Invalid combination of boft_n_butterfly_factor ({boft_n_butterfly_factor + 1}) and boft_block_num ({boft_block_num})!" + ) + if boft_block_num % (2**boft_n_butterfly_factor) != 0: + raise ValueError( + f"boft_block_num ({boft_block_num}) must be a multiple of 2 raised to the power of boft_n_butterfly_factor ({boft_n_butterfly_factor + 1})!" + ) + + boft_block_size = int(conv_filter_dim // boft_block_num) + + elif boft_block_size != 0 and boft_block_num == 0: + if conv_filter_dim % boft_block_size != 0: + raise ValueError( + f"Convolutional kernel dimension ({conv_filter_dim}) must be divisible by boft_block_size ({boft_block_size})!" + ) + + if boft_n_butterfly_factor != 0: + if conv_filter_dim < (boft_block_size * (2**boft_n_butterfly_factor)): + raise ValueError( + f"Invalid combination of convolutional kernel dimension ({conv_filter_dim}), boft_n_butterfly_factor ({boft_n_butterfly_factor + 1}) and boft_block_size ({boft_block_size})!" + ) + if conv_filter_dim % (boft_block_size * (2**boft_n_butterfly_factor)) != 0: + raise ValueError( + f"Invalid combination of convolutional kernel dimension ({conv_filter_dim}), boft_n_butterfly_factor ({boft_n_butterfly_factor + 1}) and boft_block_size ({boft_block_size})!" + ) + + boft_block_num = int(conv_filter_dim // boft_block_size) + + else: + raise ValueError( + "Something went wrong, please report this error: https://github.com/huggingface/peft/issues" + ) + + # In OFT you can specify the number of blocks to be 1 + if boft_n_butterfly_factor != 0: + if boft_block_num % 2 != 0: + raise ValueError(f"boft_block_num ({boft_block_num}) must be an even number!") + + if boft_block_size % 2 != 0: + raise ValueError(f"boft_block_size ({boft_block_size}) must be an even number!") + + # If there is no butterfly factor, then permutation matrix P will be an identity matrix. + P = torch.empty((boft_n_butterfly_factor + 1, conv_filter_dim, conv_filter_dim)) + for i in range(boft_n_butterfly_factor + 1): + perm = self.block_butterfly_perm( + conv_filter_dim, int(boft_block_num / (2 ** (i))), int(boft_block_size / 2), boft_n_butterfly_factor + ) + perm_mat = self.perm2mat(perm) + P[i] = perm_mat + + self.register_buffer("boft_P", P, persistent=False) + + self.boft_R[adapter_name] = nn.Parameter( + torch.zeros(boft_n_butterfly_factor + 1, boft_block_num, boft_block_size, boft_block_size) + ) + self.boft_s[adapter_name] = nn.Parameter(torch.ones(1, int(self.out_features))) + + self.reset_boft_parameters(adapter_name, init_weights) + + # set the boft block size and number + self.boft_block_size[adapter_name] = boft_block_size + self.boft_block_num[adapter_name] = boft_block_num + + 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.boft_R.keys(): + base_layer = self.get_base_layer() + orig_weight = self.get_base_weight().clone() + orig_dtype = orig_weight.dtype + if safe_merge: + # Note that safe_merge will be slower than the normal merge + # because of the copy operation. + butterfly_oft_mat, boft_s = self.get_delta_weight(active_adapter) + + orig_weight = orig_weight.view( + self.out_features, self.in_features * base_layer.kernel_size[0] * base_layer.kernel_size[0] + ) + orig_weight = torch.transpose(orig_weight, 0, 1) + orig_weight = torch.mm(butterfly_oft_mat, orig_weight.to(butterfly_oft_mat.dtype)) + orig_weight = torch.transpose(orig_weight, 0, 1) + orig_weight = orig_weight * boft_s + orig_weight = orig_weight.view( + self.out_features, self.in_features, base_layer.kernel_size[0], base_layer.kernel_size[0] + ) + + self.set_base_weight(orig_weight.contiguous().to(orig_dtype)) + else: + butterfly_oft_mat, boft_s = self.get_delta_weight(active_adapter) + + orig_weight = orig_weight.view( + self.out_features, self.in_features * base_layer.kernel_size[0] * base_layer.kernel_size[0] + ) + orig_weight = torch.transpose(orig_weight, 0, 1) + orig_weight = torch.mm(butterfly_oft_mat, orig_weight.to(butterfly_oft_mat.dtype)) + orig_weight = torch.transpose(orig_weight, 0, 1) + orig_weight = orig_weight * boft_s + orig_weight = orig_weight.view( + self.out_features, self.in_features, base_layer.kernel_size[0], base_layer.kernel_size[0] + ) + + self.set_base_weight(orig_weight.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 + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + base_layer = self.get_base_layer() + if active_adapter in self.boft_R.keys(): + butterfly_oft_mat, boft_s = self.get_delta_weight(active_adapter) + + orig_weight = self.get_base_weight().clone() + orig_dtype = orig_weight.dtype + orig_weight = orig_weight.view( + self.out_features, + self.in_features * base_layer.kernel_size[0] * base_layer.kernel_size[0], + ) + orig_weight = torch.transpose(orig_weight, 0, 1) + orig_weight = torch.mm(butterfly_oft_mat.t(), orig_weight.to(butterfly_oft_mat.dtype)) + orig_weight = torch.transpose(orig_weight, 0, 1) + orig_weight = orig_weight * (1 / boft_s) + orig_weight = orig_weight.view( + self.out_features, + self.in_features, + base_layer.kernel_size[0], + base_layer.kernel_size[0], + ) + + self.set_base_weight(orig_weight.to(orig_dtype)) + + def get_delta_weight(self, adapter) -> tuple[torch.Tensor, 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. + """ + + boft_R = self.boft_R[adapter] + boft_s = self.boft_s[adapter].transpose(0, 1) + + N, D, H, _ = boft_R.shape + boft_R = boft_R.view(N * D, H, H) + orth_rotate_butterfly = self.cayley_batch(boft_R) + orth_rotate_butterfly = orth_rotate_butterfly.view(N, D, H, H) + if self.fbd_cuda_available: + block_diagonal_butterfly = FastBlockDiag.apply(orth_rotate_butterfly) + else: + orth_rotate_butterfly = orth_rotate_butterfly.squeeze(0) + block_diagonal_butterfly = torch.block_diag(*torch.unbind(orth_rotate_butterfly)) + block_diagonal_butterfly = block_diagonal_butterfly.unsqueeze(0) + + boft_P = self.boft_P.to(block_diagonal_butterfly.device, block_diagonal_butterfly.dtype) + butterfly_oft_mat_batch = torch.bmm(block_diagonal_butterfly, boft_P.permute(0, 2, 1)) + butterfly_oft_mat_batch = torch.bmm(boft_P, butterfly_oft_mat_batch) + butterfly_oft_mat = butterfly_oft_mat_batch[0] + + for i in range(1, butterfly_oft_mat_batch.shape[0]): + butterfly_oft_mat = butterfly_oft_mat_batch[i] @ butterfly_oft_mat + + return butterfly_oft_mat, boft_s + + 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: + boft_rotation = torch.eye( + self.in_features * self.base_layer.kernel_size[0] * self.base_layer.kernel_size[0], + device=x.device, + dtype=x.dtype, + ) + boft_scale = torch.ones((int(self.out_features), 1), device=x.device, dtype=x.dtype) + + for active_adapter in self.active_adapters: + if active_adapter not in self.boft_R.keys(): + continue + boft_R = self.boft_R[active_adapter] + boft_s = self.boft_s[active_adapter].transpose(0, 1) + dropout = self.boft_dropout[active_adapter] + + N, D, H, _ = boft_R.shape + boft_R = boft_R.view(N * D, H, H) + orth_rotate_butterfly = self.cayley_batch(boft_R) + orth_rotate_butterfly = orth_rotate_butterfly.view(N, D, H, H) + orth_rotate_butterfly = dropout(orth_rotate_butterfly) + if self.fbd_cuda_available: + block_diagonal_butterfly = FastBlockDiag.apply(orth_rotate_butterfly) + else: + orth_rotate_butterfly = orth_rotate_butterfly.squeeze(0) + block_diagonal_butterfly = torch.block_diag(*torch.unbind(orth_rotate_butterfly)) + block_diagonal_butterfly = block_diagonal_butterfly.unsqueeze(0) + + boft_P = self.boft_P.to(x) + block_diagonal_butterfly = block_diagonal_butterfly.to(x) + butterfly_oft_mat_batch = torch.bmm(block_diagonal_butterfly, boft_P.permute(0, 2, 1)) + butterfly_oft_mat_batch = torch.bmm(boft_P, butterfly_oft_mat_batch) + butterfly_oft_mat = butterfly_oft_mat_batch[0] + + for i in range(1, butterfly_oft_mat_batch.shape[0]): + butterfly_oft_mat = butterfly_oft_mat_batch[i] @ butterfly_oft_mat + + boft_rotation = butterfly_oft_mat @ boft_rotation + boft_scale = boft_s * boft_scale + + orig_weight = self.get_base_weight() + x = x.to(orig_weight.dtype) + + orig_weight = orig_weight.view( + self.out_features, + self.in_features * self.base_layer.kernel_size[0] * self.base_layer.kernel_size[0], + ) + orig_weight = torch.transpose(orig_weight, 0, 1) + rotated_weight = torch.mm(boft_rotation, orig_weight) + rotated_weight = torch.transpose(rotated_weight, 0, 1) + + scaled_rotated_weight = rotated_weight * boft_scale + + scaled_rotated_weight = scaled_rotated_weight.view( + self.out_features, self.in_features, self.base_layer.kernel_size[0], self.base_layer.kernel_size[0] + ) + x = self._cast_input_dtype(x, scaled_rotated_weight.dtype) + bias = self._cast_input_dtype(self.base_layer.bias, scaled_rotated_weight.dtype) + result = F.conv2d( + input=x, + weight=scaled_rotated_weight, + bias=bias, + padding=self.base_layer.padding[0], + stride=self.base_layer.stride[0], + ) + + result = result.to(previous_dtype) + return result + + def extra_repr(self) -> str: + return quantization_extra_repr(self) + + def __repr__(self) -> str: + rep = super().__repr__() + return "boft." + rep diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/boft/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/boft/model.py new file mode 100644 index 0000000000000000000000000000000000000000..80f546adf0336ef4a176ce4e29adec7351357b61 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/boft/model.py @@ -0,0 +1,141 @@ +# 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. + +# The implementation is based on "Parameter-Efficient Orthogonal Finetuning +# via Butterfly Factorization" (https://huggingface.co/papers/2311.06243) in ICLR 2024. + +import warnings + +import torch + +from peft.tuners.tuners_utils import ( + BaseTuner, + BaseTunerLayer, +) +from peft.utils import ( + TRANSFORMERS_MODELS_TO_BOFT_TARGET_MODULES_MAPPING, + get_quantization_kwargs, + resolve_quantization_backend, +) + +from .layer import BOFTLayer, Conv2d, Linear + + +def _get_tuner_layer_class(target_base_layer: torch.nn.Module) -> type[BOFTLayer] | None: + layer_cls: type[BOFTLayer] | None = None + if isinstance(target_base_layer, torch.nn.Linear): + layer_cls = Linear + elif isinstance(target_base_layer, torch.nn.Conv2d): + layer_cls = Conv2d + elif (quant_backend := resolve_quantization_backend(target_base_layer)) is not None: + layer_cls = {"linear": Linear, "conv2d": Conv2d}.get(quant_backend.layer_type) + + return layer_cls + + +class BOFTModel(BaseTuner): + """ + Creates BOFT and OFT model from a pretrained transformers model. Paper: https://huggingface.co/papers/2311.06243 + https://huggingface.co/papers/2306.07280 + + Args: + model ([`transformers.PreTrainedModel`]): The model to be adapted. + config ([`BOFTConfig`]): The configuration of the BOFT 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 BOFT model. + + Example: + ```py + >>> import transformers + >>> from peft import BOFTConfig, get_peft_model + + >>> config = BOFTConfig( + ... boft_block_size=8, + ... boft_n_butterfly_factor=1, + ... target_modules=["query", "value", "key", "output.dense", "mlp.fc1", "mlp.fc2"], + ... boft_dropout=0.1, + ... bias="boft_only", + ... modules_to_save=["classifier"], + ... ) + + >>> model = transformers.Dinov2ForImageClassification.from_pretrained( + ... "facebook/dinov2-large", + ... num_labels=100, + ... ) + >>> boft_model = get_peft_model(model, config) + ``` + + **Attributes**: + - **model** ([`transformers.PreTrainedModel`]) -- The model to be adapted. + - **peft_config** ([`BOFTConfig`]): The configuration of the BOFT model. + """ + + prefix: str = "boft_" + tuner_layer_cls = BOFTLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_BOFT_TARGET_MODULES_MAPPING + + def _create_and_replace( + self, + boft_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 = get_quantization_kwargs(self) + + # If it is not a BOFTLayer, create a new module, else update it with new adapters + if not isinstance(target, BOFTLayer): + new_module = self._create_new_module(boft_config, adapter_name, target, **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, + config=boft_config, + ) + + @staticmethod + def _create_new_module(boft_config, adapter_name, target, **kwargs): + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + layer_cls = _get_tuner_layer_class(target_base_layer) + if layer_cls is None: + raise TypeError( + f"Target module {target} is not supported. Currently, only `torch.nn.Linear` and `torch.nn.Conv2d` (optionally quantized) " + "are supported." + ) + + if (layer_cls == Linear) and boft_config.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." + ) + boft_config.fan_in_fan_out = False + new_module = layer_cls(target, adapter_name, config=boft_config, **kwargs) + return new_module diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/c3a/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/c3a/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ba8a7cbf61845f934737e11be277a7e2f48e7b34 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/c3a/__init__.py @@ -0,0 +1,23 @@ +# 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 C3AConfig +from .layer import C3ALayer, C3ALinear +from .model import C3AModel + + +__all__ = ["C3AConfig", "C3ALayer", "C3ALinear", "C3AModel"] + +register_peft_method(name="c3a", model_cls=C3AModel, config_cls=C3AConfig) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/c3a/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/c3a/config.py new file mode 100644 index 0000000000000000000000000000000000000000..2059c77a417f9f4eaa54f9d1f73943836646d328 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/c3a/config.py @@ -0,0 +1,137 @@ +# 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 Literal, Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class C3AConfig(PeftConfig): + """This is the configuration class to store the configuration of a [`C3AModel`]. + + Args: + block_size (`int`): + block size for C3A, must be divisible by both the input size and the output size of the target layer. If + you have no idea what block_size you should use, set it to the greatest common divisor of all input & + output sizes of your target layers. Increasing this would result in less parameters. + target_modules (`Union[list[str],str]`): The names of the modules to apply C3A to. + bias (`str`): Bias type for C3A. Can be 'none', 'all' or 'c3a_only'. If 'all' or 'c3a_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 C3A layers to be set as trainable + and saved in the final checkpoint. + layers_to_transform (`Union[list[int],int]`): + The layer indexes to transform, if this argument is specified, it will apply C3A on the layer indexes that + are specified in this list. If a single integer is passed, it will apply C3A 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. + block_size_pattern (`dict`): + The mapping from layer names or regexp expression to block_size which are different from the default + specified. For example, `{"model.decoder.layers.0.encoder_attn.k_proj": 1280`} + init_weights (`Union[bool, Literal["gaussian", "kaiming_uniform", "xavier_uniform"]]`): + Defaults to 'xavier_uniform'. Setting this to `False` also uses 'xavier_uniform'. To set the weights to + zeros (thus making C3A a no-op), set the value to `True`. + """ + + block_size: int = field( + default=256, + metadata={ + "help": ( + "block size for C3A, must be divisible by both the input size and the output size of the target layer." + " If you have no idea what block_size you should use, set it to the greatest common divisor of all" + " input & output sizes of your target layers. Increasing this would result in less parameters." + ) + }, + ) + 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 C3A." + " For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$' " + ) + }, + ) + bias: str = field(default="none", metadata={"help": "Bias type for C3A. Can be 'none', 'all' or 'c3a_only'"}) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": ( + "list of modules apart from C3A 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." + ) + }, + ) + 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." + " This only works when target_modules is a list of str." + ) + }, + ) + 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 only works when target_modules is a list of str." + ) + }, + ) + block_size_pattern: Optional[dict] = field( + default_factory=dict, + metadata={ + "help": ( + "The mapping from layer names or regexp expression to block_size" + " which are different from the default specified." + " For example, `{model.decoder.layers.0.encoder_attn.k_proj: 1280`}" + ) + }, + ) + init_weights: Optional[Union[bool, Literal["gaussian", "kaiming_uniform", "xavier_uniform"]]] = field( + default="xavier_uniform", + metadata={ + "help": ( + "Defaults to 'xavier_uniform'. Setting this to `False` also uses 'xavier_uniform'. To set the weights " + "to zeros (thus making C3A a no-op), set the value to `True`." + ) + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.C3A + self.target_modules = ( + set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules + ) + # if target_modules is a regex expression, then layers_to_transform should be None + if isinstance(self.target_modules, str) and self.layers_to_transform is not None: + raise ValueError("`layers_to_transform` cannot be used when `target_modules` is a str.") + + # if target_modules is a regex expression, then layers_pattern should be None + if isinstance(self.target_modules, str) and self.layers_pattern is not None: + raise ValueError("`layers_pattern` cannot be used when `target_modules` is a str.") diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/c3a/layer.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/c3a/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..ee124893eb92191eb7bf359a55550bc3f10bbcb5 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/c3a/layer.py @@ -0,0 +1,209 @@ +# 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 Any, Optional + +import torch +from torch import nn + +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge + +from .config import C3AConfig +from .utils import BlockCircularConvolution, get_circulant_fast + + +class C3ALayer(BaseTunerLayer): + # All names of layers that may contain (trainable) adapter weights + adapter_layer_names = ("c3a_kernel",) + # All names of other parameters that may contain adapter-related parameters + other_param_names = ("block_size",) + + def __init__(self, base_layer: nn.Module, **kwargs) -> None: + self.base_layer = base_layer + self.block_size = {} + self.c3a_kernel = nn.ParameterDict({}) + # Mark the weight as unmerged + self._disable_adapters = False + self.merged_adapters = [] + self.kwargs = kwargs + + base_layer = self.get_base_layer() + if isinstance(base_layer, nn.Linear): + self.in_features, self.out_features = base_layer.in_features, base_layer.out_features + else: + raise TypeError(f"Unsupported layer type {type(base_layer)}") + + def get_delta_weight(self, adapter) -> torch.Tensor: + if adapter not in self.c3a_kernel.keys(): + raise ValueError(f"Adapter {adapter} not found.") + base_layer_weight = self.get_base_layer().weight + base_layer_weight_dtype = base_layer_weight.dtype + c3a_kernel = self.c3a_kernel[adapter] + + delta_weight = get_circulant_fast(c3a_kernel.to(torch.float32)).to(base_layer_weight_dtype) + return delta_weight / base_layer_weight.size(-1) + + def update_layer(self, adapter_name: str, block_size: int, config: C3AConfig, **kwargs): + init_weights = config.init_weights + inference_mode = config.inference_mode + + if block_size <= 0: + raise ValueError(f"`block_size` should be a positive integer value but the value passed is {block_size}") + if self.in_features % block_size != 0: + raise ValueError( + f"The block size should be a factor of the input size. However, the input size is {self.in_features} and the block size is {block_size}" + ) + if self.out_features % block_size != 0: + raise ValueError( + f"The block size should be a factor of the output size. However, the output size is {self.out_features} and the block size is {block_size}" + ) + + self.block_size[adapter_name] = block_size + + weight = self.get_base_layer().weight + self.c3a_kernel[adapter_name] = nn.Parameter( + torch.zeros( + self.out_features // block_size, + self.in_features // block_size, + block_size, + # Currently, only fp32 is widely supported for FFT (fp16 is only supported on GPU with shapes of powers + # of 2, bf16 lacks FFT support) + dtype=torch.float32, + device=weight.device, + ) + ) + + self.reset_c3a_parameters(adapter_name, init_weights) + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + @torch.no_grad() + def reset_c3a_parameters(self, adapter_name, init_weights): + if init_weights is True: + return + + if adapter_name in self.c3a_kernel.keys(): + if init_weights == "gaussian": + nn.init.normal_(self.c3a_kernel[adapter_name]) + elif init_weights in ["xavier_uniform", False]: + fan_in, fan_out = self.in_features, self.out_features + std = 1.0 * math.sqrt(2.0 / float(fan_in + fan_out)) + a = math.sqrt(3.0) * std + nn.init.uniform_(self.c3a_kernel[adapter_name], -a, a) + elif init_weights == "kaiming_uniform": + fan_in = self.in_features + a = 1.0 * math.sqrt(1.0 / float(fan_in)) + nn.init.uniform_(self.c3a_kernel[adapter_name], -a, a) + else: + raise ValueError(f"Unknown init_weights: {init_weights}") + + +class C3ALinear(nn.Module, C3ALayer): + # Lora implemented in a dense layer + def __init__( + self, + base_layer, + adapter_name: str, + config: C3AConfig, + block_size: int, + **kwargs, + ) -> None: + super().__init__() + C3ALayer.__init__(self, base_layer, **kwargs) + self._active_adapter = adapter_name + self.update_layer(adapter_name, block_size, config=config) + + 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.c3a_kernel.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() + delta_weight = self.get_delta_weight(active_adapter) + orig_weights = orig_weights + delta_weight + + 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: + delta_weight = self.get_delta_weight(active_adapter) + base_layer.weight.data = base_layer.weight.data + delta_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 + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter in self.c3a_kernel.keys(): + self.get_base_layer().weight.data -= self.get_delta_weight(active_adapter) + + 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: + result = self.base_layer(x, *args, **kwargs) + x = x.to(torch.float32) + for active_adapter in self.active_adapters: + if active_adapter not in self.c3a_kernel.keys(): + continue + c3a_kernel = self.c3a_kernel[active_adapter].to(torch.float32) + x = BlockCircularConvolution.apply(x, c3a_kernel) / x.size(-1) + result += x.to(result.dtype) + + 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 "c3a." + rep diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/c3a/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/c3a/model.py new file mode 100644 index 0000000000000000000000000000000000000000..cb946df1e126180862266fafc5bd5b802e8676a1 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/c3a/model.py @@ -0,0 +1,100 @@ +# 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 re +from itertools import chain + +import torch + +from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer +from peft.utils import ( + TRANSFORMERS_MODELS_TO_C3A_TARGET_MODULES_MAPPING, +) + +from .layer import C3ALayer, C3ALinear + + +class C3AModel(BaseTuner): + """ + Creates C3A model from a pretrained transformers model. + + The method is described in detail in https://huggingface.co/papers/2407.19342. + + Args: + model ([`torch.nn.Module`]): The model to be adapted. + config ([`C3AConfig`]): The configuration of the C3A model. + adapter_name (`str`): The name of the adapter, defaults to `"default"`. + + Returns: + `torch.nn.Module`: The C3A model. + + **Attributes**: + - **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted. + - **peft_config** ([`C3AConfig`]): The configuration of the C3A model. + """ + + prefix: str = "c3a_" + tuner_layer_cls = C3ALayer + target_module_mapping = TRANSFORMERS_MODELS_TO_C3A_TARGET_MODULES_MAPPING + + def _create_and_replace( + self, + c3a_config, + adapter_name, + target, + target_name, + parent, + current_key, + **optional_kwargs, + ): + if current_key is None: + raise ValueError("Current Key shouldn't be `None`") + # Regexp matching - Find key which matches current target_name in patterns provided + pattern_keys = list(chain(c3a_config.block_size_pattern.keys())) + target_name_key = next(filter(lambda key: re.match(rf".*\.{key}$", current_key), pattern_keys), current_key) + + block_size = c3a_config.block_size_pattern.get(target_name_key, c3a_config.block_size) + kwargs = { + "block_size": block_size, + } + + if isinstance(target, C3ALinear): + target.update_layer( + adapter_name, + block_size, + config=c3a_config, + ) + else: + new_module = self._create_new_module(c3a_config, adapter_name, target, **kwargs) + if adapter_name != 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(c3a_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): + new_module = C3ALinear(target, adapter_name, config=c3a_config, **kwargs) + else: + raise TypeError( + f"Target module {target} is not supported. Currently, only `torch.nn.Linear` is supported." + ) + + return new_module diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/c3a/utils.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/c3a/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7ad3bc5f6027bc1fe6df7e7073ffb0cbb0ce942d --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/c3a/utils.py @@ -0,0 +1,48 @@ +# 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 torch.autograd import Function +from torch.fft import fft, ifft + + +def get_circulant_fast(w): + _, n, b = w.shape + x = torch.eye(n * b, dtype=w.dtype, device=w.device) + x = x.reshape(*x.shape[:-1], n, b) + x = torch.einsum("...nb,mnb->...mb", ifft(x), fft(w)) + x = fft(x).real.flatten(start_dim=1).T + return x + + +class BlockCircularConvolution(Function): + @staticmethod + def forward(ctx, x, w): + _, n, b = w.shape + x = x.reshape(*x.shape[:-1], n, b) + ctx.save_for_backward(x, w) + x = torch.einsum("...nb,mnb->...mb", ifft(x), fft(w)) + x = fft(x).real + x = x.reshape(*x.shape[:-2], -1) + return x + + @staticmethod + def backward(ctx, grad_output): + x, w = ctx.saved_tensors + m, _, b = w.shape + grad_output = grad_output.reshape(*grad_output.shape[:-1], m, b) + grad_output_fft = fft(grad_output) + x_grad = fft(torch.einsum("...mb,mnb->...nb", grad_output_fft, ifft(w))).real + x_grad = x_grad.reshape(*x_grad.shape[:-2], -1) + w_grad = fft(torch.einsum("...mb,...nb->mnb", grad_output_fft, ifft(x))).real + return x_grad, w_grad diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/cartridge/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/cartridge/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..78ecfa0c3a14d56a936fc5db391ff3f9c8537b3a --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/cartridge/__init__.py @@ -0,0 +1,23 @@ +# 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 CartridgeConfig +from .model import CartridgeEncoder + + +__all__ = ["CartridgeConfig", "CartridgeEncoder"] + +register_peft_method(name="cartridge", config_cls=CartridgeConfig, model_cls=CartridgeEncoder) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/cartridge/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/cartridge/config.py new file mode 100644 index 0000000000000000000000000000000000000000..1eba07f0b8c0f53b78b0044eae076ff0dde0b99e --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/cartridge/config.py @@ -0,0 +1,74 @@ +# 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 dataclasses import dataclass, field + +from peft.config import PromptLearningConfig +from peft.utils import PeftType + + +@dataclass +class CartridgeConfig(PromptLearningConfig): + """ + Configuration for CARTRIDGE, a KV-cache-parameterized prefix adapter. + + This is similar to prefix-tuning in how it is served (as `past_key_values`), but it stores the KV cache directly as + trainable parameters instead of learning it via an MLP projection. + + Initialization: + The Cartridges paper discusses multiple initialization options. In PEFT, initialization is a *separate* step + from constructing the adapter config: + + - **Random KV initialization (paper option 2)**: Create the adapter via `get_peft_model(...)`. The CARTRIDGE + prompt encoder parameters are randomly initialized by PyTorch. + + - **KV derived from the first tokens of a prompt/corpus (paper option 3)**: Run a no-grad prefill on the *base + model* and copy the first `num_virtual_tokens` cached KV tokens into the adapter. PEFT provides utilities for + this (importable from `peft` or from `peft.tuners.cartridge.utils`): + + - `initialize_kv_prefix_from_text(model, tokenizer, text=...)` + - `initialize_kv_prefix_from_past_key_values(model, past_key_values=...)` + + If you already have a flattened KV-prefix tensor, you can load it directly via the prompt encoder’s + `load_prompt_embeddings(...)` method. + + Args: + num_frozen_tokens (`int`, defaults to 1): + Number of *prefix* tokens at the start of the cartridge to keep frozen (no gradients). The Cartridges paper + recommends freezing the first token as an attention sink for stability (set this to `1`), as many LLMs use + early tokens as attention sinks and changing them can harm training. + """ + + num_frozen_tokens: int = field( + default=1, + metadata={ + "help": ( + "Number of initial virtual tokens to freeze (no gradients). The paper recommends freezing the first " + "token as an attention sink for stability." + ) + }, + ) + + def __post_init__(self): + super().__post_init__() + if self.num_frozen_tokens < 0: + raise ValueError(f"`num_frozen_tokens` must be >= 0, got {self.num_frozen_tokens}.") + # `num_virtual_tokens` is required for prompt-learning configs. Validate the relationship early for a clearer + # error, even if the encoder also checks it. + if (self.num_virtual_tokens is not None) and (self.num_frozen_tokens > self.num_virtual_tokens): + raise ValueError( + f"`num_frozen_tokens` must be <= `num_virtual_tokens`, got num_frozen_tokens={self.num_frozen_tokens} " + f"and num_virtual_tokens={self.num_virtual_tokens}." + ) + self.peft_type = PeftType.CARTRIDGE diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/cartridge/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/cartridge/model.py new file mode 100644 index 0000000000000000000000000000000000000000..bd0ad07ffeb9980759c16240b7d8ed51ad826da8 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/cartridge/model.py @@ -0,0 +1,116 @@ +# 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 + + +class CartridgeEncoder(torch.nn.Module): + """ + A parameterized prefix KV cache. + + The parameters are stored in the same flattened layout as `PrefixEncoder` output: `[num_virtual_tokens, num_layers + * 2 * token_dim]`, where `token_dim` is per-head hidden size times number of heads (after any GQA adjustment + performed by `_prepare_prompt_learning_config`). + + If `num_frozen_tokens > 0`, the first `num_frozen_tokens` virtual tokens are stored as a non-trainable parameter, + and the remaining tokens are trainable. + """ + + def __init__(self, config): + super().__init__() + self.config = config + + num_virtual_tokens = config.num_virtual_tokens + hidden = config.num_layers * 2 * config.token_dim + num_frozen_tokens = int(config.num_frozen_tokens) + if num_frozen_tokens < 0 or num_frozen_tokens > num_virtual_tokens: + raise ValueError( + f"`num_frozen_tokens` must be in [0, num_virtual_tokens], got {num_frozen_tokens} for " + f"num_virtual_tokens={num_virtual_tokens}." + ) + + self.num_frozen_tokens = num_frozen_tokens + self.num_trainable_tokens = num_virtual_tokens - num_frozen_tokens + + if self.num_frozen_tokens: + frozen = torch.empty(self.num_frozen_tokens, hidden) + self.frozen_embedding = torch.nn.Parameter(frozen, requires_grad=False) + else: + self.frozen_embedding = None + + trainable = torch.empty(self.num_trainable_tokens, hidden) + self.trainable_embedding = torch.nn.Parameter(trainable, requires_grad=not config.inference_mode) + + self.reset_parameters() + + @property + def embedding(self): + """ + Expose a prefix-encoder compatible interface (`.embedding.weight`) for PEFT internals. + """ + + class _Proxy(torch.nn.Module): + def __init__(self, parent: CartridgeEncoder): + super().__init__() + self._parent = parent + + @property + def weight(self): + return self._parent.weight + + return _Proxy(self) + + @property + def weight(self) -> torch.Tensor: + if self.frozen_embedding is None: + return self.trainable_embedding + return torch.cat([self.frozen_embedding, self.trainable_embedding], dim=0) + + def reset_parameters(self): + # Match `torch.nn.Embedding` initialization (normal with std=1). + with torch.no_grad(): + if self.frozen_embedding is not None: + torch.nn.init.normal_(self.frozen_embedding) + torch.nn.init.normal_(self.trainable_embedding) + + def load_prompt_embeddings(self, prompt_embeddings: torch.Tensor) -> None: + """ + Load the flattened prompt embeddings saved by PEFT (`prompt_embeddings`). + + PEFT saves prompt-learning adapters as a single `prompt_embeddings` tensor. For CARTRIDGE, we split that tensor + into frozen and trainable segments according to `self.num_frozen_tokens`. + """ + if prompt_embeddings.ndim != 2 or prompt_embeddings.shape[0] != ( + self.num_frozen_tokens + self.num_trainable_tokens + ): + raise ValueError( + "Invalid `prompt_embeddings` shape. Expected " + f"({self.num_frozen_tokens + self.num_trainable_tokens}, hidden), got {tuple(prompt_embeddings.shape)}." + ) + with torch.no_grad(): + if self.frozen_embedding is not None: + self.frozen_embedding.copy_( + prompt_embeddings[: self.num_frozen_tokens].to(self.frozen_embedding.device) + ) + trainable_part = prompt_embeddings[self.num_frozen_tokens :] + else: + trainable_part = prompt_embeddings + self.trainable_embedding.copy_(trainable_part.to(self.trainable_embedding.device)) + + def forward(self, prefix_tokens: torch.Tensor) -> torch.Tensor: + batch_size = prefix_tokens.shape[0] + # Ignore token ids; they exist for prompt-learning uniformity. + return self.weight.unsqueeze(0).expand(batch_size, -1, -1) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/cartridge/utils.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/cartridge/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..57b22e28b88b90e4a9bac57e97a5e4982aae8138 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/cartridge/utils.py @@ -0,0 +1,237 @@ +# 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 collections.abc import Sequence +from dataclasses import replace +from pathlib import Path +from typing import Any, Optional + +import torch +from safetensors.torch import save_file + +from peft.config import PeftConfig +from peft.utils import PeftType +from peft.utils.constants import SAFETENSORS_WEIGHTS_NAME, WEIGHTS_NAME +from peft.utils.save_and_load import load_peft_weights + + +def _to_legacy_past_key_values(past_key_values: Any): + # Support both legacy tuples and transformers.Cache-like objects. + if isinstance(past_key_values, (tuple, list)): + return past_key_values + to_legacy = getattr(past_key_values, "to_legacy_cache", None) + if callable(to_legacy): + return to_legacy() + if hasattr(past_key_values, "__iter__"): + legacy = list(past_key_values) + if legacy and isinstance(legacy[0], (tuple, list)) and len(legacy[0]) >= 2: + return [(layer[0], layer[1]) for layer in legacy] + raise TypeError( + "Unsupported `past_key_values` type. Expected a legacy tuple/list, an object with `to_legacy_cache()`, or an " + "iterable of (key, value) tuples." + ) + + +def prompt_embeddings_from_past_key_values( + past_key_values: Any, + *, + num_virtual_tokens: int, +) -> torch.Tensor: + """ + Convert a (legacy) `past_key_values` cache into the flattened prompt embeddings tensor saved by PEFT. + + The output matches the layout expected by `PeftModel.get_prompt()` for prefix-style prompt learning: shape + `[num_virtual_tokens, num_layers * 2 * token_dim]`. + """ + legacy = _to_legacy_past_key_values(past_key_values) + if len(legacy) == 0: + raise ValueError("Empty `past_key_values`.") + + # Each layer: (key, value), where key/value are [batch, num_heads, seq_len, head_dim] + num_layers = len(legacy) + key0, _ = legacy[0] + if key0.ndim != 4: + raise ValueError(f"Expected key/value tensors with rank 4, got key.ndim={key0.ndim}.") + if key0.shape[0] != 1: + raise ValueError( + "This helper expects `past_key_values` from a single-sequence prefill (batch=1). " + f"Got batch={key0.shape[0]}." + ) + num_heads = key0.shape[1] + seq_len = key0.shape[2] + head_dim = key0.shape[3] + if seq_len < num_virtual_tokens: + raise ValueError(f"Need at least {num_virtual_tokens} cached tokens, got {seq_len}.") + + packed = torch.empty( + num_virtual_tokens, + num_layers * 2, + num_heads, + head_dim, + device=key0.device, + dtype=key0.dtype, + ) + for layer_idx, (k, v) in enumerate(legacy): + if k.shape[:2] != (1, num_heads) or v.shape[:2] != (1, num_heads): + raise ValueError("Inconsistent head shapes across layers in `past_key_values`.") + if k.shape[2] < num_virtual_tokens or v.shape[2] < num_virtual_tokens: + raise ValueError("Not enough cached tokens in `past_key_values` for the requested cartridge length.") + if k.shape[3] != head_dim or v.shape[3] != head_dim: + raise ValueError("Inconsistent head_dim across layers in `past_key_values`.") + packed[:, 2 * layer_idx] = k[0, :, :num_virtual_tokens, :].transpose(0, 1).contiguous() + packed[:, 2 * layer_idx + 1] = v[0, :, :num_virtual_tokens, :].transpose(0, 1).contiguous() + + return packed.reshape(num_virtual_tokens, -1) + + +@torch.no_grad() +def initialize_kv_prefix_from_past_key_values( + model, + *, + adapter_name: Optional[str] = None, + past_key_values: Any, + num_virtual_tokens: Optional[int] = None, +) -> torch.Tensor: + """ + Initialize a KV-prefix prompt-learning adapter from an existing cached prefix (`past_key_values`). + + Returns the prompt embeddings tensor that was loaded into the adapter. + """ + if adapter_name is None: + adapter_name = model.active_adapter + config = model.peft_config[adapter_name] + if config.peft_type not in (PeftType.CARTRIDGE, PeftType.PREFIX_TUNING): + raise ValueError( + f"Adapter '{adapter_name}' must be a CARTRIDGE or PREFIX_TUNING adapter (got {config.peft_type})." + ) + if getattr(config, "prefix_projection", False): + raise ValueError( + "Initialization from KV cache is not supported for prefix tuning with `prefix_projection=True`." + ) + if num_virtual_tokens is None: + num_virtual_tokens = config.num_virtual_tokens + + prompt_embeddings = prompt_embeddings_from_past_key_values(past_key_values, num_virtual_tokens=num_virtual_tokens) + model.prompt_encoder[adapter_name].load_prompt_embeddings(prompt_embeddings) + return prompt_embeddings + + +@torch.no_grad() +def initialize_kv_prefix_from_text( + model, + tokenizer, + *, + text: str, + adapter_name: Optional[str] = None, + num_virtual_tokens: Optional[int] = None, + use_chat_template: bool = True, + max_length: Optional[int] = None, +) -> torch.Tensor: + """ + Convenience initializer: prefill the base model on `text` and load the resulting cache prefix into the adapter. + """ + if adapter_name is None: + adapter_name = model.active_adapter + config = model.peft_config[adapter_name] + if config.peft_type not in (PeftType.CARTRIDGE, PeftType.PREFIX_TUNING): + raise ValueError( + f"Adapter '{adapter_name}' must be a CARTRIDGE or PREFIX_TUNING adapter (got {config.peft_type})." + ) + if getattr(config, "prefix_projection", False): + raise ValueError( + "Initialization from KV cache is not supported for prefix tuning with `prefix_projection=True`." + ) + if num_virtual_tokens is None: + num_virtual_tokens = config.num_virtual_tokens + + def _tokenize_plain(): + toks = tokenizer(text, return_tensors="pt", truncation=max_length is not None, max_length=max_length) + return toks["input_ids"] + + if use_chat_template and hasattr(tokenizer, "apply_chat_template"): + try: + input_ids = tokenizer.apply_chat_template( + [{"role": "system", "content": text}], + tokenize=True, + add_generation_prompt=False, + return_dict=False, + return_tensors="pt", + ) + except (TypeError, ValueError): + # Some tokenizers don't support the full signature or do not define a chat template. + input_ids = _tokenize_plain() + else: + if max_length is not None and input_ids.shape[1] > max_length: + input_ids = input_ids[:, :max_length] + else: + input_ids = _tokenize_plain() + + input_ids = input_ids.to(model.device) + attention_mask = torch.ones_like(input_ids) + with model.disable_adapter(): + outputs = model(input_ids=input_ids, attention_mask=attention_mask, use_cache=True) + return initialize_kv_prefix_from_past_key_values( + model, + adapter_name=adapter_name, + past_key_values=outputs.past_key_values, + num_virtual_tokens=num_virtual_tokens, + ) + + +def compose_cartridge_adapters( + adapter_paths: Sequence[str | Path], + *, + output_path: str | Path, + safe_serialization: bool = True, +) -> None: + """ + Compose multiple CARTRIDGE adapters by concatenating their prompt embeddings. + + This implements the paper's "composition via concatenation" behavior at the adapter level (no runtime + multi-adapter). + """ + adapter_paths = [Path(p) for p in adapter_paths] + if len(adapter_paths) < 2: + raise ValueError("Need at least 2 adapters to compose.") + + configs = [PeftConfig.from_pretrained(str(p)) for p in adapter_paths] + for p, cfg in zip(adapter_paths, configs): + if cfg.peft_type != PeftType.CARTRIDGE: + raise ValueError(f"Adapter at '{p}' is not a CARTRIDGE adapter (got {cfg.peft_type}).") + + base = configs[0] + for cfg in configs[1:]: + for attr in ("task_type", "token_dim", "num_layers", "num_attention_heads", "num_transformer_submodules"): + if getattr(cfg, attr, None) != getattr(base, attr, None): + raise ValueError(f"Incompatible CARTRIDGE configs for attribute '{attr}'.") + + weights = [load_peft_weights(str(p), device="cpu") for p in adapter_paths] + prompt_embeddings = [w["prompt_embeddings"] for w in weights] + composed = torch.cat(prompt_embeddings, dim=0) + + num_virtual_tokens = composed.shape[0] + # Preserve the "frozen prefix tokens" count of the first adapter only (matches a single attention-sink prefix). + num_frozen_tokens = base.num_frozen_tokens + out_cfg = replace(base, num_virtual_tokens=num_virtual_tokens, num_frozen_tokens=num_frozen_tokens) + + output_path = Path(output_path) + output_path.mkdir(parents=True, exist_ok=True) + out_cfg.save_pretrained(str(output_path)) + + if safe_serialization: + save_file({"prompt_embeddings": composed}, str(output_path / SAFETENSORS_WEIGHTS_NAME)) + else: + torch.save({"prompt_embeddings": composed}, str(output_path / WEIGHTS_NAME)) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/cpt/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/cpt/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fcd4de85989168ad6834712679c805cba39c1df1 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/cpt/__init__.py @@ -0,0 +1,24 @@ +# 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 peft.utils import register_peft_method + +from .config import CPTConfig +from .model import CPTEmbedding + + +__all__ = ["CPTConfig", "CPTEmbedding"] + +register_peft_method(name="cpt", config_cls=CPTConfig, model_cls=CPTEmbedding) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/cpt/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/cpt/config.py new file mode 100644 index 0000000000000000000000000000000000000000..d23b0acc650ed1aae04d43cdcb53a4f7613389f4 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/cpt/config.py @@ -0,0 +1,99 @@ +# 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 dataclasses import dataclass, field +from typing import Literal, Optional + +from peft.config import PromptLearningConfig +from peft.utils import PeftType, TaskType + + +@dataclass +class CPTConfig(PromptLearningConfig): + """ + CPT Configuration class extending PeftConfig for Context-aware Prompt Tuning (CPT). + + This class introduces additional parameters required for CPT, such as: + - Token type masks + - Prompt tuning initialization + - Loss weighting + - Projection settings + + For more details, see the paper: https://huggingface.co/papers/2410.17222 + """ + + # Token-related configurations + cpt_token_ids: Optional[list[int]] = field( + default=None, metadata={"help": "Tensor of token IDs used for CPT prompts."} + ) + cpt_mask: Optional[list[int]] = field(default=None, metadata={"help": "Tensor mask applied to CPT tokens."}) + cpt_tokens_type_mask: Optional[list[int]] = field( + default=None, metadata={"help": "Mask indicating the type of each CPT token."} + ) + + # Loss-related configurations + opt_weighted_loss_type: Optional[Literal["none", "decay"]] = field( + default="none", metadata={"help": "Type of weighted loss: 'none' or 'decay'."} + ) + opt_loss_decay_factor: Optional[float] = field( + default=1.0, metadata={"help": "Factor for exponential decay in loss weighting."} + ) + + # Projection-related configurations + opt_projection_epsilon: Optional[float] = field( + default=0.1, metadata={"help": "Epsilon value for input projection."} + ) + opt_projection_format_epsilon: Optional[float] = field( + default=0.1, metadata={"help": "Epsilon value for format projection."} + ) + + # Tokenizer configuration + 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`" + }, + ) + # Neet to define CPT-specific static attributes + is_prompt_learning = True # Indicates that CPT is a prompt-learning method. + + def __post_init__(self): + """ + Post-initialization hook to set additional attributes after the config is initialized. + """ + # CPT-specific static attributes + self.is_prompt_learning = True # Indicates that CPT is a prompt-learning method. + self.num_layers = None # Number of layers (optional, not always required). + self.token_dim = None # Dimension of token embeddings. + self.num_attention_heads = None # Number of attention heads (if applicable). + self.num_transformer_submodules = 1 # Number of transformer submodules used. + self.peft_type = PeftType.CPT # Specifies that the PEFT type is CPT. + if self.task_type != TaskType.CAUSAL_LM: + raise ValueError(f"{self.__class__.__name__} only supports task_type = {TaskType.CAUSAL_LM.value}.") + + if self.cpt_token_ids is None: + self.cpt_token_ids = [0] + + self.num_virtual_tokens = len(self.cpt_token_ids) + + if self.cpt_mask is None: + self.cpt_mask = [1 for _ in self.cpt_token_ids] + + if self.cpt_tokens_type_mask is None: + self.cpt_tokens_type_mask = [1 for _ in self.cpt_token_ids] + + if not ( + len(self.cpt_token_ids) == len(self.cpt_mask) == len(self.cpt_tokens_type_mask) == self.num_virtual_tokens + ): + raise ValueError("cpt_token_ids, cpt_mask and cpt_tokens_type_mask must have the same length.") diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/cpt/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/cpt/model.py new file mode 100644 index 0000000000000000000000000000000000000000..6c4dc08e5153b38827e638691f315abc432cd5dc --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/cpt/model.py @@ -0,0 +1,202 @@ +# 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 copy + +import torch +from torch.nn import CrossEntropyLoss + +from peft.utils.integrations import gather_params_ctx + + +class CPTEmbedding(torch.nn.Module): + """ + CPTEmbedding is a custom embedding layer designed for Context-aware Prompt Tuning (CPT) in PEFT. It initializes + embeddings, applies prompt-specific projections, and computes loss using label masks. + """ + + def __init__(self, config, word_embeddings): + """ + Initializes the CPTEmbedding module. + + Args: + config (Namespace): + Configuration object containing model hyperparameters and CPT-specific settings. + word_embeddings (torch.nn.Embedding): + The base word embedding layer used to initialize CPT embeddings. + """ + super().__init__() + self.config = copy.deepcopy(config) + num_virtual_tokens = config.num_virtual_tokens + + # Initialize embeddings with virtual token dimensions + self.embedding = torch.nn.Embedding(num_virtual_tokens, config.token_dim) + + # Initialize embeddings using text-based prompt tuning, if configured + if not config.inference_mode: + assert config.num_virtual_tokens == len(config.cpt_token_ids) + + init_token_ids = torch.LongTensor(config.cpt_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) + + self.embedding.requires_grad_(False) + + # Initialize delta embedding with zero weights + self.delta_embedding = torch.nn.Embedding(num_virtual_tokens, config.token_dim) + self.delta_embedding.weight.data = torch.zeros_like(self.delta_embedding.weight).to(torch.float32) + + # Apply hook for backward gradient updates + self.set_updated_tokens() + + def forward(self, indices): + """ + Computes the prompt embeddings and applies delta adjustments. + + Args: + indices (torch.Tensor): + Indices of the tokens to be embedded. + + Returns: + torch.Tensor: + Sum of prompt embeddings and delta embeddings. + """ + with torch.no_grad(): + prompt_embeddings = self.embedding(indices) + + self.delta_embedding.weight.data = self.get_projection() # Apply epsilon-based projection + + delta_prompt_embeddings = self.delta_embedding(indices) + + return prompt_embeddings + delta_prompt_embeddings + + def set_updated_tokens(self): + """ + Sets up a backward hook to selectively update token gradients based on the CPT token type mask. + """ + tensor_ICL_mask = torch.Tensor(self.config.cpt_tokens_type_mask).long() + mask_input_template = torch.remainder(tensor_ICL_mask, 4) == 1 + mask_input = torch.remainder(tensor_ICL_mask, 4) == 2 + mask_output_template = torch.remainder(tensor_ICL_mask, 4) == 3 + mask = mask_input_template | mask_input | mask_output_template + mask = mask.view(-1, 1) + + def backward_hook(grad): + grad = grad * mask.to(grad.device) # Apply mask to gradients + return grad + + self.delta_embedding.weight.register_hook(backward_hook) + + def get_epsilon(self): + cpt_tokens_type_mask = self.config.cpt_tokens_type_mask + + MIN_VALUE = 1e-10 + + # Calculate normalized epsilon values for input, output, and format tokens + normalized_format_eps = self.config.opt_projection_format_epsilon * torch.sqrt( + torch.Tensor([self.config.token_dim / 2048]) + ) + normalized_input_eps = self.config.opt_projection_epsilon * torch.sqrt( + torch.Tensor([self.config.token_dim / 2048]) + ) + + epsilon = torch.ones_like(torch.Tensor(cpt_tokens_type_mask)).to(torch.float32) * MIN_VALUE + cpt_tokens_type_mask = torch.Tensor(cpt_tokens_type_mask).long() + + epsilon[(cpt_tokens_type_mask > 0) & (torch.remainder(cpt_tokens_type_mask, 4) == 1)] = normalized_format_eps + epsilon[(cpt_tokens_type_mask > 0) & (torch.remainder(cpt_tokens_type_mask, 4) == 3)] = normalized_format_eps + epsilon[(cpt_tokens_type_mask > 0) & (torch.remainder(cpt_tokens_type_mask, 4) == 2)] = normalized_input_eps + + return epsilon + + def get_projection(self): + """ + Applies epsilon-based projection to the delta embeddings to control their norm. + """ + + # Apply projection to control delta embedding norm + with torch.no_grad(): + new_embeddings_weights = self.delta_embedding.weight.clone().to(self.delta_embedding.weight.device) + token_norm = torch.norm(new_embeddings_weights, p=2, dim=1) + + projection_mask = token_norm > 0 + if torch.any(projection_mask): + epsilon = self.get_epsilon().to(self.delta_embedding.weight.device) + new_embeddings_weights[projection_mask] *= ( + epsilon[projection_mask] / (token_norm[projection_mask].clamp(min=epsilon[projection_mask])) + ).view(-1, 1) + return new_embeddings_weights + + @staticmethod + def calculate_loss(base_model_output, labels, cpt_type_mask, config): + """ + Computes the loss for CPT models with optional exponential decay. + + Args: + base_model_output (ModelOutput): + Output from the base model containing logits. + labels (torch.Tensor): + Ground-truth labels for the input tokens. + cpt_type_mask (torch.Tensor): + Token type mask used for filtering valid loss terms. + config (Namespace): + Configuration object containing loss-related hyperparameters. + + Returns: + ModelOutput: + The base model output with computed loss. + """ + + device = base_model_output.logits.device + + lm_logits = base_model_output.logits + labels = labels.to(device) + + # Shift logits and labels for token prediction + shift_logits = lm_logits[..., :-1, :].contiguous() + shift_labels = labels[..., 1:].contiguous() + shift_cpt_type_mask = cpt_type_mask[..., 1:].contiguous() + + shift_labels_bool = (shift_labels.clone().detach() != -100).bool() + batch_size, seq_length, vocab_size = shift_logits.shape + + # Compute cross-entropy loss + loss_fct = CrossEntropyLoss(reduction="none", ignore_index=-100) + loss = loss_fct( + shift_logits.view(batch_size * seq_length, vocab_size), shift_labels.view(batch_size * seq_length) + ) + loss = loss.view(batch_size, seq_length) + # Apply exponential decay weights to the loss + shift_labels_weights = shift_labels_bool.clone().detach().float() + + for i in range(batch_size): + idx_labels = (shift_cpt_type_mask[i] > 0) & (shift_cpt_type_mask[i] % 4 == 0) + labels_ids = shift_cpt_type_mask[i][idx_labels].unique() + + exponential_decay = torch.ones_like(shift_cpt_type_mask[i]).to(device=device).float() + decay_value = 1 + for label_mask_idx in torch.flip(labels_ids, [0]): + exponential_decay[shift_cpt_type_mask[i] == label_mask_idx] = decay_value + decay_value *= config.opt_loss_decay_factor + if config.opt_weighted_loss_type == "decay": + shift_labels_weights[i] *= exponential_decay + + # Compute the weighted mean loss + loss = (loss[shift_labels_bool] * shift_labels_weights[shift_labels_bool]).mean() + + base_model_output.loss = loss + + return base_model_output diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/delora/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/delora/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..982801ca5665621e50cda5c6540203fdaa29f34c --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/delora/__init__.py @@ -0,0 +1,23 @@ +# 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 DeloraConfig +from .layer import DeloraLayer, DeloraLinear +from .model import DeloraModel + + +__all__ = ["DeloraConfig", "DeloraLayer", "DeloraLinear", "DeloraModel"] + +register_peft_method(name="delora", model_cls=DeloraModel, config_cls=DeloraConfig) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/delora/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/delora/config.py new file mode 100644 index 0000000000000000000000000000000000000000..9535a9d2765f7e4e5bcdc5b5bb5615d334a95f81 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/delora/config.py @@ -0,0 +1,162 @@ +# 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 Literal, Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class DeloraConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`DeloraModel`]. + + Args: + r (`int`): + The rank of the DeLoRA adapter. + delora_lambda (`int`): + The initial value of the boundary of the DeLoRA adapter. This variable sets an upper bound to the Frobenius + norm of the weight change, avoiding the finetuned model to deviate too much from the original model. + module_dropout (`float`): + The dropout probability for disabling DeLoRA modules during training. + 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/Conv1D 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. + 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. + bias (`str`): + Bias type for DeLoRA. Can be 'none', 'all' or 'delora_only'. If 'all' or 'delora_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. + init_weights (`bool`): + Whether to perform initialization of adapter weights. If `True` (default): A is initialized with kaiming + uniform initialization, while B is initialized with zeros. If `False`: A and B are both initialized with + kaiming uniform, immediately contributing a non-zero delta. This is generally discouraged for normal use. + 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'`. + rank_pattern (`dict`): + The mapping from layer names or regexp expression to ranks which are different from the default rank + specified by `r`. For example, `{'^model.decoder.layers.0.encoder_attn.k_proj': 16}`. + lambda_pattern (`dict`): + The mapping from layer names or regexp expression to lambdas which are different from the default lambda + specified by `delora_lambda`. For example, `{'^model.decoder.layers.0.encoder_attn.k_proj': 16}`. + modules_to_save (`Optional[List[str]]`): + List of modules apart from adapter layers to be set as trainable and saved in the final checkpoint. + """ + + r: int = field(default=8, metadata={"help": "DeLoRA rank"}) + delora_lambda: int = field( + default=15, + metadata={ + "help": "The initial value of the boundary of the DeLoRA adapter. This variable sets an upper bound to the " + "Frobenius norm of the weight change, avoiding the finetuned model to deviate too much from the original model." + }, + ) + module_dropout: float = field( + default=0.0, metadata={"help": "The dropout probability for disabling DeLoRA modules during training"} + ) + 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 DeLoRA." + "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$' " + "This can also be a wildcard 'all-linear' which matches all linear layers except the output layer." + }, + ) + 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 DeLoRA."}, + ) + bias: Literal["none", "all", "delora_only"] = field( + default="none", metadata={"help": "Bias type for DeLoRA. Can be 'none', 'all' or 'delora_only'"} + ) + init_weights: bool = field( + default=True, + metadata={ + "help": "Whether to perform initialization of adapter weights. If `True` (default): A is initialized with kaiming uniform " + "initialization, while B is initialized with zeros. If `False`: A and B are both initialized with kaiming uniform, " + "immediately contributing a non-zero delta. This is generally discouraged for normal use." + }, + ) + 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'`." + }, + ) + rank_pattern: Optional[dict] = field( + default_factory=dict, + metadata={ + "help": "The mapping from layer names or regexp expression to ranks which are different from the default rank specified " + "by `r`. For example, `{'^model.decoder.layers.0.encoder_attn.k_proj': 16}`." + }, + ) + lambda_pattern: Optional[dict] = field( + default_factory=dict, + metadata={ + "help": "The mapping from layer names or regexp expression to lambdas which are different from the default lambda specified by `delora_lambda`." + }, + ) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": "List of modules apart from DeLoRA 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__() + # PeftType enum members are uppercase; use DELORA + self.peft_type = PeftType.DELORA + 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 + ) + # if target_modules is a regex expression, then layers_to_transform should be None + if isinstance(self.target_modules, str) and self.layers_to_transform is not None: + raise ValueError("`layers_to_transform` cannot be used when `target_modules` is a str.") + + # 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: + raise ValueError(f"`r` must be a positive integer; got {self.r}.") diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/delora/layer.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/delora/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..789ee5bcafd712feaeab1afc60a853eecd5148b6 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/delora/layer.py @@ -0,0 +1,274 @@ +# 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 Any, Optional + +import torch +from torch import nn + +from peft.tuners._buffer_dict import BufferDict +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge + +from .config import DeloraConfig + + +class DeloraLayer(BaseTunerLayer): + # All names of layers that may contain (trainable) adapter weights + adapter_layer_names = ( + "delora_A", + "delora_B", + "delora_lambda", + ) + # All names of other parameters that may contain adapter-related parameters + other_param_names = ( + "r", + "delora_dropout", + "delora_w_norm", + ) + + def __init__(self, base_layer: nn.Module, **kwargs) -> None: + self.base_layer = base_layer + self.r = {} + self.delora_dropout = nn.ModuleDict({}) + self.delora_A = nn.ParameterDict({}) + self.delora_B = nn.ParameterDict({}) + self.delora_lambda = nn.ParameterDict({}) + # Use persistent buffers so they are included in state_dict and saved. + self.delora_w_norm = BufferDict({}, persistent=True) + # Mark the weight as unmerged + self._disable_adapters = False + self.merged_adapters = [] + self.kwargs = kwargs + + base_layer_mod = self.get_base_layer() + if isinstance(base_layer_mod, nn.Linear): + self.in_features, self.out_features = base_layer_mod.in_features, base_layer_mod.out_features + else: + raise TypeError(f"Unsupported layer type {type(base_layer_mod)}") + + @staticmethod + def _compute_delta( + A: torch.Tensor, B: torch.Tensor, delora_lambda: torch.Tensor, r: int, w_norm: torch.Tensor + ) -> torch.Tensor: + """Compute delta = B @ diag(delora_lambda/r / (||A_i||*||B^j||)) @ A, scaled by provided w_norm (per-input channel)""" + An = torch.clamp(A.norm(dim=1), min=1e-4) + Bn = torch.clamp(B.norm(dim=0), min=1e-4) + diag = torch.diag_embed(delora_lambda / r / (An * Bn)) + delta = B @ diag @ A + delta = delta * w_norm.unsqueeze(0) + return delta + + def get_delta_weight(self, adapter: str) -> torch.Tensor: + if adapter not in self.delora_A or adapter not in self.delora_B: + raise ValueError(f"Adapter {adapter} not found.") + + delta = self._compute_delta( + self.delora_A[adapter], + self.delora_B[adapter], + self.delora_lambda[adapter], + self.r[adapter], + self.delora_w_norm[adapter], + ) + return delta + + def update_layer( + self, + adapter_name: str, + r: int, + delora_lambda: float, + config: DeloraConfig, + **kwargs: Any, + ) -> None: + """Internal function to create delora adapter + + Args: + adapter_name (`str`): Name for the adapter to add. + r (`int`): Rank for the added adapter. + delora_lambda (`float`): Boundary for the adapter's norm. + config (`DeloraConfig`): The adapter configuration for this layer. + """ + module_dropout = config.module_dropout + init_weights = config.init_weights + inference_mode = config.inference_mode + + 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.delora_A[adapter_name] = nn.Parameter(torch.empty(r, self.in_features)) + self.delora_B[adapter_name] = nn.Parameter(torch.empty(self.out_features, r)) + self.delora_lambda[adapter_name] = nn.Parameter(torch.empty(1)) + if module_dropout > 0.0: + module_dropout_layer = nn.Dropout(p=module_dropout) + else: + module_dropout_layer = nn.Identity() + self.delora_dropout.update(nn.ModuleDict({adapter_name: module_dropout_layer})) + + # Initialize weights + self.reset_delora_parameters(adapter_name, init_weights, delora_lambda) + + # 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_delora_parameters( + self, + adapter_name: str, + init_weights: bool = True, + delora_lambda: float = 15.0, + ) -> None: + if adapter_name not in self.delora_A.keys(): + return + + if init_weights is True: + nn.init.kaiming_uniform_(self.delora_A[adapter_name], a=math.sqrt(5)) + nn.init.zeros_(self.delora_B[adapter_name]) + else: + nn.init.kaiming_uniform_(self.delora_A[adapter_name], a=math.sqrt(5)) + nn.init.kaiming_uniform_(self.delora_B[adapter_name], a=math.sqrt(5)) + + self.delora_lambda[adapter_name].data.fill_(float(delora_lambda)) + + # capture a fixed norm for this adapter to use for future delta computations + with torch.no_grad(): + w = self.get_base_layer().weight + if w.device.type != "meta": + w_norm = torch.norm(w.data, dim=0).detach() + else: + # For meta tensors, we can't compute the norm, so use a default value + w_norm = torch.ones(w.shape[1], device=w.device) + self.delora_w_norm[adapter_name] = w_norm + + +class DeloraLinear(nn.Module, DeloraLayer): + # DeLoRA implemented in a dense layer + def __init__( + self, + base_layer, + adapter_name: str, + config: DeloraConfig, + r: int, + delora_lambda: float, + **kwargs, + ) -> None: + super().__init__() + DeloraLayer.__init__(self, base_layer, **kwargs) + self._active_adapter = adapter_name + self.update_layer(adapter_name, r, delora_lambda, config=config) + + 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 in self.delora_A.keys(): + base_layer = self.get_base_layer() + delta_weight = ( + self.get_delta_weight(active_adapter) + .detach() + .to(dtype=base_layer.weight.dtype, device=base_layer.weight.device) + ) + with torch.no_grad(): + if safe_merge: + orig_weights = base_layer.weight.data.clone() + orig_weights = orig_weights + delta_weight + + 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.add_(delta_weight) + + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + Unmerge 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 in self.delora_A.keys(): + self.get_base_layer().weight.data -= self.get_delta_weight(active_adapter) + + 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: + if not self.active_adapters: + return self.base_layer(x, *args, **kwargs).to(previous_dtype) + + base_out = self.base_layer(x, *args, **kwargs) + add_out = torch.zeros_like(base_out) + + for adapter in self.active_adapters: + if adapter not in self.delora_A: + continue + + x_d = self.delora_dropout[adapter](x) + + # Decomposed delta calculation + # 1. (x * w_norm) @ A.T + h = nn.functional.linear(x_d * self.delora_w_norm[adapter], self.delora_A[adapter]) + + # 2. h @ diag + An = torch.clamp(self.delora_A[adapter].norm(dim=1), min=1e-4) + Bn = torch.clamp(self.delora_B[adapter].norm(dim=0), min=1e-4) + scaling = (self.delora_lambda[adapter] / self.r[adapter]) / (An * Bn) + + h = h * scaling + + # 3. h @ B.T + h = nn.functional.linear(h, self.delora_B[adapter]) + + add_out += h + + result = base_out + add_out.to(base_out.dtype) + + 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 "delora." + rep diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/delora/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/delora/model.py new file mode 100644 index 0000000000000000000000000000000000000000..b97998de548ecf5f304cacab9d3cb36938728309 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/delora/model.py @@ -0,0 +1,104 @@ +# 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 + +from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer +from peft.utils import ( + TRANSFORMERS_MODELS_TO_DELORA_TARGET_MODULES_MAPPING, +) +from peft.utils.other import get_pattern_key + +from .config import DeloraConfig +from .layer import DeloraLayer, DeloraLinear + + +class DeloraModel(BaseTuner): + """ + Creates DeLoRA model from a pretrained transformers model. + + The method is described in detail in [DeLoRA: Decoupled Low-rank + Adaptation](https://huggingface.co/papers/2503.18225). + + Args: + model ([`torch.nn.Module`]): The model to be adapted. + config ([`DeloraConfig`]): The configuration of the DeLoRA model. + adapter_name (`str`): The name of the adapter, defaults to `"default"`. + + Returns: + `torch.nn.Module`: The DeLoRA model. + + **Attributes**: + - **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted. + - **peft_config** ([`DeloraConfig`]): The configuration of the DeLoRA model. + """ + + prefix: str = "delora_" + tuner_layer_cls = DeloraLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_DELORA_TARGET_MODULES_MAPPING + + def _check_new_adapter_config(self, config: DeloraConfig) -> 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) + + def _create_and_replace( + self, + delora_config, + adapter_name, + target, + target_name, + parent, + current_key, + **optional_kwargs, + ): + if current_key is None: + raise ValueError("Current Key shouldn't be `None`") + + # Regexp matching - Find key which matches current target_name in patterns provided + r_key = get_pattern_key(delora_config.rank_pattern.keys(), current_key) + lambda_key = get_pattern_key(delora_config.lambda_pattern.keys(), current_key) + r = delora_config.rank_pattern.get(r_key, delora_config.r) + delora_lambda = delora_config.lambda_pattern.get(lambda_key, delora_config.delora_lambda) + + kwargs = { + "r": r, + "delora_lambda": delora_lambda, + } + + if isinstance(target, DeloraLinear): + target.update_layer(adapter_name, config=delora_config, **kwargs) + else: + new_module = self._create_new_module(delora_config, adapter_name, target, **kwargs) + if adapter_name != 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(delora_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): + new_module = DeloraLinear(target, adapter_name, config=delora_config, **kwargs) + + return new_module diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/fourierft/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/fourierft/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..dfe3f5d89e36123eefef7fc6e675c6b80bd8d44c --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/fourierft/__init__.py @@ -0,0 +1,24 @@ +# 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 peft.utils import register_peft_method + +from .config import FourierFTConfig +from .layer import FourierFTLayer, FourierFTLinear +from .model import FourierFTModel + + +__all__ = ["FourierFTConfig", "FourierFTLayer", "FourierFTLinear", "FourierFTModel"] + +register_peft_method(name="fourierft", model_cls=FourierFTModel, config_cls=FourierFTConfig) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/fourierft/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/fourierft/config.py new file mode 100644 index 0000000000000000000000000000000000000000..dbbb80d8e080e9237b711473b44d55f6ff186239 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/fourierft/config.py @@ -0,0 +1,206 @@ +# 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 + +from dataclasses import dataclass, field +from typing import Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class FourierFTConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`FourierFTModel`]. + + Args: + n_frequency (`int`): + Num of learnable frequencies for the Discrete Fourier Transform. 'n_frequency' is an integer that is + greater than 0 and less than or equal to d^2 (assuming the weight W has dimensions of d by d). + Additionally, it is the number of trainable parameters required to update each delta W weight. + 'n_frequency' will affect the performance and efficiency for PEFT. Specifically, it has little impact on + training speed, but higher values of it (typically) result in larger GPU memory costs and better accuracy. + With the same `target_modules`, the number of parameters of LoRA is (2*d*r/n_frequency) times that of + FourierFT. The following examples of settings regarding 'n_frequency' can be used as reference for users. + For NLU tasks with the RoBERTa-large model, adopting 'n_frequency': 1000 can almost achieve similar results + as 'r': 8 in LoRA. At this time, the number of parameters of LoRA is about 16 times that of FourierFT. For + image classification tasks with Vit-large models, adopting 'n_frequency': 3000 can almost achieve similar + results as 'r': 16 in LoRA, where the number of parameters of LoRA is about 11 times that of FourierFT. + scaling (`float`): + The scaling value for the delta W matrix. This is an important hyperparameter used for scaling, similar to + the 'lora_alpha' parameter in the LoRA method. 'scaling' can be determined during the hyperparameter search + process. However, if users want to skip this process, one can refer to the settings in the following + scenarios. This parameter can be set to 100.0 or 150.0 for both RoBERTa-base and RoBERTa-large models + across all NLU (GLUE) tasks. This parameter can be set to 300.0 for both LLaMA family models for all + instruction tuning. This parameter can be set to 300.0 for both ViT-base and ViT-large models across all + image classification tasks. + random_loc_seed (`int`): + Seed for the random location of the frequencies, i.e., the spectral entry matrix. + target_modules (`Union[list[str],str]`): + List of module names or regex expression of the module names to replace with FourierFT. For example, ['q', + 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'. Only linear layers are supported. + 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. + 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 FourierFT. Can be 'none', 'all' or 'fourier_only'. + modules_to_save (`list[str]`): + List of modules apart from FourierFT 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. + layers_to_transform (`Union[list[int],int]`): + 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]]`): + 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'`. + n_frequency_pattern (`dict`): + The mapping from layer names or regexp expression to n_frequency which are different from the default + specified. For example, `{model.decoder.layers.0.encoder_attn.k_proj: 1000`}. + init_weights (`bool`): + The initialization of the Fourier weights. Set this to False (the default) if the spectrum are initialized + to a standard normal distribution. Set this to True if the spectrum are initialized to zeros. + """ + + n_frequency: int = field( + default=1000, + metadata={ + "help": ( + "Num of learnable frequencies for the Discrete Fourier Transform. 'n_frequency' is an integer that is" + "greater than 0 and less than or equal to d^2 (assuming the weight W has dimensions of d by d)." + "Additionally, it is the number of trainable parameters required to update each delta W weight." + "'n_frequency' will affect the performance and efficiency for PEFT. Specifically, it has little impact on" + "training speed, but higher values of it (typically) result in larger GPU memory costs and better accuracy." + "With the same `target_modules`, the number of parameters of LoRA is (2*d*r/n_frequency) times that of FourierFT." + "The following examples of settings regarding 'n_frequency' can be used as reference for users. For NLU" + "tasks with the RoBERTa-large model, adopting 'n_frequency': 1000 can almost achieve similar results as" + "'r': 8 in LoRA. At this time, the number of parameters of LoRA is about 16 times that of FourierFT." + "For image classification tasks with Vit-large models, adopting 'n_frequency': 3000 can almost achieve" + "similar results as 'r': 16 in LoRA, where the number of parameters of LoRA is about 11 times that of FourierFT." + ) + }, + ) + scaling: float = field( + default=150.0, + metadata={ + "help": ( + "The scaling value for the delta W matrix. This is an important hyperparameter used for scaling, similar to the" + "'lora_alpha' parameter in the LoRA method. 'scaling' can be determined during the hyperparameter search process." + "However, if users want to skip this process, one can refer to the settings in the following scenarios." + "This parameter can be set to 100.0 or 150.0 for both RoBERTa-base and RoBERTa-large models across all NLU (GLUE) tasks." + "This parameter can be set to 300.0 for both LLaMA family models for all instruction tuning." + "This parameter can be set to 300.0 for both ViT-base and ViT-large models across all image classification tasks." + ) + }, + ) + random_loc_seed: Optional[int] = field( + default=777, metadata={"help": "Seed for the random location of the frequencies."} + ) + 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)"}, + ) + 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 FourierFT." + "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'. " + "Only linear layers are supported." + ) + }, + ) + 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 fourierft."}, + ) + bias: str = field( + default="none", metadata={"help": "Bias type for FourierFT. Can be 'none', 'all' or 'fourier_only'."} + ) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": ( + "List of modules apart from FourierFT 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." + ) + }, + ) + 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'`." + ) + }, + ) + n_frequency_pattern: Optional[dict] = field( + default_factory=dict, + metadata={ + "help": ( + "The mapping from layer names or regexp expression to n_frequency which are different from the default specified." + "For example, `{model.decoder.layers.0.encoder_attn.k_proj: 500`}." + ) + }, + ) + init_weights: bool = field( + default=False, + metadata={ + "help": ( + "The initialization of the Fourier weights. Set this to False (the default) if the spectrum should be " + "initialized to a standard normal distribution. Set this to True if the spectrum should be initialized " + "to zeros." + ) + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.FOURIERFT + 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 + ) + # if target_modules is a regex expression, then layers_to_transform should be None + if isinstance(self.target_modules, str) and self.layers_to_transform is not None: + raise ValueError("`layers_to_transform` cannot be used when `target_modules` is a str.") + + # if target_modules is a regex expression, then layers_pattern should be None + if isinstance(self.target_modules, str) and self.layers_pattern is not None: + raise ValueError("`layers_pattern` cannot be used when `target_modules` is a str.") + # 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. ") diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/fourierft/layer.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/fourierft/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..664cd4eaf773f6eb430f019b236ec510cf5f59c7 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/fourierft/layer.py @@ -0,0 +1,200 @@ +# 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 typing import Any, Optional + +import torch +import torch.nn.functional as F +from torch import nn +from transformers.pytorch_utils import Conv1D + +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge +from peft.utils.other import transpose + +from .config import FourierFTConfig + + +class FourierFTLayer(BaseTunerLayer): + # All names of layers that may contain (trainable) adapter weights + adapter_layer_names = ("fourierft_spectrum",) + # All names of other parameters that may contain adapter-related parameters + other_param_names = ("fourierft_n_frequency", "fourierft_scaling", "fourierft_random_loc_seed") + + def __init__(self, base_layer: nn.Module, **kwargs) -> None: + self.base_layer = base_layer + self.fourierft_n_frequency = {} + self.fourierft_scaling = {} + self.fourierft_spectrum = nn.ParameterDict({}) + self.indices = {} + self.fourierft_random_loc_seed = {} + # Mark the weight as unmerged + self._disable_adapters = False + self.merged_adapters = [] + self.kwargs = kwargs + + base_layer = self.get_base_layer() + if isinstance(base_layer, nn.Linear): + self.in_features, self.out_features = base_layer.in_features, base_layer.out_features + elif isinstance(base_layer, Conv1D): + self.in_features, self.out_features = ( + base_layer.weight.ds_shape if hasattr(base_layer.weight, "ds_shape") else base_layer.weight.shape + ) + else: + raise TypeError(f"Unsupported layer type {type(base_layer)}") + + def update_layer(self, adapter_name: str, n_frequency: int, config: FourierFTConfig, **kwargs): + scaling = config.scaling + init_weights = config.init_weights + random_loc_seed = config.random_loc_seed + inference_mode = config.inference_mode + + if n_frequency <= 0: + raise ValueError(f"`n_frequency` should be a positive integer value but the value passed is {n_frequency}") + if n_frequency > self.in_features * self.out_features: + raise ValueError( + f"`n_frequency` should be less than or equal to the product of the input and output dimensions " + f"but the value passed is {n_frequency} and the product is {self.in_features * self.out_features}" + ) + self.fourierft_n_frequency[adapter_name] = n_frequency + self.fourierft_random_loc_seed[adapter_name] = random_loc_seed + self.indices[adapter_name] = torch.randperm( + self.out_features * self.in_features, + generator=torch.Generator().manual_seed(self.fourierft_random_loc_seed[adapter_name]), + )[:n_frequency] + self.indices[adapter_name] = torch.stack( + [self.indices[adapter_name] // self.in_features, self.indices[adapter_name] % self.in_features], dim=0 + ) + self.fourierft_scaling[adapter_name] = scaling + # Actual trainable parameters + self.fourierft_spectrum[adapter_name] = nn.Parameter(torch.randn(n_frequency), requires_grad=True) + + if init_weights: + self.reset_fourier_parameters(adapter_name) + + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + @torch.no_grad() + def reset_fourier_parameters(self, adapter_name): + if adapter_name in self.fourierft_spectrum.keys(): + nn.init.zeros_(self.fourierft_spectrum[adapter_name]) + + def get_delta_weight(self, adapter) -> torch.Tensor: + # careful: ifft2 does not work with float16 or bfloat16 + spectrum = self.fourierft_spectrum[adapter] + indices = self.indices[adapter].to(spectrum.device) + dense_spectrum = torch.zeros(self.out_features, self.in_features, device=spectrum.device) + dense_spectrum[indices[0, :], indices[1, :]] = spectrum.float() + delta_weight = torch.fft.ifft2(dense_spectrum).real * self.fourierft_scaling[adapter] + return delta_weight.to(spectrum.dtype) + + +class FourierFTLinear(nn.Module, FourierFTLayer): + # FourierFT implemented in a dense layer + def __init__( + self, + base_layer, + adapter_name: str, + config: FourierFTConfig, + n_frequency: int = 1000, + **kwargs, + ) -> None: + super().__init__() + FourierFTLayer.__init__(self, base_layer, **kwargs) + self.fan_in_fan_out = config.fan_in_fan_out + self._active_adapter = adapter_name + self.update_layer(adapter_name, n_frequency, config=config) + + 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.fourierft_spectrum.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 += transpose(self.get_delta_weight(active_adapter), self.fan_in_fan_out) + + 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 += transpose(self.get_delta_weight(active_adapter), self.fan_in_fan_out) + 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 in self.fourierft_spectrum.keys(): + self.get_base_layer().weight.data -= transpose( + self.get_delta_weight(active_adapter), self.fan_in_fan_out + ) + + 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: + result = self.base_layer(x, *args, **kwargs) + for active_adapter in self.active_adapters: + if active_adapter not in self.fourierft_spectrum.keys(): + continue + + delta_w = self.get_delta_weight(active_adapter) + x = x.to(delta_w.dtype) + result = result + F.linear(x, delta_w) + + result = result.to(previous_dtype) + return result + + def supports_lora_conversion(self, adapter_name: str = "default") -> bool: + # get_delta_weight does not transpose Conv1D because it is used in forward, therefore, it has the wrong + # shape for conversion + return not isinstance(self.get_base_layer(), Conv1D) + + def __repr__(self) -> str: + rep = super().__repr__() + return "fourierft." + rep diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/fourierft/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/fourierft/model.py new file mode 100644 index 0000000000000000000000000000000000000000..98b1680346af0df472dcc863859d5af4bbeb19da --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/fourierft/model.py @@ -0,0 +1,118 @@ +# 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 re +import warnings +from itertools import chain + +import torch +from transformers.pytorch_utils import Conv1D + +from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer +from peft.utils import ( + TRANSFORMERS_MODELS_TO_FOURIERFT_TARGET_MODULES_MAPPING, +) + +from .layer import FourierFTLayer, FourierFTLinear + + +class FourierFTModel(BaseTuner): + """ + Creates FourierFT model from a pretrained transformers model. + + The method is described in detail in https://huggingface.co/papers/2405.03003. + + Args: + model ([`torch.nn.Module`]): The model to be adapted. + config ([`FourierFTConfig`]): The configuration of the FourierFT 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 FourierFT model. + + **Attributes**: + - **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted. + - **peft_config** ([`FourierFTConfig`]): The configuration of the Fourier model. + """ + + prefix: str = "fourierft_" + tuner_layer_cls = FourierFTLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_FOURIERFT_TARGET_MODULES_MAPPING + + def _create_and_replace( + self, + fourierft_config, + adapter_name, + target, + target_name, + parent, + current_key, + **optional_kwargs, + ): + if current_key is None: + raise ValueError("Current Key shouldn't be `None`") + # Regexp matching - Find key which matches current target_name in patterns provided + pattern_keys = list(chain(fourierft_config.n_frequency_pattern.keys())) + target_name_key = next(filter(lambda key: re.match(rf".*\.{key}$", current_key), pattern_keys), current_key) + + n_frequency = fourierft_config.n_frequency_pattern.get(target_name_key, fourierft_config.n_frequency) + kwargs = { + "n_frequency": n_frequency, + } + if isinstance(target, FourierFTLayer): + target.update_layer( + adapter_name, + n_frequency, + config=fourierft_config, + ) + else: + new_module = self._create_new_module(fourierft_config, adapter_name, target, **kwargs) + if adapter_name != 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(fourierft_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): + if fourierft_config.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." + ) + fourierft_config.fan_in_fan_out = False + elif isinstance(target_base_layer, Conv1D): + kwargs["is_target_conv_1d_layer"] = True + if not fourierft_config.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." + ) + fourierft_config.fan_in_fan_out = True + else: + raise TypeError( + f"Target module {target} is not supported. Currently, only the following modules are supported: " + "`torch.nn.Linear`." + ) + + new_module = FourierFTLinear(target, adapter_name, config=fourierft_config, **kwargs) + + return new_module diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/gralora/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/gralora/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..830e0a477c45632ebe83b0be2b15c816e9087160 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/gralora/__init__.py @@ -0,0 +1,24 @@ +# 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 GraloraConfig +from .layer import GraloraLayer +from .model import GraloraModel + + +__all__ = ["GraloraConfig", "GraloraLayer", "GraloraModel"] + +register_peft_method(name="gralora", config_cls=GraloraConfig, model_cls=GraloraModel) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/gralora/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/gralora/config.py new file mode 100644 index 0000000000000000000000000000000000000000..39f6c1b0b91ebb7051a834caa9a33e1930435f27 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/gralora/config.py @@ -0,0 +1,182 @@ +# 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 dataclasses import dataclass, field +from typing import Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class GraloraConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`GraloraModel`]. + + Args: + r (`int`): + GraLoRA attention dimension determines the rank of the GraLoRA adapter. The total parameter count of the + GraLoRA adapter is same as LoRA with same rank r, while the expressivitiy is multiplied by gralora_k. + hybrid_r (`int`): + Hybrid GraLoRA rank determines the rank allocated to vanilla LoRA method when using Hybrid GraLoRA method. + Hybrid GraLoRA, a combination of GraLoRA and vanilla LoRA, becomes available when hybrid_r > 0. The + parameter count of the GraLoRA adapter is r + hybrid_r. + target_modules (`Union[List[str], str]`): + List of module names or regex expression of the module names to replace with GraLoRA. " For example, ['q', + 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'. " This can also be a wildcard 'all-linear' + which matches all linear/Conv1D " "(if the model is a PreTrainedModel, the output layer excluded). " If 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. " To avoid + targeting any modules (because you want to apply `target_parameters`), set " `target_modules=[]`. + alpha (`int`): GraLoRA alpha. + GraLoRA alpha is the scaling factor for the GraLoRA adapter. Scale becomes alpha / (r + hybrid_r). + gralora_dropout (`float`): + GraLoRA dropout is the dropout probability for the GraLoRA adapter. It is used to prevent overfitting and + improve the generalization of the GraLoRA adapter. + gralora_k (`int`): + GraLoRA k determines the number of subblocks in the GraLoRA adapter. The rank r must be divisible by + gralora_k for the GraLoRA adapter to be valid. The total parameter count is preserved regardles of + gralora_k. The entire rank of the GraLoRA adapter is increased by gralora_k, while the rank of each + subblock is reduced by gralora_k. gralora_k=2 is recommended for rank 32 or lower, and gralora_k=4 is + recommended for rank 64 or higher. + 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 for gralora. Can be 'none', 'all' or 'gralora_only'. If 'all' or 'gralora_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. + init_weights (`bool`): + Whether to initialize the weights of the GraLoRA 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, 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. This only works when target_modules is a list of str. + layers_pattern (`Optional[Union[List[str], str]]`): + 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 only works when target_modules is a list of str. This should target + the `nn.ModuleList` of the model, which is often called `'layers'` or `'h'`. + """ + + r: int = field( + default=32, + metadata={ + "help": ( + "GraLoRA attention dimension determines the rank of the GraLoRA adapter. " + "The total parameter count of the GraLoRA adapter is same as LoRA with same rank r, while the expressivitiy is multiplied by gralora_k." + ) + }, + ) + hybrid_r: int = field( + default=0, + metadata={ + "help": ( + "hybrid_r is the rank allocated to vanilla LoRA method when using Hybrid GraLoRA method. " + "Hybrid GraLoRA, a combination of GraLoRA and vanilla LoRA, becomes available when hybrid_r > 0. " + "r + hybrid_r determines the parameter count of the GraLoRA adapter." + ) + }, + ) + 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 LoRA. " + "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'. " + "This can also be a wildcard 'all-linear' which matches all linear/Conv1D " + "(if the model is a PreTrainedModel, the output layer excluded). " + "If 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. " + "To avoid targeting any modules (because you want to apply `target_parameters`), set " + "`target_modules=[]`." + ) + }, + ) + alpha: int = field( + default=64, + metadata={ + "help": ( + "gralora alpha is the scaling factor for the GraLoRA adapter. Scale becomes alpha / (r + hybrid_r). " + ) + }, + ) + gralora_dropout: float = field(default=0.0, metadata={"help": "gralora dropout"}) + gralora_k: int = field( + default=2, + metadata={ + "help": ( + "gralora_k determines the number of subblocks in the GraLoRA adapter. " + "The rank r must be divisible by gralora_k for the GraLoRA adapter to be valid. " + "The total parameter count is preserved regardles of gralora_k. " + "The entire rank of the GraLoRA adapter is increased by gralora_k, while the rank of each subblock is reduced by gralora_k. " + "gralora_k=2 is recommended for rank 32 or lower, and gralora_k=4 is recommended for rank 64 or higher. " + ) + }, + ) + 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: str = field( + default="none", metadata={"help": "Bias type for gralora. Can be 'none', 'all' or 'gralora_only'"} + ) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": ( + "List of modules apart from gralora 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 GraLoRA 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. " + "This only works when target_modules is a list of str." + ) + }, + ) + 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. " + "This only works when target_modules is a list of str. This should target the `nn.ModuleList` of the " + "model, which is often called `'layers'` or `'h'`." + ) + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.GRALORA + self.target_modules = ( + set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules + ) + if self.r % self.gralora_k != 0: + raise ValueError(f"r should be divisible by gralora_k, but got {self.r} and {self.gralora_k}") diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/gralora/layer.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/gralora/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..1064c6b9a12e612e7225950802067fb05ef5bc08 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/gralora/layer.py @@ -0,0 +1,394 @@ +# 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 math +import warnings +from typing import Optional + +import torch +from torch import nn +from transformers.pytorch_utils import Conv1D + +from peft.tuners.tuners_utils import BaseTunerLayer +from peft.utils.other import transpose + +from .config import GraloraConfig + + +class GraloraLayer(BaseTunerLayer): + # List all names of layers that may contain adapter weight + adapter_layer_names = ("gralora_A", "gralora_B", "gralora_A_general", "gralora_B_general") + other_param_names = ("r", "hybrid_r", "alpha", "scaling", "gralora_dropout") + + def __init__(self, base_layer: nn.Module, **kwargs): + self.base_layer = base_layer + self.r = {} + self.alpha = {} + self.gralora_k = {} + self.hybrid_r = {} + self.scaling = {} + self.gralora_dropout = nn.ModuleDict({}) + + self.gralora_A = nn.ParameterDict({}) + self.gralora_B = nn.ParameterDict({}) + self.gralora_A_general = nn.ModuleDict({}) + self.gralora_B_general = nn.ModuleDict({}) + + # 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 + 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 + ) + else: + raise NotImplementedError(f"Unsupported layer type {type(base_layer)}") + + self.in_features = in_features + self.out_features = out_features + self.kwargs = kwargs + + def update_layer( + self, + adapter_name: str, + module_name: str, + r: int, + config: GraloraConfig, + ): + alpha = config.alpha + gralora_dropout = config.gralora_dropout + gralora_k = config.gralora_k + hybrid_r = config.hybrid_r + init_weights = config.init_weights + + if r <= 0: + raise ValueError(f"`r` should be a positive integer value but the value passed is {r}") + elif hybrid_r < 0: + raise ValueError(f"`hybrid_r` should be a non-negative integer value but the value passed is {hybrid_r}") + + self.r[adapter_name] = r + self.alpha[adapter_name] = alpha + self.gralora_k[adapter_name] = gralora_k + self.hybrid_r[adapter_name] = hybrid_r + + if gralora_dropout > 0.0: + gralora_dropout_layer = nn.Dropout(p=gralora_dropout) + else: + gralora_dropout_layer = nn.Identity() + + self.gralora_dropout.update(nn.ModuleDict({adapter_name: gralora_dropout_layer})) + + # Actual trainable parameters + if self.in_features % gralora_k != 0: + raise ValueError( + f"in_features should be divisible by gralora_k, but got {self.in_features} and {gralora_k}" + ) + if self.out_features % gralora_k != 0: + raise ValueError( + f"out_features should be divisible by gralora_k, but got {self.out_features} and {gralora_k}" + ) + subblock_in_features = self.in_features // gralora_k + subblock_out_features = self.out_features // gralora_k + + # gralora_r is the rank allocated to GraLoRA method; hybrid_r is the rank allocated to vanilla LoRA + gralora_r = r + + gralora_A = [] + gralora_B = [] + for _ in range(gralora_k): + new_A = nn.Parameter(torch.empty(gralora_r, subblock_in_features)) + new_B = nn.Parameter(torch.empty(subblock_out_features, gralora_r)) + if init_weights: + # Initialize to identity: A is random, B is zero + nn.init.kaiming_uniform_(new_A, a=math.sqrt(5)) + nn.init.zeros_(new_B) + else: + # Initialize to random: both A and B are random (for testing) + nn.init.kaiming_uniform_(new_A, a=math.sqrt(5)) + nn.init.kaiming_uniform_(new_B, a=math.sqrt(5)) + gralora_A.append(new_A) + gralora_B.append(new_B) + # stack A and B and transpose to get the final shape + gralora_A = torch.stack(tuple(gralora_A), dim=0) # [N, gralora_r, in_features//N] + gralora_A = gralora_A.transpose(1, 2).contiguous() # [N, in_features//N, gralora_r] + + gralora_B = torch.stack(tuple(gralora_B), dim=0) # [N, out_features//N, gralora_r] + gralora_B = gralora_B.transpose(1, 2).contiguous() # [N, gralora_r, out_features//N] + + if hybrid_r > 0: + general_gralora_A = nn.Linear(self.in_features, hybrid_r, bias=False) + general_gralora_B = nn.Linear(hybrid_r, self.out_features, bias=False) + if init_weights: + # Initialize to identity: A is random, B is zero + nn.init.kaiming_uniform_(general_gralora_A.weight, a=math.sqrt(5)) + nn.init.zeros_(general_gralora_B.weight) + else: + # Initialize to random: both A and B are random (for testing) + nn.init.kaiming_uniform_(general_gralora_A.weight, a=math.sqrt(5)) + nn.init.kaiming_uniform_(general_gralora_B.weight, a=math.sqrt(5)) + else: + general_gralora_A = nn.Identity() + general_gralora_B = nn.Identity() + + self.gralora_A[adapter_name] = gralora_A + self.gralora_B[adapter_name] = gralora_B + self.gralora_A_general[adapter_name] = general_gralora_A + self.gralora_B_general[adapter_name] = general_gralora_B + + self.module_name = module_name + + self.scaling[adapter_name] = alpha / (gralora_r + hybrid_r) + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters) + + +class Linear(nn.Linear, GraloraLayer): + # Gralora implemented in a dense layer + def __init__( + self, + base_layer, + adapter_name: str, + module_name, + config: GraloraConfig, + r: int = 0, + **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__() + GraloraLayer.__init__(self, base_layer, **kwargs) + self.fan_in_fan_out = config.fan_in_fan_out + + self._active_adapter = adapter_name + self.update_layer(adapter_name, module_name, r, config=config) + + 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`. + """ + from peft.tuners.tuners_utils import check_adapters_to_merge + + 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.gralora_A.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() + delta_weight = self.get_delta_weight(active_adapter) + orig_weights += delta_weight + + 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: + delta_weight = self.get_delta_weight(active_adapter) + base_layer.weight.data += delta_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 + + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter in self.gralora_A.keys(): + delta_weight = self.get_delta_weight(active_adapter) + self.get_base_layer().weight.data -= delta_weight + + def get_delta_weight(self, adapter) -> torch.Tensor: + """ + Compute the delta weight for GraLoRA adapter. + + GraLoRA applies block-wise low-rank adaptation with information exchange. This method computes the equivalent + weight matrix that would be added to the base weight during merge. + + Args: + adapter (str): The name of the adapter + + Returns: + torch.Tensor: The delta weight matrix with shape [out_features, in_features] + """ + gralora_A = self.gralora_A[adapter] # [N, in_features//N, rank] + gralora_B = self.gralora_B[adapter] # [N, rank, out_features//N] + gralora_A_general = self.gralora_A_general[adapter] + gralora_B_general = self.gralora_B_general[adapter] + + device = gralora_A.device + dtype = gralora_A.dtype + + gralora_k = self.gralora_k[adapter] + hybrid_r = self.hybrid_r[adapter] + r = self.r[adapter] + + # Handle CPU fp16/bf16 casting + cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16) + + if cast_to_fp32: + gralora_A = gralora_A.float() + gralora_B = gralora_B.float() + + # Get dimensions + in_features = self.in_features + out_features = self.out_features + gralora_rank = r + subblock_gralora_rank = gralora_rank // gralora_k + + # scatter gralora_A to get the scattered weight matrix + l_indices = torch.arange(in_features, device=device) + n_indices = l_indices // (in_features // gralora_k) + i_indices = l_indices % (in_features // gralora_k) + gralora_A_scattered = torch.zeros( + in_features, gralora_k, gralora_rank, device=device, dtype=torch.float32 if cast_to_fp32 else dtype + ) + gralora_A_scattered.scatter_( + 1, + n_indices.unsqueeze(1).unsqueeze(2).expand(-1, 1, gralora_rank), + gralora_A[n_indices, i_indices, :].unsqueeze(1), + ) + + # compute the delta weight + delta_weight = ( + torch.einsum( + "ikr, kro -> iko", + gralora_A_scattered.view(in_features, gralora_k, gralora_k, subblock_gralora_rank) + .permute(0, 2, 1, 3) + .reshape(in_features, gralora_k, gralora_rank), + gralora_B, + ) + .reshape(in_features, out_features) + .T + ) + + # Add hybrid LoRA component if present + if hybrid_r > 0: + weight_A_general = gralora_A_general.weight # [hybrid_r, in_features] + weight_B_general = gralora_B_general.weight # [out_features, hybrid_r] + + if cast_to_fp32: + weight_A_general = weight_A_general.float() + weight_B_general = weight_B_general.float() + + # Compute delta for hybrid part: [out_features, hybrid_r] @ [hybrid_r, in_features] + delta_weight += weight_B_general @ weight_A_general + + # Apply scaling and transpose if needed + delta_weight = transpose(delta_weight, self.fan_in_fan_out) * self.scaling[adapter] + + # Cast back if needed + if cast_to_fp32: + delta_weight = delta_weight.to(dtype=dtype) + + return delta_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: + result = self.base_layer(x, *args, **kwargs) + torch_result_dtype = result.dtype + + # Handle 2D input: [batch, features] -> [batch, 1, features] + # This is common for MLPs and other non-sequence models + x_is_2d = x.ndim == 2 + if x_is_2d: + x = x.unsqueeze(1) # [B, F] -> [B, 1, F] + + for active_adapter in self.active_adapters: + if active_adapter not in self.gralora_A.keys(): + continue + gralora_A = self.gralora_A[active_adapter] + gralora_B = self.gralora_B[active_adapter] + + gralora_A_general = self.gralora_A_general[active_adapter] + gralora_B_general = self.gralora_B_general[active_adapter] + + r = self.r[active_adapter] + gralora_rank = r + gralora_k = self.gralora_k[active_adapter] + hybrid_r = self.hybrid_r[active_adapter] + + dropout = self.gralora_dropout[active_adapter] + scaling = self.scaling[active_adapter] + + gralora_dtype = gralora_A.dtype + + B, L, in_features = x.shape + N = gralora_k + subblock_gralora_rank = gralora_rank // N + + output = torch.einsum( + "bljr, jro -> bljo", + torch.einsum( + "blni, nir -> blnr", + dropout(x.to(gralora_dtype)).view(B, L, N, in_features // N), + gralora_A, + ) + .view(B, L, N, N, subblock_gralora_rank) + .permute(0, 1, 3, 2, 4) + .reshape(B, L, N, N * subblock_gralora_rank), + gralora_B, + ).reshape(B, L, -1) + + # Squeeze back to 2D if input was 2D + if x_is_2d: + output = output.squeeze(1) # [B, 1, F] -> [B, F] + + result += scaling * output.to(torch_result_dtype) + if hybrid_r > 0: + hybrid_output = gralora_B_general(gralora_A_general(dropout(x.to(gralora_dtype)))) + if x_is_2d: + hybrid_output = hybrid_output.squeeze(1) + result += scaling * hybrid_output.to(torch_result_dtype) + + 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 "gralora." + rep diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/gralora/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/gralora/model.py new file mode 100644 index 0000000000000000000000000000000000000000..c371268c3006717077bfda7d0ecf0c078d799df9 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/gralora/model.py @@ -0,0 +1,125 @@ +# 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 transformers.pytorch_utils import Conv1D + +from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer +from peft.utils import TRANSFORMERS_MODELS_TO_GRALORA_TARGET_MODULES_MAPPING + +from .layer import GraloraLayer, Linear + + +class GraloraModel(BaseTuner): + """ + Creates Vector-based Random Matrix Adaptation (Gralora) model from a pretrained transformers model. + + Args: + model ([`~transformers.PreTrainedModel`]): The model to be adapted. + config ([`GraloraConfig`]): The configuration of the Gralora model. + adapter_name (`str`): The name of the adapter, defaults to `"default"`. + + Returns: + `torch.nn.Module`: The Gralora model. + + Example: + + ```py + >>> from transformers import AutoModelForCausalLM + >>> from peft import GraloraConfig, get_peft_model + + >>> base_model = AutoModelForCausalLM.from_pretrained("facebook/opt-125m") + >>> config = GraloraConfig(r=128) + >>> model = get_peft_model(base_model, config) + ``` + + **Attributes**: + - **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted. + - **peft_config** ([`GraloraConfig`]): The configuration of the Gralora model. + """ + + # The unique prefix for GraLoRA method + prefix: str = "gralora_" + # The class of tuner layer for GraLoRA method + tuner_layer_cls = GraloraLayer + + target_module_mapping = TRANSFORMERS_MODELS_TO_GRALORA_TARGET_MODULES_MAPPING + + def _create_and_replace( + self, + gralora_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 = gralora_config.r + if isinstance(target, Linear): + target.update_layer( + adapter_name, + current_key, + r=r, + config=gralora_config, + ) + else: + new_module = self._create_new_module(gralora_config, adapter_name, target, current_key, r=r) + 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(gralora_config, adapter_name, target, module_name, **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): + if gralora_config.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." + ) + gralora_config.fan_in_fan_out = False + elif isinstance(target_base_layer, Conv1D): + kwargs["is_target_conv_1d_layer"] = True + if not gralora_config.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." + ) + gralora_config.fan_in_fan_out = True + else: + raise TypeError( + 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, + adapter_name, + module_name, + config=gralora_config, + **kwargs, + ) + + return new_module diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/hira/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/hira/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5f2b5a6171e6571e0bd653daa1798322818ddcf9 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/hira/__init__.py @@ -0,0 +1,45 @@ +# 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 HiraConfig +from .layer import Conv2d, Conv3d, Embedding, HiraLayer, Linear +from .model import HiraModel + + +__all__ = [ + "Conv2d", + "Conv3d", + "Embedding", + "HiraConfig", + "HiraLayer", + "HiraModel", + "Linear", +] + +register_peft_method(name="hira", config_cls=HiraConfig, model_cls=HiraModel, is_mixed_compatible=True) + + +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 diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/hira/bnb.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/hira/bnb.py new file mode 100644 index 0000000000000000000000000000000000000000..51c1521859a906c9aa80e8bdea3e2d019d709a9d --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/hira/bnb.py @@ -0,0 +1,471 @@ +# 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 Any, Optional + +import bitsandbytes as bnb +import torch +import torch.nn.functional as F + +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 HiraConfig +from .layer import HiraLayer + + +if is_bnb_available(): + + class Linear8bitLt(torch.nn.Module, HiraLayer): + # HiRA implemented in a dense layer + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + config: HiraConfig, + r: int = 0, + **kwargs, + ) -> None: + super().__init__() + HiraLayer.__init__(self, base_layer) + self.fan_in_fan_out = False + + self._active_adapter = adapter_name + self.update_layer(adapter_name, r, config=config) + + 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.hira_A.keys(): + continue + + warnings.warn( + "Merge hira 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) + hira_data = self.get_delta_weight(active_adapter) + hira_data = output.to(hira_data.dtype).to(hira_data.device) * hira_data + w_data = output.to(hira_data.dtype).to(hira_data.device) + hira_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.hira_A.keys(): + continue + warnings.warn( + "Unmerge hira 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) + + hira_data = self.get_delta_weight(active_adapter) + w_data = output.to(hira_data.dtype).to(hira_data.device) / (1 + hira_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_delta_weight(self, adapter): + return transpose( + self.hira_B[adapter] @ self.hira_A[adapter], + False, + ) + + 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]) + + # dequantitize + 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 + dequant_w = dequantize_bnb_weight(weight, state=state) + for i, active_adapter in enumerate(unique_adapters): + if active_adapter == "__base__": + continue + if active_adapter not in self.hira_A.keys(): + continue + + hira_A = self.hira_A[active_adapter] + hira_B = self.hira_B[active_adapter] + dropout = self.hira_dropout[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + x = self._cast_input_dtype(x, hira_A.dtype) + + # getting the sub-batch, passing it to HiRA layers and updating the corresponding indices of the linear + # layer output + sub_batch = x[sub_batch_indices_list[i]] + sub_batch = dropout(sub_batch) + prod_AB = torch.mm(hira_A.T, hira_B.T) + + eff_weight = transpose(dequant_w.to(prod_AB.dtype).to(prod_AB.device), self.fan_in_fan_out) * prod_AB.T + hira_out = F.linear(sub_batch, eff_weight) + if requires_conversion: + hira_out = hira_out.to(expected_dtype) + result[sub_batch_indices_list[i]] += hira_out + + return result + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + 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: + # 2) now compute the HiRA “delta” in float32 and add it: + # dequantize once per forward + raw_weight = self.get_base_layer().weight + state = self.get_base_layer().state + dequant_w = dequantize_bnb_weight(raw_weight, state=state) # float32 tensor [out, in] + result = self.base_layer(x, *args, **kwargs) + for active_adapter in self.active_adapters: + if active_adapter not in self.hira_A.keys(): + continue + hira_A = self.hira_A[active_adapter] + hira_B = self.hira_B[active_adapter] + dropout = self.hira_dropout[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + x = self._cast_input_dtype(x, hira_A.dtype) + dropout_sub = dropout(x) + # compute Δ = B @ A → shape (out, in) + prod_AB = hira_B @ hira_A + # effective weight = W₀ ⊙ Δ + eff_w = dequant_w * prod_AB + hira_out = F.linear(dropout_sub, eff_w) + if requires_conversion: + hira_out = hira_out.to(expected_dtype) + result = result + hira_out + if requires_conversion: + result = result.to(expected_dtype) + + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "hira." + rep + + def dispatch_bnb_8bit(target: torch.nn.Module, adapter_name: str, hira_config, **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=hira_config, **eightbit_kwargs) + + return new_module + + +if is_bnb_4bit_available(): + + class Linear4bit(torch.nn.Module, HiraLayer): + # HiRA implemented in a dense layer + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + config: HiraConfig, + r: int = 0, + **kwargs, + ) -> None: + super().__init__() + HiraLayer.__init__(self, base_layer) + self.fan_in_fan_out = False + + self._active_adapter = adapter_name + self.update_layer(adapter_name, r, config=config) + + 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.hira_A.keys(): + continue + + warnings.warn( + "Merge hira 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) + hira_data = self.get_delta_weight(active_adapter) + w_data = output * (1 + hira_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" + ) + + 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.hira_A.keys(): + continue + warnings.warn( + "Unmerge hira 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) + + hira_data = self.get_delta_weight(active_adapter) + w_data = output / (1 + hira_data) + + 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 transpose( + self.hira_B[adapter] @ self.hira_A[adapter], + False, + ) + + 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]) + weight = self.get_base_layer().weight + dequant_w = dequantize_bnb_weight(weight, state=weight.quant_state) + for i, active_adapter in enumerate(unique_adapters): + if active_adapter == "__base__": + continue + if active_adapter not in self.hira_A.keys(): + continue + + hira_A = self.hira_A[active_adapter] + hira_B = self.hira_B[active_adapter] + dropout = self.hira_dropout[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + x = self._cast_input_dtype(x, hira_A.dtype) + + # getting the sub-batch, passing it to HiRA layers and updating the corresponding indices of the linear + # layer output + sub_batch = x[sub_batch_indices_list[i]] + prod_AB = torch.mm(hira_A.T, hira_B.T) + sub_batch = dropout(sub_batch) + eff_weight = transpose(dequant_w.to(prod_AB.dtype).to(prod_AB.device), self.fan_in_fan_out) * prod_AB.T + hira_out = F.linear(sub_batch, eff_weight) + if requires_conversion: + hira_out = hira_out.to(expected_dtype) + result[sub_batch_indices_list[i]] += hira_out + + return result + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + 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) + # 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() + # dequanted w + weight = self.get_base_layer().weight + dequant_w = dequantize_bnb_weight(weight, state=weight.quant_state) + for active_adapter in self.active_adapters: + if active_adapter not in self.hira_A.keys(): + continue + hira_A = self.hira_A[active_adapter] + hira_B = self.hira_B[active_adapter] + dropout = self.hira_dropout[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + x = self._cast_input_dtype(x, hira_A.dtype) + + dropout_sub = dropout(x) + # compute Δ = B @ A → shape (out, in) + prod_AB = hira_B @ hira_A + # effective weight = W₀ ⊙ Δ + eff_w = dequant_w * prod_AB + hira_out = F.linear(dropout_sub, eff_w) + if requires_conversion: + hira_out = hira_out.to(expected_dtype) + result = result + hira_out + if requires_conversion: + result = result.to(expected_dtype) + + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "hira." + rep + + def dispatch_bnb_4bit(target: torch.nn.Module, adapter_name: str, hira_config, **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=hira_config, **fourbit_kwargs) + + return new_module diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/hira/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/hira/config.py new file mode 100644 index 0000000000000000000000000000000000000000..6ad9027fa9982d337f865f0ce4ce7a685577c9d7 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/hira/config.py @@ -0,0 +1,151 @@ +# 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 Literal, Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class HiraConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`HiraModel`]. + + Args: + r (`int`): + Rank of the low-rank component in HiRA. Although HiRA achieves a high-rank adaptation through Hadamard + fusion, this value defines the dimension of the underlying low-rank factorization (matrices A and B). + 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/Conv1D modules are chosen (if + the model is a PreTrainedModel, the output layer excluded). 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. + 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. + hira_dropout (`float`): + The dropout probability for HiRA layers. + 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`. + modules_to_save (`List[str]`): + List of modules apart from adapter layers to be set as trainable and saved in the final checkpoint. + 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'`. + rank_pattern (`dict`): + The mapping from layer names or regexp expression to ranks which are different from the default r specified + by `r`. For example, `{'^model.decoder.layers.0.encoder_attn.k_proj': 16}`. + """ + + r: int = field(default=32, metadata={"help": "HiRA intermediate r configuration"}) + 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 HiRA." + "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'." + "This can also be a wildcard 'all-linear' which matches all linear/Conv1D " + "(if the model is a PreTrainedModel, the output layer excluded)." + "If 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." + ), + }, + ) + 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 HiRA."}, + ) + hira_dropout: float = field(default=0.0, metadata={"help": "HiRA dropout"}) + 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)"}, + ) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": "List of modules apart from HiRA 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 | Literal["gaussian"] | None = field( + default=True, + metadata={ + "help": ( + "How to initialize the weights of the HiRA layers. " + "Passing True (default) results in the default initialization" + ", with the HiRA B weight being set to 0. This means that without further training, the HiRA " + "adapter will be a no-op. " + "Setting the initialization to False leads to random initialization of HiRA A and B, meaning that HiRA " + "is not a no-op before training; this setting is intended for debugging purposes. " + "Passing `'gaussian'` results in Gaussian initialization scaled by the HiRA rank for linear and layers. " + ), + }, + repr=False, + ) + 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. " + "This only works when target_modules is a list of str." + }, + ) + 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 only works when target_modules is a list of str. This should target the `nn.ModuleList` of the " + "model, which is often called `'layers'` or `'h'`." + }, + ) + rank_pattern: Optional[dict] = field( + default_factory=dict, + metadata={ + "help": ( + "The mapping from layer names or regexp expression to rank of AB which are different from the default rank specified by `rank` of AB. " + "For example, `{'^model.decoder.layers.0.encoder_attn.k_proj': 16}`." + ) + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.HIRA + 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 + ) + + # if target_modules is a regex expression, then layers_to_transform should be None + if isinstance(self.target_modules, str) and self.layers_to_transform is not None: + raise ValueError("`layers_to_transform` cannot be used when `target_modules` is a str.") + + # if target_modules is a regex expression, then layers_pattern should be None + if isinstance(self.target_modules, str) and self.layers_pattern is not None: + raise ValueError("`layers_pattern` cannot be used when `target_modules` is a str.") diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/hira/layer.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/hira/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..34efe03634588f4ab6d6f5ce2a8467ebe28619a9 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/hira/layer.py @@ -0,0 +1,789 @@ +# 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 Any, Optional + +import torch +import torch.nn.functional as F +from torch import nn +from transformers.pytorch_utils import Conv1D + +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge +from peft.utils.other import transpose + +from .config import HiraConfig + + +class HiraLayer(BaseTunerLayer): + # All names of layers that may contain (trainable) adapter weights + adapter_layer_names: tuple[str, ...] = ("hira_A", "hira_B", "hira_embedding_A", "hira_embedding_B") + # All names of other parameters that may contain adapter-related parameters + other_param_names: tuple[str, ...] = ("r", "hira_dropout") + + def __init__(self, base_layer: nn.Module, ephemeral_gpu_offload: bool = False, **kwargs) -> None: + self.base_layer = base_layer + self.r = {} + self.hira_dropout = nn.ModuleDict({}) + self.hira_A = nn.ParameterDict({}) + self.hira_B = nn.ParameterDict({}) + # For Embedding layer + self.hira_embedding_A = nn.ParameterDict({}) + self.hira_embedding_B = nn.ParameterDict({}) + # Mark the weight as unmerged + self._disable_adapters = False + self.merged_adapters = [] + self._caches: dict[str, Any] = {} + self.ephemeral_gpu_offload: bool = ephemeral_gpu_offload + # flag to enable/disable casting of input to weight dtype during forward call + self.cast_input_dtype_enabled: bool = 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.Conv1d, nn.Conv2d, nn.Conv3d)): + in_features, out_features = base_layer.in_channels, base_layer.out_channels + elif isinstance(base_layer, nn.Embedding): + in_features, out_features = base_layer.num_embeddings, base_layer.embedding_dim + 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 + ) + 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 update_layer( + self, + adapter_name, + r, + config: HiraConfig, + **kwargs, + ): + # This code works for linear layers, override for other layer types + if r <= 0: + raise ValueError(f"`r` should be a positive integer value but the value passed is {r}") + + hira_dropout = config.hira_dropout + init_weights = config.init_weights + + self.r[adapter_name] = r + if hira_dropout > 0.0: + hira_dropout_layer = nn.Dropout(p=hira_dropout) + else: + hira_dropout_layer = nn.Identity() + + self.hira_dropout.update(nn.ModuleDict({adapter_name: hira_dropout_layer})) + # Actual trainable parameters + self.hira_A.update(nn.ParameterDict({adapter_name: nn.Parameter(torch.randn(r, self.in_features))})) + self.hira_B.update(nn.ParameterDict({adapter_name: nn.Parameter(torch.randn(self.out_features, r))})) + + # for inits that require access to the base weight, use gather_param_ctx so that the weight is gathered when using DeepSpeed + if init_weights: + self.reset_hira_parameters(adapter_name, init_weights) + self._move_adapter_to_device_of_base_layer(adapter_name) + + self.set_adapter(self.active_adapters) + + def reset_hira_parameters(self, adapter_name, init_weights): + if init_weights is False: + return + + if adapter_name in self.hira_A.keys(): + if init_weights is True: + # initialize A the same way as the default for nn.Linear and B to zero + nn.init.kaiming_uniform_(self.hira_A[adapter_name], a=math.sqrt(5)) + elif init_weights.lower() == "gaussian": + nn.init.normal_(self.hira_A[adapter_name], std=1 / self.r[adapter_name]) + else: + raise ValueError(f"Unknown initialization {init_weights=}") + nn.init.zeros_(self.hira_B[adapter_name]) + if adapter_name in self.hira_embedding_A.keys(): + # Initialize A to zeros and B the same way as the default for nn.Embedding, see: + nn.init.zeros_(self.hira_embedding_A[adapter_name]) + nn.init.normal_(self.hira_embedding_B[adapter_name]) + + +class Linear(nn.Module, HiraLayer): + # HiRA implemented in a dense layer + def __init__( + self, + base_layer, + adapter_name: str, + config: HiraConfig, + r: int = 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, + **kwargs, + ) -> None: + super().__init__() + HiraLayer.__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, config=config) + 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 + + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.data.dtype + + merged_delta = torch.zeros_like(base_layer.weight.data, dtype=orig_dtype) + for active_adapter in adapter_names: + if active_adapter in self.hira_A.keys(): + merged_delta = merged_delta + self.get_delta_weight(active_adapter).to(orig_dtype) + self.merged_adapters.append(active_adapter) + + if safe_merge: + orig_weight = base_layer.weight.data.clone() + merged_weight = orig_weight * (1 + merged_delta) + + if not torch.isfinite(merged_weight).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {','.join(adapter_names)} seems to be broken" + ) + + base_layer.weight.data = merged_weight + else: + base_layer.weight.data *= 1 + merged_delta + + 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 + weight = self.get_base_layer().weight + orig_dtype = weight.dtype + merged_delta = torch.zeros_like(weight.data, dtype=torch.float32) + + for active_adapter in self.merged_adapters: + if active_adapter in self.hira_A.keys(): + merged_delta = merged_delta + self.get_delta_weight(active_adapter).to(torch.float32) + + # avoid NaN error, cast to fp32 + w32 = weight.data.to(torch.float32) + den32 = 1 + merged_delta + tiny = torch.finfo(den32.dtype).tiny # ~1e-45 for float32 + den32 = torch.where(den32 == 0, tiny, den32) + w32 = w32 / den32 + weight.data.copy_(w32.to(orig_dtype)) + + self.merged_adapters.clear() + + 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.hira_B[adapter].device + dtype = self.hira_B[adapter].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) + + weight_A = self.hira_A[adapter] + weight_B = self.hira_B[adapter] + + if cast_to_fp32: + weight_A = weight_A.float() + weight_B = weight_B.float() + output_tensor = transpose((weight_B @ weight_A), self.fan_in_fan_out) + if cast_to_fp32: + output_tensor = output_tensor.to(dtype=dtype) + + # cast back the weights + self.hira_A[adapter].data = weight_A.to(dtype) + self.hira_B[adapter].data = weight_B.to(dtype) + + return output_tensor + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> 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) + torch_result_dtype = result.dtype + + hira_A_keys = self.hira_A.keys() + for active_adapter in self.active_adapters: + if active_adapter not in hira_A_keys: + continue + hira_A = self.hira_A[active_adapter] + hira_B = self.hira_B[active_adapter] + _prod_AB = torch.mm(hira_A.T, hira_B.T) + x = self._cast_input_dtype(x, hira_A.dtype) + dropout = self.hira_dropout[active_adapter] + dropout_sub = dropout(x) + hira_result = F.linear( + dropout_sub, transpose(self.get_base_layer().weight, self.fan_in_fan_out) * _prod_AB.T + ) + result = result + hira_result + + result = result.to(torch_result_dtype) + + return result + + def supports_lora_conversion(self, adapter_name: str = "default") -> bool: + # The generic LoRA conversion path only works for additive adapters, i.e. adapters that can be written as + # W' = W + Delta and expose that additive residual via get_delta_weight(). HiRA is different: its effective + # update is multiplicative, W' = W * (1 + Delta_hira), so the actual additive residual would be + # W * Delta_hira and depends on the current base weight. Returning Delta_hira from get_delta_weight() is + # sufficient for HiRA merge/unmerge, but it is not the quantity that the generic LoRA converter factorizes. + # Mark conversion as unsupported to avoid producing a LoRA adapter that does not preserve HiRA behavior. + return False + + def __repr__(self) -> str: + rep = super().__repr__() + return "hira." + rep + + +class Embedding(nn.Module, HiraLayer): + # HiRA implemented in a Embedding layer + def __init__( + self, + base_layer: nn.Module, + adapter_name: str, + config: HiraConfig, + r: int = 0, + fan_in_fan_out: bool = False, # Set this to True if the layer to replace stores weight like (fan_in, fan_out) + **kwargs, + ) -> None: + super().__init__() + HiraLayer.__init__(self, base_layer) + self.fan_in_fan_out = fan_in_fan_out + + self._active_adapter = adapter_name + self.update_layer(adapter_name, r, config=config) + + def update_layer(self, adapter_name, r, config: HiraConfig, **kwargs) -> None: + if r <= 0: + raise ValueError(f"`r` should be a positive integer value but the value passed is {r}") + + hira_dropout = config.hira_dropout + init_weights = config.init_weights + + self.r[adapter_name] = r + if hira_dropout > 0.0: + hira_dropout_layer = nn.Dropout(p=hira_dropout) + else: + hira_dropout_layer = nn.Identity() + + self.hira_dropout[adapter_name] = hira_dropout_layer + # Actual trainable parameters + weight_A = torch.randn((r, self.in_features)) + weight_B = torch.randn((self.out_features, r)) + self.hira_embedding_A[adapter_name] = nn.Parameter(weight_A) + self.hira_embedding_B[adapter_name] = nn.Parameter(weight_B) + self.reset_hira_parameters(adapter_name, init_weights) + + # call this before init of the hira variants + self._move_adapter_to_device_of_base_layer(adapter_name) + + self.set_adapter(self.active_adapters) + + 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 + + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.dtype + merged_delta = torch.zeros_like(base_layer.weight.data, dtype=orig_dtype) + + for active_adapter in adapter_names: + if active_adapter in self.hira_embedding_A.keys(): + merged_delta = merged_delta + self.get_delta_weight(active_adapter).to(orig_dtype) + self.merged_adapters.append(active_adapter) + + if safe_merge: + orig_weight = base_layer.weight.data.clone() + merged_weight = orig_weight * (1 + merged_delta) + if not torch.isfinite(merged_weight).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {','.join(adapter_names)} seems to be broken" + ) + base_layer.weight.data = merged_weight + else: + base_layer.weight.data *= 1 + merged_delta + + 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 + weight = self.get_base_layer().weight + orig_dtype = weight.dtype + merged_delta = torch.zeros_like(weight.data, dtype=torch.float32) + + for active_adapter in self.merged_adapters: + if active_adapter in self.hira_embedding_A.keys(): + merged_delta = merged_delta + self.get_delta_weight(active_adapter).to(torch.float32) + + w32 = weight.data.to(torch.float32) + den32 = 1 + merged_delta + tiny = torch.finfo(den32.dtype).tiny # ~1e-45 for float32 + den32 = torch.where(den32 == 0, tiny, den32) + w32 = w32 / den32 + weight.data.copy_(w32.to(orig_dtype)) + + self.merged_adapters.clear() + + 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.hira_embedding_B[adapter].device + dtype = self.hira_embedding_A[adapter].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) + + weight_A = self.hira_embedding_A[adapter] + weight_B = self.hira_embedding_B[adapter] + + if cast_to_fp32: + weight_A = weight_A.float() + weight_B = weight_B.float() + output_tensor = transpose(weight_B @ weight_A, True) + + if cast_to_fp32: + output_tensor = output_tensor.to(dtype=dtype) + + # cast back the weights + self.hira_embedding_A[adapter].data = weight_A.to(dtype) + self.hira_embedding_B[adapter].data = weight_B.to(dtype) + + return output_tensor + + 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: + """ + HiRA forward for Embedding layer. Supports mixed adapters per batch or single adapter. + """ + + # Adapter disabled or after merge: use base embedding + 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) + + # Single adapter active: compute base embedding + HiRA residual + result = self.base_layer(x, *args, **kwargs) + torch_result_dtype = result.dtype + base_weight = self.get_base_layer().weight # (num_embeddings, embedding_dim) + + for adapter in self.active_adapters: + if adapter not in self.hira_embedding_A: + continue + # HiRA factors + hira_A = self.hira_embedding_A[adapter] # (r, num_embeddings) + hira_B = self.hira_embedding_B[adapter] # (embedding_dim, r) + + # Compute modulation matrix: B @ A -> (embedding_dim, num_embeddings) + mod_matrix = torch.mm(hira_B, hira_A) + # Element-wise modulated embedding weight + eff_weight = base_weight * mod_matrix.T # (num_embeddings, embedding_dim) + + # Compute HiRA residual via embedding lookup + hira_out = F.embedding(x, eff_weight) + result = result + hira_out + + return result.to(torch_result_dtype) + + def __repr__(self) -> str: + rep = super().__repr__() + return "hira." + rep + + +class _ConvNd(nn.Module, HiraLayer): + # HiRA implemented in a conv(2,3)d layer + def __init__( + self, + base_layer: nn.Module, + adapter_name: str, + config: HiraConfig, + r: int = 0, + **kwargs, + ) -> None: + super().__init__() + HiraLayer.__init__(self, base_layer) + + if base_layer.groups > 1: + warnings.warn("HiRA adapter added to ConvNd layer with groups > 1. Merging is not supported.") + + self._active_adapter = adapter_name + self._kernel_dim = base_layer.weight.dim() + + self.update_layer(adapter_name, r, config=config) + + def update_layer(self, adapter_name, r, config: HiraConfig, **kwargs): + if r <= 0: + raise ValueError(f"`r` should be a positive integer value but the value passed is {r}") + + hira_dropout = config.hira_dropout + init_weights = config.init_weights + + self.r[adapter_name] = r + if hira_dropout > 0.0: + hira_dropout_layer = nn.Dropout(p=hira_dropout) + else: + hira_dropout_layer = nn.Identity() + + self.hira_dropout[adapter_name] = hira_dropout_layer + # Determine base conv parameters + base = self.get_base_layer() + conv_cls = type(base) + in_channels = base.in_channels + out_channels = base.out_channels + kernel_size = base.kernel_size + stride = base.stride + padding = base.padding + dilation = getattr(base, "dilation", (1,) * (base.weight.dim() - 2)) + groups = getattr(base, "groups", 1) + # Spatial dims for B: 1 in each spatial dimension + spatial_ones = (1,) * (base.weight.dim() - 2) + + # HiRA factor A: conv from in_channels to r + weight_shape_A = (r, in_channels, *kernel_size) + weight_shape_B = (out_channels, r, *spatial_ones) + + self.hira_A[adapter_name] = nn.Parameter(torch.randn(weight_shape_A)) + self.hira_B[adapter_name] = nn.Parameter(torch.randn(weight_shape_B)) + + # Initialize HiRA parameters (A with Kaiming, B zeros) + if init_weights: + # A: same init as base conv weight + nn.init.kaiming_uniform_(self.hira_A[adapter_name], a=math.sqrt(5)) + # B: initialize to zero + nn.init.zeros_(self.hira_B[adapter_name]) + + # Place adapters on correct device and register + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights inside 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 + + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.dtype + + if base_layer.groups > 1: + # https://github.com/huggingface/peft/pull/2403 + raise NotImplementedError("Merging is not supported for _ConvNd layers with groups > 1!") + + merged_delta = torch.zeros_like(base_layer.weight.data, dtype=orig_dtype) + + for active_adapter in adapter_names: + if active_adapter in self.hira_A.keys(): + merged_delta = merged_delta + self.get_delta_weight(active_adapter).to(orig_dtype) + self.merged_adapters.append(active_adapter) + + if safe_merge: + orig_weight = base_layer.weight.data.clone() + merged_weight = orig_weight * (1 + merged_delta) + + if not torch.isfinite(merged_weight).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {','.join(adapter_names)} seems to be broken" + ) + + base_layer.weight.data = merged_weight + + else: + base_layer.weight.data *= 1 + merged_delta.to(orig_dtype) + + 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 + weight = self.get_base_layer().weight + orig_dtype = weight.dtype + merged_delta = torch.zeros_like(weight.data, dtype=torch.float32) + + for active_adapter in self.merged_adapters: + if active_adapter in self.hira_A.keys(): + merged_delta = merged_delta + self.get_delta_weight(active_adapter).to(torch.float32) + + w32 = weight.data.to(torch.float32) + den32 = 1 + merged_delta + tiny = torch.finfo(den32.dtype).tiny # ~1e-45 for float32 + den32 = torch.where(den32 == 0, tiny, den32) + w32 = w32 / den32 + weight.data.copy_(w32.to(orig_dtype)) + + self.merged_adapters.clear() + + 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.hira_B[adapter].device + dtype = self.hira_A[adapter].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) + + weight_A = self.hira_A[adapter] + weight_B = self.hira_B[adapter] + + if cast_to_fp32: + weight_A = weight_A.float() + weight_B = weight_B.float() + + if self.get_base_layer().weight.size()[2:4] == (1, 1): + # conv2d 1x1 + output_tensor = (weight_B.squeeze(3).squeeze(2) @ weight_A.squeeze(3).squeeze(2)).unsqueeze(2).unsqueeze(3) + else: + output_tensor = self.conv_fn(weight_A.transpose(0, 1), weight_B) + + if self.get_base_layer().groups <= 1: + output_tensor = output_tensor.transpose(0, 1) + + if cast_to_fp32: + output_tensor = output_tensor.to(dtype=dtype) + + # cast back the weights + self.hira_A[adapter].data = weight_A.to(dtype) + self.hira_B[adapter].data = weight_B.to(dtype) + + return output_tensor + + 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) + torch_result_dtype = result.dtype + base = self.get_base_layer() + # Determine which convolution function to use + if isinstance(base, nn.Conv1d): + conv_fn = F.conv1d + elif isinstance(base, nn.Conv2d): + conv_fn = F.conv2d + elif isinstance(base, nn.Conv3d): + conv_fn = F.conv3d + else: + raise TypeError(f"Unsupported conv layer {type(base)} for HiRA.") + for active_adapter in self.active_adapters: + if active_adapter not in self.hira_A.keys(): + continue + hira_A = self.hira_A[active_adapter] + dropout = self.hira_dropout[active_adapter] + x = self._cast_input_dtype(x, hira_A.dtype) + x_in = self._cast_input_dtype(x, hira_A.dtype) + x_drop = dropout(x_in) + # low-rank factor B@A + bia = self.get_delta_weight(active_adapter) # now returns (B@A) tensor + # element-wise modulate base weight: W0 ⊙ (B@A) + base_weight = base.weight + eff_weight = base_weight * bia + hira_out = conv_fn( + x_drop, + eff_weight, + bias=None, + stride=base.stride, + padding=base.padding, + dilation=getattr(base, "dilation", 1), + groups=base.groups, + ) + result = result + hira_out + + result = result.to(torch_result_dtype) + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "hira." + rep + + +class Conv2d(_ConvNd): + # HiRA implemented in a conv2d layer + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + if not self._kernel_dim == 4: + raise ValueError(f"Conv2d layer kernel must have 4 dimensions, not {self._kernel_dim}") + self.conv_fn = F.conv2d + + +class Conv1d(_ConvNd): + # HiRA implemented in a conv1d layer + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + if not self._kernel_dim == 3: + raise ValueError(f"Conv1d layer kernel must have 3 dimensions, not {self._kernel_dim}") + self.conv_fn = F.conv1d + + +class Conv3d(_ConvNd): + # HiRA implemented in a conv3d layer + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + if not self._kernel_dim == 5: + raise ValueError(f"Conv3d layer kernel must have 5 dimensions, not {self._kernel_dim}") + self.conv_fn = F.conv3d + + +def dispatch_default( + target: torch.nn.Module, + adapter_name: str, + hira_config: HiraConfig, + **kwargs, +) -> Optional[torch.nn.Module]: + """ + Dispatch function for HiRA adapters that avoids LoFT-Q related config. + """ + # Determine the base module (unwrap BaseTunerLayer) + if isinstance(target, BaseTunerLayer): + base = target.get_base_layer() + else: + base = target + + r = hira_config.r + fan_in_fan_out = hira_config.fan_in_fan_out + + new_module = None + # Embedding + if isinstance(base, nn.Embedding): + new_module = Embedding(target, adapter_name, config=hira_config, r=r) + # Conv layers + elif isinstance(base, nn.Conv2d): + new_module = Conv2d(target, adapter_name, config=hira_config, r=r) + elif isinstance(base, nn.Conv3d): + new_module = Conv3d(target, adapter_name, config=hira_config, r=r) + elif isinstance(base, nn.Conv1d): + new_module = Conv1d(target, adapter_name, config=hira_config, r=r) + # Linear layers + elif isinstance(base, nn.Linear): + # Linear always uses fan_in_fan_out=False + 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." + ) + new_module = Linear(target, adapter_name, config=hira_config, r=r, fan_in_fan_out=False) + # HuggingFace Conv1D + elif isinstance(base, Conv1D): + # Conv1D expects fan_in_fan_out=True + if not 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." + ) + new_module = Linear( + target, adapter_name, config=hira_config, r=r, fan_in_fan_out=True, is_target_conv_1d_layer=True + ) + + return new_module diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/hira/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/hira/model.py new file mode 100644 index 0000000000000000000000000000000000000000..3c4a3a719d43a35e0d87364bf8f7dbde4f5bbcd3 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/hira/model.py @@ -0,0 +1,225 @@ +# 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 operator + +import torch +from torch import nn + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available +from peft.tuners.tuners_utils import BaseTuner +from peft.utils.other import get_pattern_key + +from ...utils.constants import TRANSFORMERS_MODELS_TO_HIRA_TARGET_MODULES_MAPPING +from .config import HiraConfig +from .layer import HiraLayer, dispatch_default + + +def _adapter_names_pre_forward_hook(target, args, kwargs, adapter_names): + # pre-forward hook to inject the adapter_names argument when using mixed adapter batches inference + kwargs["adapter_names"] = adapter_names + return args, kwargs + + +def _get_encoder(model: nn.Module) -> nn.Module | None: + """Check if the model has an encoder and if it has, returns it; otherwise returns None""" + if not hasattr(model, "get_encoder"): + return None + + encoder = model.get_encoder() + # https://github.com/huggingface/transformers/pull/42156 + # new logic in transformers v5: all PretrainedModels return a model here, but it is self if there is no encoder + if encoder is model: + return None + return encoder + + +class HiraModel(BaseTuner): + """ + Creates HiRA Adapter model from a pretrained transformers model. + + The method is described in detail in https://openreview.net/pdf?id=TwJrTz9cRS. + + Args: + model ([`torch.nn.Module`]): The model to be adapted. + config ([`LoraConfig`]): The configuration of the Lora 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 Lora model. + + Example: + + ```py + >>> from transformers import AutoModelForSeq2SeqLM + >>> from peft import HiraModel, HiraConfig + + >>> config = HiraConfig( + ... task_type="SEQ_2_SEQ_LM", + ... r=32, + ... target_modules=["q", "v"], + ... hira_dropout=0.01, + ... ) + + >>> model = AutoModelForSeq2SeqLM.from_pretrained("t5-base") + >>> hira_model = HiraModel(model, config, "default") + ``` + + ```py + >>> import torch + >>> import transformers + >>> from peft import HiraConfig, PeftModel, get_peft_model, prepare_model_for_kbit_training + + >>> rank = ... + >>> target_modules = ["q_proj", "k_proj", "v_proj", "out_proj", "fc_in", "fc_out", "wte"] + >>> config = HiraConfig(r=32, target_modules=target_modules, hira_dropout=0.1, task_type="CAUSAL_LM") + >>> quantization_config = transformers.BitsAndBytesConfig(load_in_8bit=True) + + >>> tokenizer = transformers.AutoTokenizer.from_pretrained( + ... "kakaobrain/kogpt", + ... revision="KoGPT6B-ryan1.5b-float16", # or float32 version: revision=KoGPT6B-ryan1.5b + ... bos_token="[BOS]", + ... eos_token="[EOS]", + ... unk_token="[UNK]", + ... pad_token="[PAD]", + ... mask_token="[MASK]", + ... ) + >>> model = transformers.GPTJForCausalLM.from_pretrained( + ... "kakaobrain/kogpt", + ... revision="KoGPT6B-ryan1.5b-float16", # or float32 version: revision=KoGPT6B-ryan1.5b + ... pad_token_id=tokenizer.eos_token_id, + ... use_cache=False, + ... device_map={"": rank}, + ... torch_dtype=torch.float16, + ... quantization_config=quantization_config, + ... ) + >>> model = prepare_model_for_kbit_training(model) + >>> hira_model = get_peft_model(model, config) + ``` + + **Attributes**: + - **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted. + - **peft_config** ([`LoraConfig`]): The configuration of the Lora model. + """ + + prefix: str = "hira_" + tuner_layer_cls = HiraLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_HIRA_TARGET_MODULES_MAPPING + + def _create_and_replace( + self, + hira_config, + adapter_name, + target, + target_name, + parent, + current_key, + ) -> None: + if current_key is None: + raise ValueError("Current Key shouldn't be `None`") + + # Regexp matching - Find key which matches current target_name in patterns provided + r_key = get_pattern_key(hira_config.rank_pattern.keys(), current_key) + r = hira_config.rank_pattern.get(r_key, hira_config.r) + + kwargs = { + "r": r, + "fan_in_fan_out": hira_config.fan_in_fan_out, + "loaded_in_8bit": getattr(self.model, "is_loaded_in_8bit", False), + "loaded_in_4bit": getattr(self.model, "is_loaded_in_4bit", False), + } + # for torchao merging, we need the get_apply_tensor_subclass from the quantization config + try: + kwargs["get_apply_tensor_subclass"] = operator.attrgetter( + "hf_quantizer.quantization_config.get_apply_tensor_subclass" + )(self.model) + except AttributeError: + pass + + if isinstance(target, HiraLayer): + target.update_layer(adapter_name, r, config=hira_config) + else: + device_map = self.model.hf_device_map if hasattr(self.model, "hf_device_map") else None + new_module = self._create_new_module(hira_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) + + def _replace_module(self, parent, child_name, new_module, child): + setattr(parent, child_name, new_module) + # It's not necessary to set requires_grad here, as that is handled by + # _mark_only_adapters_as_trainable + + # child layer wraps the original module, unpack it + if hasattr(child, "base_layer"): + child = child.base_layer + + meta = torch.device("meta") + # dispatch to correct device + for name, module in new_module.named_modules(): + if (self.prefix in name) or ("ranknum" in name): + if hasattr(child, "qweight"): + weight = child.qweight + elif hasattr(child, "W_q"): + weight = child.W_q + elif hasattr(child, "weight"): + weight = child.weight + elif getattr(child, "in_proj_weight", None) is not None: # MHA + weight = child.in_proj_weight + else: + weight = next(child.parameters()) + if not any(p.device == meta for p in module.parameters()): + module.to(weight.device) + + @staticmethod + def _create_new_module(hira_config: HiraConfig, adapter_name, target, **kwargs): + # Collect dispatcher functions to decide what backend to use for the replaced HiRA 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_default, + ] + ) + + new_module = None + for dispatcher in dispatchers: + new_module = dispatcher(target, adapter_name, hira_config=hira_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.Embedding`, `torch.nn.Conv1d`, `torch.nn.Conv2d`, `torch.nn.Conv3d`, " + "`transformers.pytorch_utils.Conv1D`." + ) + + return new_module diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/hra/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/hra/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8f5f6a54435d0fcaa1bd275c623168b5491f2d9e --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/hra/__init__.py @@ -0,0 +1,24 @@ +# 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 peft.utils import register_peft_method + +from .config import HRAConfig +from .layer import HRAConv2d, HRALayer, HRALinear +from .model import HRAModel + + +__all__ = ["HRAConfig", "HRAConv2d", "HRALayer", "HRALinear", "HRAModel"] + +register_peft_method(name="hra", config_cls=HRAConfig, model_cls=HRAModel) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/hra/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/hra/config.py new file mode 100644 index 0000000000000000000000000000000000000000..9e6d87cc17c3ba003eac963467bb1253725ebe10 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/hra/config.py @@ -0,0 +1,133 @@ +# 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 + +from dataclasses import dataclass, field +from typing import Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class HRAConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`HRAModel`]. + + Args: + r (`int`): + The rank of HRA across different layers. It is best to set 'r' to an even number; otherwise, the default + initialization method will not work. + apply_GS (`bool`): + Whether to apply Gram-Schmidt orthogonalization. + 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. + 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 HRA 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. + """ + + r: int = field( + default=8, + metadata={ + "help": "The rank of HRA across different layers.", + "note": "It is best to set 'r' to an even number; otherwise, the default initialization method will not work.", + }, + ) + apply_GS: bool = field( + default=False, + metadata={"help": "Whether to apply Gram-Schmidt orthogonalization or not."}, + ) + 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 HRA.", + "example": "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 HRA."}, + ) + init_weights: bool = field( + default=True, + metadata={ + "help": ( + "Whether to initialize the weights of the HRA 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'`." + }, + ) + bias: str = field(default="none", metadata={"help": "Bias type for HRA. Can be 'none', 'all' or 'hra_only'"}) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": "List of modules apart from HRA 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.HRA + 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 + ) + # if target_modules is a regex expression, then layers_to_transform should be None + if isinstance(self.target_modules, str) and self.layers_to_transform is not None: + raise ValueError("`layers_to_transform` cannot be used when `target_modules` is a str.") + + # if target_modules is a regex expression, then layers_pattern should be None + if isinstance(self.target_modules, str) and self.layers_pattern is not None: + raise ValueError("`layers_pattern` cannot be used when `target_modules` is a str.") + + # 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. ") diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/hra/layer.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/hra/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..5adb8d979dbfd9f1796e3f9807079437124acdf7 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/hra/layer.py @@ -0,0 +1,462 @@ +# 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 math +import warnings +from typing import Any, Optional + +import torch +import torch.nn.functional as F +from torch import nn + +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge + +from .config import HRAConfig + + +class HRALayer(BaseTunerLayer): + # All names of layers that may contain (trainable) adapter weights + adapter_layer_names = ("hra_u",) + # All names of other parameters that may contain adapter-related parameters + other_param_names = ("hra_r", "hra_apply_GS") + + def __init__(self, base_layer: nn.Module, **kwargs) -> None: + self.base_layer = base_layer + self.hra_r = {} + self.hra_apply_GS = {} + self.hra_u = nn.ParameterDict({}) + # 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): + self.in_features, self.out_features = base_layer.in_features, base_layer.out_features + elif isinstance(base_layer, nn.Conv2d): + self.in_features, self.out_features = base_layer.in_channels, base_layer.out_channels + else: + raise TypeError(f"Unsupported layer type {type(base_layer)}") + + def update_layer( + self, + adapter_name: str, + r: int, + config: HRAConfig, + **kwargs, + ) -> None: + """Internal function to create hra adapter + + Args: + adapter_name (`str`): Name for the adapter to add. + r (`int`): Rank for the added adapter. + config (`HRAConfig`): The adapter configuration for this layer. + """ + apply_GS = config.apply_GS + init_weights = config.init_weights + inference_mode = config.inference_mode + + if r <= 0: + raise ValueError(f"`r` should be a positive integer value but the value passed is {r}") + + self.hra_r[adapter_name] = r + self.hra_apply_GS[adapter_name] = apply_GS + + # Determine shape of HRA weights + base_layer = self.get_base_layer() + if isinstance(base_layer, nn.Linear): + self.hra_u[adapter_name] = nn.Parameter(torch.empty(self.in_features, r), requires_grad=True) + elif isinstance(base_layer, nn.Conv2d): + self.hra_u[adapter_name] = nn.Parameter( + torch.empty(self.in_features * base_layer.kernel_size[0] * base_layer.kernel_size[0], r), + requires_grad=True, + ) + else: + raise TypeError(f"HRA is not implemented for base layers of type {type(base_layer).__name__}") + + # Initialize weights + if init_weights: + self.reset_hra_parameters(adapter_name) + else: + self.reset_hra_parameters_random(adapter_name) + + # 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_hra_parameters(self, adapter_name: str): + if self.hra_r[adapter_name] % 2 != 0: + warnings.warn("The symmetric initialization can NOT be performed when r is odd!") + nn.init.kaiming_uniform_(self.hra_u[adapter_name], a=math.sqrt(5)) + else: + shape = self.hra_u[adapter_name].shape + half_u = torch.zeros(shape[0], shape[1] // 2) + nn.init.kaiming_uniform_(half_u, a=math.sqrt(5)) + self.hra_u[adapter_name] = nn.Parameter(torch.repeat_interleave(half_u, 2, dim=1)) + + def reset_hra_parameters_random(self, adapter_name: str): + nn.init.kaiming_uniform_(self.hra_u[adapter_name], a=math.sqrt(5)) + + def scale_layer(self, scale: float) -> None: + if scale == 1: + return + + for active_adapter in self.active_adapters: + if active_adapter not in self.hra_u.keys(): + continue + + warnings.warn("Scaling operation for HRA 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.hra_u.keys(): + continue + + warnings.warn("Unscaling operation for HRA not supported! Keeping scale at 1.") + + +class HRALinear(nn.Module, HRALayer): + """ + HRA implemented in a dense layer. + """ + + def __init__( + self, + base_layer, + adapter_name: str, + config: HRAConfig, + r: int = 0, + **kwargs, + ) -> None: + super().__init__() + HRALayer.__init__(self, base_layer, **kwargs) + self._active_adapter = adapter_name + self.update_layer(adapter_name, r, config=config, **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`. + """ + 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.hra_u.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_weight = base_layer.weight.data.clone() + delta_weight = self.get_delta_weight(active_adapter) + orig_weight = torch.mm(orig_weight.to(delta_weight.dtype), delta_weight) + + if not torch.isfinite(orig_weight).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = orig_weight.to(orig_dtype) + else: + delta_weight = self.get_delta_weight(active_adapter) + new_weight = torch.mm(base_layer.weight.data.to(delta_weight.dtype), delta_weight) + base_layer.weight.data = new_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: + active_adapter = self.merged_adapters.pop() + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.dtype + if active_adapter in self.hra_u.keys(): + orig_weight = base_layer.weight.data.clone() + delta_weight = self.get_delta_weight(active_adapter, reverse=True) + new_weight = torch.mm(orig_weight.to(delta_weight.dtype), delta_weight) + base_layer.weight.data = new_weight.to(orig_dtype) + + def get_delta_weight(self, adapter_name: str, reverse: bool = False) -> torch.Tensor: + rank = self.hra_r[adapter_name] + apply_GS = self.hra_apply_GS[adapter_name] + opt_u = self.hra_u[adapter_name] + shape = opt_u.shape + + if apply_GS: + weight = [(opt_u[:, 0] / opt_u[:, 0].norm()).view(-1, 1)] + for i in range(1, rank): + ui = opt_u[:, i].view(-1, 1) + for j in range(i): + ui = ui - (weight[j].t() @ ui) * weight[j] + weight.append((ui / ui.norm()).view(-1, 1)) + weight = torch.cat(weight, dim=1) + weight = torch.eye(shape[0], device=opt_u.device, dtype=opt_u.dtype) - 2 * weight @ weight.t() + + else: + opt_u = opt_u / opt_u.norm(dim=0) + weight = torch.eye(shape[0], device=opt_u.device, dtype=opt_u.dtype) + if reverse: + indices = range(rank - 1, -1, -1) + else: + indices = range(rank) + + for i in indices: + ui = opt_u[:, i].view(-1, 1) + weight = weight - 2 * weight @ ui @ ui.t() + + return 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: + new_weight = torch.eye(self.in_features, device=x.device) + + for active_adapter in self.active_adapters: + if active_adapter not in self.hra_u.keys(): + continue + delta_weight = self.get_delta_weight(active_adapter) + new_weight = torch.mm(new_weight.to(delta_weight.dtype), delta_weight) + + orig_weight = self.get_base_layer().weight.data + orig_weight = self._cast_input_dtype(orig_weight, new_weight.dtype) + new_weight = torch.mm(orig_weight, new_weight) + bias = self._cast_input_dtype(self.base_layer.bias, new_weight.dtype) + + if self.cast_input_dtype_enabled: + x = self._cast_input_dtype(x, new_weight.dtype) + else: + x = x.to(self.get_base_layer().weight.data.dtype) + result = F.linear(input=x, weight=new_weight, bias=bias) + + result = result.to(previous_dtype) + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "hra." + rep + + +class HRAConv2d(nn.Module, HRALayer): + """HRA implemented in Conv2d layer""" + + def __init__( + self, + base_layer, + adapter_name: str, + config: HRAConfig, + r: int = 0, + **kwargs, + ): + super().__init__() + HRALayer.__init__(self, base_layer) + self._active_adapter = adapter_name + self.update_layer(adapter_name, r, config=config, **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`. + """ + 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.hra_u.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_weight = base_layer.weight.data.clone() + orig_weight = orig_weight.view( + self.out_features, + self.in_features * base_layer.kernel_size[0] * self.base_layer.kernel_size[0], + ) + delta_weight = self.get_delta_weight(active_adapter) + orig_weight = torch.mm(orig_weight.to(delta_weight.dtype), delta_weight) + orig_weight = orig_weight.view( + self.out_features, + self.in_features, + base_layer.kernel_size[0], + base_layer.kernel_size[0], + ) + + if not torch.isfinite(orig_weight).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = orig_weight.to(orig_dtype) + else: + orig_weight = base_layer.weight.data + orig_weight = orig_weight.view( + self.out_features, + self.in_features * self.base_layer.kernel_size[0] * self.base_layer.kernel_size[0], + ) + delta_weight = self.get_delta_weight(active_adapter) + orig_weight = torch.mm(orig_weight.to(delta_weight.dtype), delta_weight) + orig_weight = orig_weight.view( + self.out_features, + self.in_features, + base_layer.kernel_size[0], + base_layer.kernel_size[0], + ) + + base_layer.weight.data = orig_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: + active_adapter = self.merged_adapters.pop() + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.dtype + if active_adapter in self.hra_u.keys(): + orig_weight = base_layer.weight.data.clone() + orig_weight = orig_weight.view( + self.out_features, + self.in_features * base_layer.kernel_size[0] * base_layer.kernel_size[0], + ) + delta_weight = self.get_delta_weight(active_adapter, reverse=True) + orig_weight = torch.mm(orig_weight.to(delta_weight.dtype), delta_weight) + orig_weight = orig_weight.view( + self.out_features, self.in_features, base_layer.kernel_size[0], base_layer.kernel_size[0] + ) + + base_layer.weight.data = orig_weight.to(orig_dtype) + + def get_delta_weight(self, adapter_name: str, reverse: bool = False) -> torch.Tensor: + rank = self.hra_r[adapter_name] + apply_GS = self.hra_apply_GS[adapter_name] + opt_u = self.hra_u[adapter_name] + shape = opt_u.shape + + if apply_GS: + weight = [(opt_u[:, 0] / opt_u[:, 0].norm()).view(-1, 1)] + for i in range(1, rank): + ui = opt_u[:, i].view(-1, 1) + for j in range(i): + ui = ui - (weight[j].t() @ ui) * weight[j] + weight.append((ui / ui.norm()).view(-1, 1)) + weight = torch.cat(weight, dim=1) + weight = torch.eye(shape[0], device=opt_u.device, dtype=opt_u.dtype) - 2 * weight @ weight.t() + + else: + opt_u = opt_u / opt_u.norm(dim=0) + weight = torch.eye(shape[0], device=opt_u.device, dtype=opt_u.dtype) + if reverse: + indices = range(rank - 1, -1, -1) + else: + indices = range(rank) + + for i in indices: + ui = opt_u[:, i].view(-1, 1) + weight = weight - 2 * weight @ ui @ ui.t() + + return 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: + new_weight = torch.eye( + self.in_features * self.base_layer.kernel_size[0] * self.base_layer.kernel_size[0], + device=x.device, + ) + for active_adapter in self.active_adapters: + if active_adapter not in self.hra_u.keys(): + continue + delta_weight = self.get_delta_weight(active_adapter) + new_weight = torch.mm(new_weight.to(delta_weight.dtype), delta_weight) + + orig_weight = self.base_layer.weight.data + orig_weight = orig_weight.view( + self.out_features, + self.in_features * self.base_layer.kernel_size[0] * self.base_layer.kernel_size[0], + ) + orig_weight = self._cast_input_dtype(orig_weight, new_weight.dtype) + bias = self._cast_input_dtype(self.base_layer.bias, new_weight.dtype) + + new_weight = torch.mm(orig_weight, new_weight) + new_weight = new_weight.view( + self.out_features, + self.in_features, + self.base_layer.kernel_size[0], + self.base_layer.kernel_size[0], + ) + + if self.cast_input_dtype_enabled: + x = self._cast_input_dtype(x, new_weight.dtype) + else: + x = x.to(self.get_base_layer().weight.data.dtype) + result = F.conv2d( + input=x, + weight=new_weight, + bias=bias, + padding=self.base_layer.padding[0], + stride=self.base_layer.stride[0], + ) + + result = result.to(previous_dtype) + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "hra." + rep diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/hra/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/hra/model.py new file mode 100644 index 0000000000000000000000000000000000000000..8eb57bca548d952fec04cdc9417383d3eacc5d54 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/hra/model.py @@ -0,0 +1,122 @@ +# 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 torch + +from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer +from peft.utils import TRANSFORMERS_MODELS_TO_HRA_TARGET_MODULES_MAPPING + +from .layer import HRAConv2d, HRALayer, HRALinear + + +class HRAModel(BaseTuner): + """ + Creates Householder reflection adaptation (HRA) model from a pretrained model. The method is described in + https://huggingface.co/papers/2405.17484 + + Args: + model (`torch.nn.Module`): The model to which the adapter tuner layers will be attached. + config ([`HRAConfig`]): The configuration of the HRA 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 HRA model. + + Example: + ```py + >>> from diffusers import StableDiffusionPipeline + >>> from peft import HRAModel, HRAConfig + + >>> config_te = HRAConfig( + ... r=8, + ... target_modules=["k_proj", "q_proj", "v_proj", "out_proj", "fc1", "fc2"], + ... init_weights=True, + ... ) + >>> config_unet = HRAConfig( + ... r=8, + ... target_modules=[ + ... "proj_in", + ... "proj_out", + ... "to_k", + ... "to_q", + ... "to_v", + ... "to_out.0", + ... "ff.net.0.proj", + ... "ff.net.2", + ... ], + ... init_weights=True, + ... ) + + >>> model = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5") + >>> model.text_encoder = HRAModel(model.text_encoder, config_te, "default") + >>> model.unet = HRAModel(model.unet, config_unet, "default") + ``` + + **Attributes**: + - **model** ([`~torch.nn.Module`]) -- The model to be adapted. + - **peft_config** ([`HRAConfig`]): The configuration of the HRA model. + """ + + prefix: str = "hra_" + tuner_layer_cls = HRALayer + target_module_mapping = TRANSFORMERS_MODELS_TO_HRA_TARGET_MODULES_MAPPING + + def _create_and_replace( + self, + hra_config, + adapter_name, + target, + target_name, + parent, + current_key, + **optional_kwargs, + ): + if current_key is None: + raise ValueError("Current Key shouldn't be `None`") + + # If it is not a HRALayer, create a new module, else update it with new adapters + if not isinstance(target, HRALayer): + new_module = self._create_new_module(hra_config, adapter_name, target, r=hra_config.r) + 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=hra_config.r, + config=hra_config, + ) + + @staticmethod + def _create_new_module(hra_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): + new_module = HRALinear(target, adapter_name, config=hra_config, **kwargs) + elif isinstance(target_base_layer, torch.nn.Conv2d): + new_module = HRAConv2d(target, adapter_name, config=hra_config, **kwargs) + else: + raise TypeError( + f"Target module {target} is not supported. " + "Currently, only `torch.nn.Linear` and `torch.nn.Conv2d` are supported." + ) + + return new_module diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/ia3/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/ia3/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..21cab4d6d8a6437766f395e90079ce6ecd9e4f26 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/ia3/__init__.py @@ -0,0 +1,39 @@ +# 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.utils import register_peft_method + +from .config import IA3Config +from .layer import Conv2d, Conv3d, IA3Layer, Linear +from .model import IA3Model + + +__all__ = ["Conv2d", "Conv3d", "IA3Config", "IA3Layer", "IA3Model", "Linear"] + +register_peft_method(name="ia3", config_cls=IA3Config, model_cls=IA3Model, is_mixed_compatible=True) + + +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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/ia3/bnb.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/ia3/bnb.py new file mode 100644 index 0000000000000000000000000000000000000000..ce0a8b443ca96bfa601c774638436a8798500e13 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/ia3/bnb.py @@ -0,0 +1,130 @@ +# 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 + +import torch + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available + +from .config import IA3Config +from .layer import IA3Layer + + +if is_bnb_available(): + + class Linear8bitLt(torch.nn.Module, IA3Layer): + # (IA)^3 implemented in a dense layer + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + config: IA3Config, + is_feedforward: bool, + **kwargs, + ) -> None: + super().__init__() + IA3Layer.__init__(self, base_layer, is_feedforward=is_feedforward) + + # Freezing the pre-trained weight matrix + self.get_base_layer().weight.requires_grad = False + self._active_adapter = adapter_name + self.update_layer(adapter_name, config=config) + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + # note: no check for self.merged because merging is not supported (yet) + if self.disable_adapters: + return self.base_layer(x) + + ia3_scaling = 1 + for active_adapter in self.active_adapters: + if active_adapter not in self.ia3_l.keys(): + continue + ia3_scaling *= self.ia3_l[active_adapter].flatten() + + requires_conversion = (not torch.is_autocast_enabled()) and (x.dtype != torch.float32) + if requires_conversion: + x = x.float() + if self.is_feedforward: + result = self.base_layer(x * ia3_scaling) + expected_dtype = result.dtype + else: + result = self.base_layer(x) + expected_dtype = result.dtype + result = result * ia3_scaling + + if requires_conversion: + result = result.to(expected_dtype) + + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "ia3." + rep + + +if is_bnb_4bit_available(): + + class Linear4bit(torch.nn.Module, IA3Layer): + # IA3 implemented in a dense layer + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + config: IA3Config, + is_feedforward: bool, + **kwargs, + ) -> None: + super().__init__() + IA3Layer.__init__(self, base_layer, is_feedforward=is_feedforward) + + # Freezing the pre-trained weight matrix + self.get_base_layer().weight.requires_grad = False + self._active_adapter = adapter_name + self.update_layer(adapter_name, config=config) + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + # note: no check for self.merged because merging is not supported (yet) + if self.disable_adapters: + return self.base_layer(x) + + ia3_scaling = 1 + for active_adapter in self.active_adapters: + if active_adapter not in self.ia3_l.keys(): + continue + ia3_scaling *= self.ia3_l[active_adapter].flatten() + + requires_conversion = (not torch.is_autocast_enabled()) and (x.dtype != torch.float32) + if requires_conversion: + x = x.float() + if self.is_feedforward: + result = self.base_layer(x * ia3_scaling) + expected_dtype = result.dtype + else: + result = self.base_layer(x) + expected_dtype = result.dtype + result = result * ia3_scaling + + result = result.clone() + # adalora.py and lora.py both suggest that this is necessary for 4-bit training on older versions of Pytorch. + # This has been duplicated here. + + if requires_conversion: + result = result.to(expected_dtype) + + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "ia3." + rep diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/ia3/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/ia3/config.py new file mode 100644 index 0000000000000000000000000000000000000000..1c4161e5ed97998017b800535d4315c66c9d14cd --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/ia3/config.py @@ -0,0 +1,112 @@ +# 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 Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class IA3Config(PeftConfig): + """ + This is the configuration class to store the configuration of a [`IA3Model`]. + + Args: + 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/Conv1D 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. + 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. + feedforward_modules (`Optional[Union[List[str], str]]`): + The names of the modules to be treated as feedforward modules, as in the original paper. These modules will + have (IA)³ vectors multiplied to the input, instead of the output. `feedforward_modules` must be a name or + a subset of names present in `target_modules`. + 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`. + modules_to_save (`Optional[List[str]]`): + List of modules apart from (IA)³ layers to be set as trainable and saved in the final checkpoint. + init_ia3_weights (`bool`): + Whether to initialize the vectors in the (IA)³ layers, defaults to `True`. Setting this to `False` is + discouraged. + """ + + 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 (IA)³." + "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." + "If 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." + ), + }, + ) + 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 (IA)³."}, + ) + feedforward_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": "List of module names or a regex expression of module names which are feedforward" + "For example, ['output.dense']" + }, + ) + 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)"}, + ) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": "List of modules apart from (IA)^3 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_ia3_weights: bool = field( + default=True, + metadata={"help": "Whether to initialize the vectors in the (IA)^3 layers."}, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.IA3 + 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 + ) + self.feedforward_modules = ( + set(self.feedforward_modules) if isinstance(self.feedforward_modules, list) else self.feedforward_modules + ) + + # check if feedforward_modules is a subset of target_modules. run the check only if both are sets + if isinstance(self.feedforward_modules, set) and isinstance(self.target_modules, set): + if not self.feedforward_modules.issubset(self.target_modules): + raise ValueError("`feedforward_modules` should be a subset of `target_modules`") diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/ia3/layer.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/ia3/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..7f989ece5012e0c99d28612ac62b29e73b00ff16 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/ia3/layer.py @@ -0,0 +1,336 @@ +# 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 warnings +from typing import Any, Optional + +import torch +from torch import nn +from transformers.pytorch_utils import Conv1D + +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge +from peft.utils import transpose + +from .config import IA3Config + + +class IA3Layer(BaseTunerLayer): + # All names of layers that may contain adapter weights + adapter_layer_names = ("ia3_l",) + + def __init__(self, base_layer: nn.Module, is_feedforward: bool, **kwargs) -> None: + self.base_layer = base_layer + self.ia3_l = nn.ParameterDict({}) + # Mark the weight as unmerged + self._disable_adapters = False + self.merged_adapters = [] + self.is_feedforward = is_feedforward + + 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, nn.Conv3d)): + in_features, out_features = base_layer.in_channels, base_layer.out_channels + elif isinstance(base_layer, nn.Embedding): + in_features, out_features = base_layer.num_embeddings, base_layer.embedding_dim + 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 + ) + else: + raise TypeError(f"Unsupported layer type {type(base_layer)}") + self.in_features = in_features + self.out_features = out_features + + def update_layer(self, adapter_name: str, config: IA3Config, **kwargs): + init_ia3_weights = config.init_ia3_weights + inference_mode = config.inference_mode + + # This code works for linear layers, override for other layer types + # Actual trainable parameters + if self.is_feedforward: + weight = torch.randn((1, self.in_features)) + else: + weight = torch.randn((self.out_features, 1)) + self.ia3_l[adapter_name] = nn.Parameter(weight) + if init_ia3_weights: + self.reset_ia3_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_ia3_parameters(self, adapter_name): + if adapter_name in self.ia3_l.keys(): + # initialize learned vector with torch.ones + nn.init.constant_(self.ia3_l[adapter_name], 1.0) + + +class Linear(nn.Module, IA3Layer): + # (IA)^3 implemented in a dense layer + def __init__( + self, + base_layer: nn.Module, + adapter_name: str, + config: IA3Config, + is_feedforward: bool = False, # Set to True if the layer is treated as a feedforward layer + is_target_conv_1d_layer: bool = False, # whether target module is a conv1d layer. useful while unloading later + **kwargs, + ) -> None: + super().__init__() + IA3Layer.__init__(self, base_layer, is_feedforward=is_feedforward) + self.fan_in_fan_out = config.fan_in_fan_out + self.is_target_conv_1d_layer = is_target_conv_1d_layer + self._active_adapter = adapter_name + self.update_layer(adapter_name, config=config) + + 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.ia3_l.keys(): + base_layer = self.get_base_layer() + ia3_l = transpose(self.ia3_l[active_adapter].data, self.fan_in_fan_out) + orig_dtype = base_layer.weight.data.dtype + if safe_merge: + orig_weights = base_layer.weight.data + orig_weights = torch.mul(orig_weights, ia3_l) + + 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: + base_layer.weight.data = torch.mul(base_layer.weight.data, ia3_l).to(orig_dtype) + + if not self.is_feedforward and (base_layer.bias is not None): + scaling = self.ia3_l[active_adapter].reshape(base_layer.bias.shape) + orig_dtype = base_layer.bias.data.dtype + base_layer.bias.data = torch.mul(base_layer.bias.data, scaling.data).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 + + warnings.warn("Unmerge result can be inaccurate for (IA)^3.") + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter in self.ia3_l.keys(): + base_layer = self.get_base_layer() + # Add tolerace to avoid division by zero + ia3_l = transpose(self.ia3_l[active_adapter].data, self.fan_in_fan_out) + 1e-8 + orig_dtype = base_layer.weight.data.dtype + base_layer.weight.data = torch.div(base_layer.weight.data, ia3_l).to(orig_dtype) + + if not self.is_feedforward and (base_layer.bias is not None): + scaling = self.ia3_l[active_adapter].reshape(base_layer.bias.shape) + orig_dtype = base_layer.bias.data.dtype + base_layer.bias.data = torch.div(base_layer.bias.data, scaling.data + 1e-8).to(orig_dtype) + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + dtype = 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: + ia3_scaling = 1 + for active_adapter in self.active_adapters: + if active_adapter not in self.ia3_l.keys(): + continue + dtype = self.ia3_l[active_adapter].dtype + ia3_scaling *= self.ia3_l[active_adapter].flatten() + + if self.is_feedforward: + x = x.to(dtype) + # TODO: weight.dtype can be != self.ia3_l[self.active_adapters].dtype + # e.g. bf16 vs fp32. Is that okay? + interm = (x * ia3_scaling).to(previous_dtype) + result = self.base_layer(interm, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + result_dtype = result.dtype + result = (result * ia3_scaling).to(result_dtype) + + return result + + +class _ConvNd(nn.Module, IA3Layer): + def __init__( + self, + base_layer: nn.Module, + adapter_name: str, + config: IA3Config, + is_feedforward: bool = False, # Set to True if the layer is treated as a feedforward layer + **kwargs, + ) -> None: + super().__init__() + IA3Layer.__init__(self, base_layer, is_feedforward=is_feedforward) + self.fan_in_fan_out = config.fan_in_fan_out + self._active_adapter = adapter_name + self._kernel_dim = base_layer.weight.dim() + + self.update_layer(adapter_name, config=config) + + def update_layer(self, adapter_name: str, config: IA3Config, **kwargs): + init_ia3_weights = config.init_ia3_weights + inference_mode = config.inference_mode + + # Actual trainable parameters + num_features = self.in_features if self.is_feedforward else self.out_features + weights_size = (1, num_features) + (1,) * (self._kernel_dim - 2) + weight = torch.randn(weights_size) + self.ia3_l[adapter_name] = nn.Parameter(weight) + if init_ia3_weights: + self.reset_ia3_parameters(adapter_name) + 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.ia3_l.keys(): + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.data.dtype + ia3_scaling = self.ia3_l[active_adapter].data + if not self.is_feedforward: + ia3_scaling = ia3_scaling.transpose(0, 1) + + if safe_merge: + output_weight = torch.mul(base_layer.weight.data, ia3_scaling).clone() + + if not torch.isfinite(output_weight).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = output_weight.to(orig_dtype) + else: + base_layer.weight.data = torch.mul(base_layer.weight.data, ia3_scaling).to(orig_dtype) + + if not self.is_feedforward and (base_layer.bias is not None): + scaling = self.ia3_l[active_adapter].reshape(base_layer.bias.shape) + base_layer.bias.data = torch.mul(base_layer.bias.data, scaling.data).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 + + warnings.warn("Unmerge result can be inaccurate for (IA)^3.") + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter in self.ia3_l.keys(): + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.data.dtype + # divide by (IA)^3 vector. Add tolerace to avoid division by zero + ia3_scaling = self.ia3_l[active_adapter].data + if not self.is_feedforward: + ia3_scaling = ia3_scaling.transpose(0, 1) + base_layer.weight.data = torch.div(base_layer.weight.data, ia3_scaling + 1e-8).to(orig_dtype) + + if not self.is_feedforward and (base_layer.bias is not None): + scaling = self.ia3_l[active_adapter].reshape(base_layer.bias.shape) + orig_dtype = base_layer.bias.data.dtype + base_layer.bias.data = torch.div(base_layer.bias.data, scaling.data + 1e-8).to(orig_dtype) + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + dtype = 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: + ia3_scaling = 1 + for active_adapter in self.active_adapters: + if active_adapter not in self.ia3_l.keys(): + continue + dtype = self.ia3_l[active_adapter].dtype + ia3_scaling *= self.ia3_l[active_adapter] + + if self.is_feedforward: + x = x.to(dtype) + # TODO: weight.dtype can be != self.ia3_l[self.active_adapters].dtype + # e.g. bf16 vs fp32. Is that okay? + interm = (x * ia3_scaling).to(self.get_base_layer().weight.dtype) + result = self.base_layer(interm, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + result = result.to(dtype) * ia3_scaling + + result = result.to(previous_dtype) + return result + + +class Conv2d(_ConvNd): + # IA3 implemented in a 2D convolutional layer + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + if not self._kernel_dim == 4: + raise ValueError(f"Conv2d layer kernel must have 4 dimensions, not {self._kernel_dim}") + + +class Conv3d(_ConvNd): + # IA3 implemented in a 3D convolutional layer + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + if not self._kernel_dim == 5: + raise ValueError(f"Conv2d layer kernel must have 5 dimensions, not {self._kernel_dim}") diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/ia3/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/ia3/model.py new file mode 100644 index 0000000000000000000000000000000000000000..edf1bbb0052eae7568643e7d8877289ee5e37322 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/ia3/model.py @@ -0,0 +1,322 @@ +# 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 re +import warnings +from dataclasses import replace + +import torch +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_IA3_FEEDFORWARD_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_IA3_TARGET_MODULES_MAPPING, + ModulesToSaveWrapper, + _freeze_adapter, + _get_submodules, +) + +from .layer import Conv2d, Conv3d, IA3Layer, Linear + + +class IA3Model(BaseTuner): + """ + Creates a Infused Adapter by Inhibiting and Amplifying Inner Activations ((IA)^3) model from a pretrained + transformers model. The method is described in detail in https://huggingface.co/papers/2205.05638 + + Args: + model ([`~transformers.PreTrainedModel`]): The model to be adapted. + config ([`IA3Config`]): The configuration of the (IA)^3 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 (IA)^3 model. + + Example: + + ```py + >>> from transformers import AutoModelForSeq2SeqLM + >>> from peft import IA3Config, get_peft_model + + >>> config = IA3Config( + ... peft_type="IA3", + ... task_type="SEQ_2_SEQ_LM", + ... target_modules=["k", "v", "w0"], + ... feedforward_modules=["w0"], + ... ) + + >>> model = AutoModelForSeq2SeqLM.from_pretrained("t5-base") + >>> ia3_model = get_peft_model(model, config) + ``` + + **Attributes**: + - **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted. + - **peft_config** ([`IA3Config`]): The configuration of the (IA)^3 model. + """ + + prefix: str = "ia3_" + tuner_layer_cls = IA3Layer + + @staticmethod + def _create_new_module(ia3_config, 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 + + loaded_in_8bit = kwargs.pop("loaded_in_8bit", False) + loaded_in_4bit = kwargs.pop("loaded_in_4bit", False) + is_feedforward = kwargs.pop("is_feedforward", 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, + } + ) + new_module = Linear8bitLt( + target, adapter_name, config=ia3_config, is_feedforward=is_feedforward, **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, + } + ) + new_module = Linear4bit( + target, adapter_name, config=ia3_config, is_feedforward=is_feedforward, **fourbit_kwargs + ) + elif isinstance(target, torch.nn.Conv2d): + new_module = Conv2d(target, adapter_name, config=ia3_config, is_feedforward=is_feedforward, **kwargs) + elif isinstance(target, torch.nn.Conv3d): + new_module = Conv3d(target, adapter_name, config=ia3_config, is_feedforward=is_feedforward, **kwargs) + elif isinstance(target_base_layer, torch.nn.Linear): + if ia3_config.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." + ) + ia3_config.fan_in_fan_out = False + new_module = Linear(target, adapter_name, config=ia3_config, is_feedforward=is_feedforward, **kwargs) + elif isinstance(target_base_layer, Conv1D): + if not ia3_config.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." + ) + ia3_config.fan_in_fan_out = True + new_module = Linear( + target, + adapter_name, + config=ia3_config, + is_feedforward=is_feedforward, + is_target_conv_1d_layer=True, + **kwargs, + ) + else: + raise ValueError( + f"Target module {target} is not supported. " + f"Currently, only `torch.nn.Linear`, `torch.nn.Conv2d`, and `Conv1D` are supported." + ) + return new_module + + def _create_and_replace( + self, + ia3_config, + adapter_name, + target, + target_name, + parent, + current_key, + ): + # check if target module is in feedforward_modules + is_feedforward = self._check_target_module_feedforward(ia3_config, current_key) + + kwargs = { + "is_feedforward": is_feedforward, + "loaded_in_8bit": getattr(self.model, "is_loaded_in_8bit", False), + "loaded_in_4bit": getattr(self.model, "is_loaded_in_4bit", False), + } + + if isinstance(target, IA3Layer): + target.update_layer( + adapter_name, + config=ia3_config, + ) + else: + new_module = self._create_new_module(ia3_config, adapter_name, target, **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) + + @staticmethod + def _check_target_module_feedforward(ia3_config, key) -> bool: + """ + A helper private method that checks if the target module `key` matches with a feedforward module specified in + `ia3_config` + """ + if isinstance(ia3_config.feedforward_modules, str): + is_feedforward = bool(re.fullmatch(ia3_config.feedforward_modules, key)) + else: + is_feedforward = any(key.endswith(target_key) for target_key in ia3_config.feedforward_modules) + return is_feedforward + + @staticmethod + def _prepare_adapter_config(peft_config, model_config): + if peft_config.target_modules is None: + if model_config["model_type"] not in TRANSFORMERS_MODELS_TO_IA3_TARGET_MODULES_MAPPING: + raise ValueError("Please specify `target_modules` in `peft_config`") + peft_config.target_modules = set( + TRANSFORMERS_MODELS_TO_IA3_TARGET_MODULES_MAPPING[model_config["model_type"]] + ) + if peft_config.feedforward_modules is None: + if model_config["model_type"] not in TRANSFORMERS_MODELS_TO_IA3_FEEDFORWARD_MODULES_MAPPING: + raise ValueError("Please specify `feedforward_modules` in `peft_config`") + peft_config.feedforward_modules = set( + TRANSFORMERS_MODELS_TO_IA3_FEEDFORWARD_MODULES_MAPPING[model_config["model_type"]] + ) + return peft_config + + def _unload_and_optionally_merge(self, *args, **kwargs): + r""" + This method merges the (IA)^3 layers into the base model. This is needed if someone wants to use the base model + as a standalone model. + + Args: + safe_merge (`bool`, `optional`, defaults to `False`): + 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 getattr(self.model, "is_loaded_in_8bit", False): + raise ValueError("Cannot merge ia3 layers when the model is loaded in 8-bit mode") + + if getattr(self.model, "is_loaded_in_4bit", False): + raise ValueError("Cannot merge ia3 layers when the model is loaded in 4-bit mode") + + return super()._unload_and_optionally_merge(*args, **kwargs) + + def _check_add_weighted_adapter(self, adapters: list[str]) -> tuple[str, str]: + """ + Helper function to check if the arguments to add_weighted_adapter are valid and compatible with the underlying + model. + """ + # Validate existence of adapters + for adapter in adapters: + if adapter not in self.peft_config: + raise ValueError(f"Adapter {adapter} does not exist") + + # Check for conflicting modules_to_save + modules_to_save_wrappers = [module for module in self.modules() if isinstance(module, ModulesToSaveWrapper)] + if any( + sum(adapter in wrapper.modules_to_save for adapter in adapters) > 1 for wrapper in modules_to_save_wrappers + ): + raise ValueError("Cannot add weighted adapters targeting the same module with modules_to_save.") + + # Ensure all adapters have compatible target and feedforward module types + target_module_types = {type(self.peft_config[adapter].target_modules) for adapter in adapters} + feedforward_module_types = {type(self.peft_config[adapter].feedforward_modules) for adapter in adapters} + if len(target_module_types) > 1 or len(feedforward_module_types) > 1: + raise ValueError("All adapter configs should have the same type for target and feedforward modules.") + + # Combine target and feedforward modules + if str in target_module_types: + new_target_modules = "|".join(f"({self.peft_config[adapter].target_modules})" for adapter in adapters) + else: + new_target_modules = set.union(*(self.peft_config[adapter].target_modules for adapter in adapters)) + + if str in feedforward_module_types: + new_feedforward_modules = "|".join( + f"({self.peft_config[adapter].feedforward_modules})" for adapter in adapters + ) + else: + new_feedforward_modules = set.union( + *(self.peft_config[adapter].feedforward_modules for adapter in adapters) + ) + + return new_target_modules, new_feedforward_modules + + def add_weighted_adapter( + self, + adapters: list[str], + weights: list[float], + adapter_name: str, + ) -> None: + """ + This method adds a new adapter by merging the given adapters with the given weights. + + Args: + adapters (`list`): + List of adapter names to be merged. + weights (`list`): + List of weights for each adapter. + adapter_name (`str`): + Name of the new adapter. + """ + if adapter_name in list(self.peft_config.keys()): + return + + new_target_modules, new_feedforward_modules = self._check_add_weighted_adapter( + adapters=adapters, + ) + + self.peft_config[adapter_name] = replace( + self.peft_config[adapters[0]], + target_modules=new_target_modules, + feedforward_modules=new_feedforward_modules, + ) + self.inject_adapter(self.model, adapter_name) + + # Do we really need that? + _freeze_adapter(self.model, adapter_name) + + key_list = [key for key, _ in self.model.named_modules() if self.prefix not in key] + for key in key_list: + _, target, _ = _get_submodules(self.model, key) + if isinstance(target, IA3Layer): + if adapter_name in target.ia3_l: + target_ia3_l = target.ia3_l[adapter_name] + else: + continue + + target_ia3_l.data = target_ia3_l.data.zero_() + for adapter, weight in zip(adapters, weights): + if adapter in target.ia3_l: + current_adapter_ia3_l = target.ia3_l[adapter] + else: + continue + target_ia3_l.data += current_adapter_ia3_l.data * weight diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lily/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lily/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..df75b8a01874305e354689694fe675a344105984 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lily/__init__.py @@ -0,0 +1,26 @@ +# Copyright 2026-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 LilyConfig +from .layer import LilyLayer, Linear +from .model import LilyModel + + +__all__ = ["LilyConfig", "LilyLayer", "LilyModel", "Linear"] + +register_peft_method( + name="lily", config_cls=LilyConfig, model_cls=LilyModel, prefix="lily_", is_mixed_compatible=False +) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lily/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lily/config.py new file mode 100644 index 0000000000000000000000000000000000000000..97db3f8aaef9abac69422a23cd8c4316d11a385b --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lily/config.py @@ -0,0 +1,237 @@ +# Copyright 2026-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 LilyConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`LilyModel`]. + + Args: + r (`int`): + Lily's rank. Determines the inner hidden dimension of each adapter and the rank of the weight update `A @ + B`. In Lily, since the number of adapters is typically smaller than in LoRA, each adapter needs to carry + more capacity, so it is recommended to use a larger `r` than in LoRA — typically `2x`, `3x`, or `4x` the + LoRA rank you would normally use. The total number of trainable parameters scales with `r * (total_layers / + stride_A + num_B)`, so increasing `r` while keeping `stride_A` large and `num_B` small is the recommended + trade-off. + stride_A (`int`): + The number of consecutive layers that share one A adapter. For example, if `stride_A=4`, every 4 adjacent + layers share the same A adapter, resulting in `total_layers / stride_A` distinct A adapters in total. The A + adapter compresses the input into a low-rank representation of size `r`. `stride_A` should be no less than + 1. Suggested values: `2`, `3`, or `4` (i.e. sharing every 2, 3, or 4 layers). Keeping `stride_A` large + (fewer distinct A adapters) and increasing `r` instead leads to better performance than the opposite + trade-off (small `stride_A`, small `r`). Setting `stride_A=1` means every layer has its own A adapter. + NOTE: the A sharing happens within each target (layers with the same target suffix). For example, if your + target_modules are `['q_proj', 'v_proj']` and you set `stride_A=2`, then every 2 adjacent q_proj layers + will share an A adapter, and every 2 adjacent v_proj layers will share another A adapter, but the q_proj + and v_proj layers will not share A adapters with each other since they have different suffixes. + num_B (`int`): + The number of shared B adapters. Unlike A adapters (which are grouped by layer), all B adapters are shared + globally across every layer. For each forward pass, a router computes a weighted combination of all `num_B` + B adapters (using softmax-normalized weights) to produce a single combined B adapter, which then projects + the low-rank representation back to the original dimension. It is recommended to set `num_B` to a similar + order as `total_layers / stride_A`. Suggested values: `total_layers / 2`, `total_layers / 3`, or + `total_layers / 4`. Similar to `stride_A`, prefer smaller `num_B` with larger `r` over larger `num_B` with + smaller `r`. NOTE: to train the router, you need at least 2 B adapters (i.e. `num_B >= 2`), since the + router learns to compute a weighted combination of the B adapters. NOTE: the B sharing happens within each + target (layers with the same target suffix). For example, if your target_modules are `['q_proj', 'v_proj']` + and you set `num_B=4`, then there will be 4 B adapters shared across all q_proj layers, and another 4 B + adapters shared across all v_proj layers, but the q_proj and v_proj layers will not share B adapters with + each other since they have different suffixes. + target_modules (`Union[List[str], str]`, *optional*): + The names of the modules to apply Lily to. Can be a list of module name strings (e.g. `['q_proj', + 'v_proj']`) or a regex pattern (e.g. `'.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'`). If not + specified, Lily will be applied to all supported linear layers. + scaling (`float`): + A scalar multiplier applied to the combined adapter output (`scaling * A @ combined_B`) before adding it to + the frozen weight's forward pass. Unlike LoRA, Lily does not use an `alpha / r` formulation; instead, + `scaling` is a direct multiplier. This design makes it straightforward to sweep over values on a log scale + (e.g. `0.01`, `0.1`, `1.0`, `10.0`). The optimal value is task-dependent and should be treated as a + hyperparameter. We recommend starting with `1.0`. + modules_to_save (`List[str]`, *optional*): + List of modules apart from Lily 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. + exclude_modules (`Union[List[str], str]`, *optional*): + 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. + layers_to_transform (`Union[list[int], int]`, *optional*): + The layer indexes to transform, if 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]]`, *optional*): + 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'`. + init_weights (`bool`): + Whether to initialize Lily adapter weights using the default initialization scheme: A matrices are + initialized with Kaiming uniform, and B matrices are initialized to zero, ensuring that the adapter output + is zero at the start of training and does not disturb the pretrained model. It is strongly recommended to + keep this as `True` unless you have a specific reason to change it. + """ + + r: int = field( + default=32, + metadata={ + "help": ( + "Lily's rank. Determines the inner hidden dimension of each adapter and the rank of the " + "weight update `A @ B`. In Lily, since the number of adapters is typically smaller than in LoRA, " + "each adapter needs to carry more capacity, so it is recommended to use a larger `r` than " + "in LoRA — typically `2x`, `3x`, or `4x` the LoRA rank you would normally use. " + "The total number of trainable parameters scales with `r * (total_layers / stride_A + num_B)`, " + "so increasing `r` while keeping `stride_A` large and `num_B` small is the recommended trade-off." + ) + }, + ) + stride_A: int = field( + default=1, + metadata={ + "help": ( + "The number of consecutive layers that share one A adapter. For example, if `stride_A=4`, " + "every 4 adjacent layers share the same A adapter, resulting in `total_layers / stride_A` " + "distinct A adapters in total." + "The A adapter compresses the input into a low-rank representation of size `r`. " + "`stride_A` should be no less than 1." + "Suggested values: `2`, `3`, or `4` (i.e. sharing every 2, 3, or 4 layers). " + "Keeping `stride_A` large (fewer distinct A adapters) and increasing `r` instead leads to " + "better performance than the opposite trade-off (small `stride_A`, small `r`). " + "Setting `stride_A=1` means every layer has its own A adapter." + "Note: A sharing happens within each target module type independently. For example, if " + "`target_modules=['q_proj', 'v_proj']` and `stride_A=2`, then every 2 adjacent `q_proj` " + "layers share one A adapter and every 2 adjacent `v_proj` layers share another A adapter, " + "but `q_proj` and `v_proj` layers never share A adapters with each other." + ) + }, + ) + num_B: int = field( + default=2, + metadata={ + "help": ( + "The number of shared B adapters. Unlike A adapters (which are grouped by layer), " + "all B adapters are shared globally across every layer. For each forward pass, a router " + "computes a weighted combination of all `num_B` B adapters (using softmax-normalized " + "weights) to produce a single combined B adapter, which then projects the low-rank " + "representation back to the original dimension. It is recommended to set `num_B` to a " + "similar order as `total_layers / stride_A`. Suggested values: `total_layers / 2`, " + "`total_layers / 3`, or `total_layers / 4`. Similar to `stride_A`, prefer smaller `num_B` " + "with larger `r` over larger `num_B` with smaller `r`. " + "NOTE: to train the router, you need at least 2 B adapters (i.e. `num_B >= 2`), since the " + "router learns to compute a weighted combination of the B adapters." + "Note: B sharing happens within each target module type independently. For example, if " + "`target_modules=['q_proj', 'v_proj']` and `num_B=4`, then there will be 4 B adapters " + "shared across all `q_proj` layers and another 4 B adapters shared across all `v_proj` " + "layers, but `q_proj` and `v_proj` layers never share B adapters with each other." + ) + }, + ) + scaling: float = field( + default=1.0, + metadata={ + "help": ( + "A scalar multiplier applied to the combined adapter output (`scaling * A @ combined_B`) " + "before adding it to the frozen weight's forward pass. Unlike LoRA, Lily does not use an " + "`alpha / r` formulation; instead, `scaling` is a direct multiplier. This design " + "makes it straightforward to sweep over values on a log scale (e.g. `0.01`, `0.1`, " + "`1.0`, `10.0`). The optimal value is task-dependent and should be treated as a " + "hyperparameter. We recommend starting with `1.0`." + ) + }, + ) + 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 Lily. " + "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'. " + "If not specified, Lily will be applied to all supported linear layers." + ) + }, + ) + 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 Lily. " + "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: Optional[list[str]] = field( + default=None, + metadata={ + "help": ( + "List of modules apart from Lily 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." + ) + }, + ) + layers_to_transform: Optional[Union[list[int], int]] = field( + default=None, + metadata={ + "help": ( + "The layer indexes to transform, if 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'`." + ) + }, + ) + init_weights: bool = field( + default=True, + metadata={ + "help": ( + "Whether to initialize Lily adapter weights using the default initialization scheme: A matrices are " + "initialized with Kaiming uniform, and B matrices are initialized to zero, ensuring that the adapter " + "output is zero at the start of training and does not disturb the pretrained model. It is strongly " + "recommended to keep this as `True` unless you have a specific reason to change it." + ) + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.LILY + 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 + ) + 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.stride_A < 1: + raise ValueError("`stride_A` must be at least 1.") + if self.num_B < 2: + raise ValueError("`num_B` must be at least 2 for the router to be trained.") diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lily/layer.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lily/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..b9f472a4418ee3d88503993b09381f91579ee102 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lily/layer.py @@ -0,0 +1,183 @@ +# Copyright 2026-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 warnings +from typing import Any, Optional + +import torch +import torch.nn.functional as F +from torch import nn + +from peft.tuners.tuners_utils import BaseTunerLayer + +from .config import LilyConfig + + +class LilyLayer(BaseTunerLayer): + # All names of layers that may contain (trainable) adapter weights + adapter_layer_names: tuple[str, ...] = ("lily_A", "lily_B", "lily_router") + # All names of other parameters that may contain adapter-related parameters + other_param_names: tuple[str, ...] = ("r", "scaling", "stride_A", "num_B") + + def __init__(self, base_layer: nn.Module, **kwargs) -> None: + self.base_layer = base_layer + self.r = {} + self.scaling = {} + self.stride_A = {} + self.num_B = {} + self.lily_A = nn.ModuleDict({}) + self.lily_B = nn.ModuleDict({}) + self.lily_router = nn.ModuleDict({}) + self.kwargs = kwargs + + 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: + # 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 update_layer( + self, + adapter_name: str, + r: int, + config: LilyConfig, + lily_A: Optional[nn.Linear] = None, + lily_B: Optional[nn.Linear] = None, + ) -> None: + # collect the kwargs + scaling = config.scaling + stride_A = config.stride_A + num_B = config.num_B + init_weights = config.init_weights + inference_mode = config.inference_mode + + 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] = scaling + + # Actual trainble parameters + self.lily_A[adapter_name] = lily_A if lily_A is not None else nn.Linear(self.in_features, r, bias=False) + self.lily_B[adapter_name] = ( + lily_B if lily_B is not None else nn.Linear(self.out_features, num_B * r, bias=False) + ) + self.lily_router[adapter_name] = nn.Linear(r, num_B, bias=False) + + self.stride_A[adapter_name] = stride_A + self.num_B[adapter_name] = num_B + self.reset_lily_parameters(adapter_name, init_weights=init_weights) # initialize the parameters + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def reset_lily_parameters(self, adapter_name, init_weights: bool = True): + if adapter_name in self.lily_A: + nn.init.kaiming_uniform_(self.lily_A[adapter_name].weight, a=math.sqrt(5)) + nn.init.kaiming_uniform_(self.lily_router[adapter_name].weight, a=math.sqrt(5)) + if not init_weights: + nn.init.kaiming_uniform_(self.lily_B[adapter_name].weight, a=math.sqrt(5)) + else: + nn.init.zeros_(self.lily_B[adapter_name].weight) + + +class Linear(nn.Module, LilyLayer): + # Lily implemented in a dense layer + def __init__( + self, + base_layer, + adapter_name: str, + r: int, + config: LilyConfig, + lily_A: Optional[nn.Linear] = None, + lily_B: Optional[nn.Linear] = None, + **kwargs, + ) -> None: + super().__init__() + LilyLayer.__init__(self, base_layer, **kwargs) + + self._active_adapter = adapter_name + + self.update_layer( + adapter_name, + r, + config=config, + lily_A=lily_A, + lily_B=lily_B, + ) + + 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. + """ + raise NotImplementedError("This method is not supported for Lily.") + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + raise NotImplementedError("This method is not supported for Lily.") + + def unmerge(self) -> None: + raise NotImplementedError("This method is not supported for Lily.") + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + result = self.base_layer(x, *args, **kwargs) + + if self.disable_adapters or not self.active_adapters: + return result + + torch_result_dtype = result.dtype + + lily_A_keys = self.lily_A.keys() + + for active_adapter in self.active_adapters: + if active_adapter not in lily_A_keys: + continue + + lily_A = self.lily_A[active_adapter] + lily_B = self.lily_B[active_adapter] + router = self.lily_router[active_adapter] + num_B = self.num_B[active_adapter] + B = lily_B.weight.reshape(num_B, -1, lily_B.weight.shape[1]) + scaling = self.scaling[active_adapter] + x = self._cast_input_dtype(x, lily_A.weight.dtype) + hidden = lily_A(x) + router_logits = router(hidden) # [B, N, num_of_experts] + router_probability = F.softmax(router_logits, dim=-1) # [B, N, num_of_experts] + expert_probabilities = router_probability.reshape(-1, num_B).mean(dim=0) + combined_B = torch.einsum("e,eio->io", expert_probabilities, B) + delta = torch.matmul(hidden, combined_B) + result = result + (delta * scaling).to(torch_result_dtype) + + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "lily." + rep diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lily/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lily/model.py new file mode 100644 index 0000000000000000000000000000000000000000..ba3b96b5b771aad15cfec6ce0f5781b0eb7bfbbc --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lily/model.py @@ -0,0 +1,163 @@ +# Copyright 2026-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 +from torch import nn + +from peft.tuners.tuners_utils import ( + BaseTuner, + BaseTunerLayer, +) +from peft.utils import TRANSFORMERS_MODELS_TO_LILY_TARGET_MODULES_MAPPING + +from .config import LilyConfig +from .layer import LilyLayer, Linear + + +class LilyModel(BaseTuner): + """ + Creates a Low-Rank Interconnected Adaptation Across Layers (Lily) model from a pretrained transformers model. + + The method is described in detail in https://arxiv.org/abs/2407.09946. + + Args: + model ([`torch.nn.Module`]): The model to be adapted. + config ([`LilyConfig`]): The configuration of the Lily model. + adapter_name (`str`): The name of the adapter, defaults to `"default"`. + + Returns: + `torch.nn.Module`: The Lily PEFT model. + + **Attributes**: + - **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted. + - **peft_config** ([`LilyConfig`]): The configuration of the Lily model. + """ + + prefix: str = "lily_" + tuner_layer_cls = LilyLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_LILY_TARGET_MODULES_MAPPING + + def _create_and_replace( + self, + lily_config, + adapter_name, + target, + target_name, + parent, + current_key, + **optional_kwargs, + ): + """ + Create a new Lily layer with independent A and B for each layer. Sharing of A/B across layers is deferred to + _post_injection_hook. + """ + if current_key is None: + raise ValueError("Current Key shouldn't be `None`") + + if isinstance(target, LilyLayer): + target.update_layer( + adapter_name, + lily_config.r, + config=lily_config, + ) + else: + new_module = self._create_new_module(lily_config, adapter_name, target) + if adapter_name not in self.active_adapters: + new_module.requires_grad_(False) + self._replace_module(parent, target_name, new_module, target) + + @staticmethod + def _create_new_module(lily_config, adapter_name, target): + 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, + r=lily_config.r, + config=lily_config, + ) + + raise NotImplementedError(f"Lily does not support target modules of type {type(target_base_layer)} yet.") + + def _post_injection_hook(self, model: nn.Module, config: LilyConfig, adapter_name: str) -> None: + """ + After all layers have been independently initialized, apply A/B sharing across layers. + + A sharing: for each (target_module_suffix, weight_shape) group, consecutive blocks of `stride_A` layers share + the same A. The first layer in each block keeps its own A; subsequent layers in the block have their lily_A + replaced by the group leader's. + + B sharing: all layers in the same (target_module_suffix, weight_shape) group share the B from the very first + layer in that group. + + Both lily_A and lily_B are nn.Linear modules, so they move correctly with model.to(device) via standard + nn.Module parameter propagation. + + Note: (target_module_suffix, weight_shape) is used as the group key rather than target_module_suffix alone, to + correctly handle architectures like UNet where the same target key can appear with different shapes across + layers. + """ + stride_A = config.stride_A + + # Collect all adapted LilyLayer modules in traversal order, grouped by + # (target_module_suffix, weight_shape). + # Maps (target_suffix, weight_shape) -> list of LilyLayer in traversal order. + target_to_layers: dict[tuple[str, torch.Size], list[LilyLayer]] = {} + + for key, module in model.named_modules(): + if not isinstance(module, LilyLayer): + continue + if adapter_name not in module.lily_A: + continue + + base = module.get_base_layer() + shape = base.weight.shape # (out_features, in_features) + + # Find the longest matching target suffix for this key + matched_suffix = None + if isinstance(config.target_modules, str): + matched_suffix = config.target_modules + else: + for suffix in config.target_modules: + if key.endswith(suffix): + matched_suffix = suffix + + if matched_suffix is None: + # Should not happen since inject_adapter already matched this layer + continue + + group_key = (matched_suffix, shape) + if group_key not in target_to_layers: + target_to_layers[group_key] = [] + target_to_layers[group_key].append(module) + + # Apply A and B sharing for each (target_suffix, shape) group. + for (target_suffix, shape), layers in target_to_layers.items(): + # B sharing: all layers share the first layer's B + shared_B = layers[0].lily_B[adapter_name] + for i, layer in enumerate(layers): + if i != 0: + layer.lily_B[adapter_name] = shared_B + + # A sharing: layers within the same stride_A block share the group leader's A. + # Group leader is the first layer in each block of stride_A consecutive layers. + group_idx = (i // stride_A) * stride_A + if i != group_idx: + layer.lily_A[adapter_name] = layers[group_idx].lily_A[adapter_name] diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/ln_tuning/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/ln_tuning/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8f90a8fb058cf75450b89166bf2e562f07b835fd --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/ln_tuning/__init__.py @@ -0,0 +1,23 @@ +# 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 peft.utils import register_peft_method + +from .config import LNTuningConfig +from .model import LNTuningModel + + +__all__ = ["LNTuningConfig", "LNTuningModel"] + +register_peft_method(name="ln_tuning", config_cls=LNTuningConfig, model_cls=LNTuningModel) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/ln_tuning/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/ln_tuning/config.py new file mode 100644 index 0000000000000000000000000000000000000000..127ee9017333bce22706b58b13701049244b1da9 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/ln_tuning/config.py @@ -0,0 +1,70 @@ +# 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 + +from dataclasses import dataclass, field +from typing import Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class LNTuningConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a :class:`~peft.tuners.LNTuningModel`. + + Args: + target_modules (`Optional[Union[List[str], str]]`): + List of module names or regex expression of the module names to replace with LNTuning. For example, + '.*decoder.*' or '.*encoder.*'. 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. + 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 (`Optional[Union[List[str], str]]`): + List of modules 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. + """ + + 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 LNTuning." + "For example, '.*decoder.*' or '.*encoder.*'. " + "If 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 shoud specify the target modules manually." + ), + }, + ) + 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 LNTuning."}, + ) + modules_to_save: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": "List of modules 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.LN_TUNING diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/ln_tuning/layer.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/ln_tuning/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..e25537060750c27c39cb764f3dcc474aab8257ff --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/ln_tuning/layer.py @@ -0,0 +1,126 @@ +# 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 copy import deepcopy +from typing import Optional + +import torch +from torch import nn + +from peft.tuners.tuners_utils import BaseTunerLayer, _get_in_out_features, check_adapters_to_merge + +from .config import LNTuningConfig + + +class LNTuningLayer(nn.Module, BaseTunerLayer): + """ + Selects a layer from the model. + """ + + adapter_layer_names = ("ln_tuning_layers",) + + def __init__(self, base_layer: nn.Module, adapter_name: str, config: LNTuningConfig): + super().__init__() + self.base_layer = base_layer + self.ln_tuning_layers = nn.ModuleDict({}) + self.update_layer(self.base_layer, adapter_name, config=config) + self._active_adapter = adapter_name + 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 + + def update_layer(self, layer: nn.Module, adapter_name: str, config: LNTuningConfig, **kwargs): + inference_mode = config.inference_mode + self.ln_tuning_layers[adapter_name] = deepcopy(layer) + self.set_adapter(adapter_name, inference_mode=inference_mode) + + def enable_adapters(self, enabled: bool) -> None: + """Toggle the enabling and disabling of adapters + + Takes care of setting the requires_grad flag for the adapter weights. + + Args: + enabled (bool): True to enable adapters, False to disable adapters + """ + if enabled: + self.set_adapter(self.active_adapters) + self._disable_adapters = False + else: + if self.merged: + self.unmerge() + # disable grads on all adapter layers + for layer_name in self.adapter_layer_names: + layer = getattr(self, layer_name) + layer.requires_grad_(False) + self._disable_adapters = True + + def merge(self, adapter_names: Optional[list[str]] = None, safe_merge: bool = False): + # note that there is no actual merging, so whether safe_merge is True or False is irrelevant + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + if len(adapter_names) > 1: + raise ValueError( + f"Trying to merge {len(adapter_names)} adapters, but LN " + f"tuning does not allow merging more than one adapter at a time" + ) + merged_adapters = set(self.merged_adapters) + if merged_adapters: + warnings.warn(f"Already merged with {merged_adapters}. Unmerging first.") + self.unmerge() + + self.base_layer, self.ln_tuning_layers[adapter_names[0]] = ( + self.ln_tuning_layers[adapter_names[0]], + self.base_layer, + ) + self.merged_adapters.append(adapter_names[0]) + + def unmerge(self): + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + # popping one element is sufficient because LN + # tuning does not allow merging more than one adapter at a time. + merged_name = self.merged_adapters.pop() + self.base_layer, self.ln_tuning_layers[merged_name] = ( + self.ln_tuning_layers[merged_name], + self.base_layer, + ) + + 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 or (len(self.active_adapters) == 0): + result = self.base_layer(x, *args, **kwargs) + else: + if len(self.active_adapters) != 1: + raise ValueError( + f"Trying to run forward with {len(self.active_adapters)} active " + f"adapters, but LN tuning does not allow inference with more than one adapter at a time" + ) + active_adapter = self.active_adapters[0] + result = self.ln_tuning_layers[active_adapter](x, *args, **kwargs) + + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "ln_tuning." + rep diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/ln_tuning/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/ln_tuning/model.py new file mode 100644 index 0000000000000000000000000000000000000000..c37ed51e921a1ac558eb1866c15b959d39282ddd --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/ln_tuning/model.py @@ -0,0 +1,137 @@ +# 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 + +from typing import Optional + +from torch.nn.modules import Module +from tqdm import tqdm + +from peft.config import PeftConfig +from peft.tuners.tuners_utils import BaseTuner, _get_submodules +from peft.utils import TRANSFORMERS_MODELS_TO_LNTUNING_TARGET_MODULES_MAPPING + +from .layer import LNTuningLayer + + +class LNTuningModel(BaseTuner): + """ + Creates LayerNorm tuning from a pretrained transformer model. + + The method is described in detail in https://huggingface.co/papers/2312.11420. + + Args: + model ([`torch.nn.Module`]): The model to be adapted. + config ([`LNTuningConfig`]): The configuration of the Lora model. + adapter_name (`str`): The name of the adapter, defaults to `"default"`. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + This option has no effect on LN tuning but exists for consistency with other PEFT methods. + + Returns: + 'torch.nn.Module': The adapted model with LayerNorm tuned on. + + Example: + + ```py + >>> from transformers import AutoModelForCausalLM + >>> from peft import get_peft_model, TaskType, LNTuningConfig + + >>> peft_config = LNTuningConfig( + ... task_type=TaskType.CAUSAL_LM, + ... ) + + >>> model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf") + >>> model = get_peft_model(model, peft_config) + >>> model.print_trainable_parameters() + ``` + + **Attributes**: + - **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted. + - **peft_config** ([`LNTuningConfig`]): The configuration of the Lora model. + """ + + prefix: str = "ln_tuning_" + tuner_layer_cls = LNTuningLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_LNTUNING_TARGET_MODULES_MAPPING + + def _create_and_replace( + self, + peft_config: PeftConfig, + adapter_name: str, + target: Module, + target_name: str, + parent: Module, + current_key: str, + ) -> None: + # replace the original module with a same new module + new_module = self._create_new_module(peft_config, target, adapter_name) + if adapter_name != self.active_adapter: + new_module.requires_grad_(False) + self._replace_module(parent, target_name, new_module, target) + + def _create_new_module( + self, + peft_config: PeftConfig, + target: Module, + adapter_name: str, + ) -> Module: + if not isinstance(target, LNTuningLayer): + new_module = LNTuningLayer(target, adapter_name, config=peft_config) + else: + new_module = target + new_module.update_layer(target.base_layer, adapter_name, config=peft_config) + return new_module + + def _unloading_checks(self, adapter_names: Optional[list[str]]): + adapters_to_consider = adapter_names or self.active_adapters + is_modules_to_save_available = any( + self.peft_config[adapter].modules_to_save for adapter in adapters_to_consider + ) + if is_modules_to_save_available and len(adapters_to_consider) > 1: + raise ValueError("Cannot unload multiple adapters that specify `modules_to_save`.") + + def _unload_and_optionally_merge( + self, + merge=True, + progressbar: bool = False, + safe_merge: bool = False, + adapter_names: Optional[list[str]] = None, + ): + self._unloading_checks(adapter_names) + key_list = [key for key, _ in self.model.named_modules() if self.prefix not in key] + desc = "Unloading adapters " + ("and merging " if merge else "") + "model" + + for key in tqdm(key_list, disable=not progressbar, desc=desc): + try: + parent, target, target_name = _get_submodules(self.model, key) + except AttributeError: + continue + + if hasattr(target, "base_layer"): + if merge: + target.merge(adapter_names) + self._replace_module(parent, target_name, target.get_base_layer(), target) + + # Clean up peft_config from the model since all PEFT modules have been removed. + # This prevents spurious warnings when re-wrapping the model with get_peft_model(). + if hasattr(self.model, "peft_config"): + del self.model.peft_config + + return self.model + + def _cast_adapter_dtype(self, adapter_name: str, autocast_adapter_dtype: bool = True) -> None: + # Note: LN Tuning does not add adapter layers, instead it creates copies of the original layer. For this reason, + # we need to skip adapter autocasting, otherwise we would change the dtype of copies of the original layer, + # resulting in dtype errors down the line. + pass diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/loha/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/loha/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..70dd1545bbd49b0aaa5eafbde05f82b6a04c3d74 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/loha/__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 LoHaConfig +from .layer import Conv2d, Linear, LoHaLayer +from .model import LoHaModel + + +__all__ = ["Conv2d", "Linear", "LoHaConfig", "LoHaLayer", "LoHaModel"] + +register_peft_method(name="loha", config_cls=LoHaConfig, model_cls=LoHaModel, prefix="hada_", is_mixed_compatible=True) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/loha/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/loha/config.py new file mode 100644 index 0000000000000000000000000000000000000000..79c1f630130133c393c18e09a2624795f9353157 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/loha/config.py @@ -0,0 +1,143 @@ +# 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 Optional, Union + +from peft.tuners.lycoris_utils import LycorisConfig +from peft.utils import PeftType + + +@dataclass +class LoHaConfig(LycorisConfig): + """ + This is the configuration class to store the configuration of a [`LoHaModel`]. + + Args: + r (`int`): + LoHa rank. + alpha (`int`): + The alpha parameter for LoHa scaling. + rank_dropout (`float`): + The dropout probability for rank dimension during training. + module_dropout (`float`): + The dropout probability for disabling LoHa modules during training. + use_effective_conv2d (`bool`): + Use parameter effective decomposition for Conv2d (and Conv1d) with ksize > 1 ("Proposition 3" from FedPara + paper). + 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/Conv1D 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. + 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 adapter weights. This defaults to `True`, passing `False` is + discouraged. + 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'`. + rank_pattern (`dict`): + The mapping from layer names or regexp expression to ranks which are different from the default rank + specified by `r`. For example, `{'^model.decoder.layers.0.encoder_attn.k_proj': 16}`. + alpha_pattern (`dict`): + The mapping from layer names or regexp expression to alphas which are different from the default alpha + specified by `alpha`. For example, `{'^model.decoder.layers.0.encoder_attn.k_proj': 16}`. + modules_to_save (`Optional[List[str]]`): + List of modules apart from adapter layers to be set as trainable and saved in the final checkpoint. + """ + + r: int = field(default=8, metadata={"help": "LoHa rank"}) + alpha: int = field(default=8, metadata={"help": "LoHa alpha"}) + rank_dropout: float = field( + default=0.0, metadata={"help": "The dropout probability for rank dimension during training"} + ) + module_dropout: float = field( + default=0.0, metadata={"help": "The dropout probability for disabling LoHa modules during training"} + ) + use_effective_conv2d: bool = field( + default=False, + metadata={ + "help": ( + "Use parameter effective decomposition for Conv2d (and Conv1d) with ksize > 1 " + '("Proposition 3" from FedPara paper)' + ) + }, + ) + 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 LoHa." + "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." + }, + ) + 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 LoHa."}, + ) + init_weights: bool = field( + default=True, + metadata={ + "help": ( + "Whether to initialize the weights of the LoHa 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 LoHA 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.LOHA + 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. ") diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/loha/layer.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/loha/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..7b3a5c24f84b16586f21247cb209f9ea52f572bc --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/loha/layer.py @@ -0,0 +1,435 @@ +# 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.functional as F +from torch import nn + +from peft.tuners.lycoris_utils import LycorisLayer + +from .config import LoHaConfig + + +class LoHaLayer(nn.Module, LycorisLayer): + # All names of layers that may contain adapter weights + adapter_layer_names = ("hada_w1_a", "hada_w1_b", "hada_w2_a", "hada_w2_b", "hada_t1", "hada_t2") + # other_param_names is defined on parent class + + def __init__(self, base_layer: nn.Module): + super().__init__() + LycorisLayer.__init__(self, base_layer) + + # LoHa info + self.hada_w1_a = nn.ParameterDict({}) + self.hada_w1_b = nn.ParameterDict({}) + self.hada_w2_a = nn.ParameterDict({}) + self.hada_w2_b = nn.ParameterDict({}) + self.hada_t1 = nn.ParameterDict({}) + self.hada_t2 = nn.ParameterDict({}) + + @property + def _available_adapters(self) -> set[str]: + return {*self.hada_w1_a, *self.hada_w1_b, *self.hada_w2_a, *self.hada_w2_b, *self.hada_t1, *self.hada_t2} + + def create_adapter_parameters(self, adapter_name: str, r: int, shape: tuple[int, ...]): + # https://github.com/KohakuBlueleaf/LyCORIS/blob/eb460098187f752a5d66406d3affade6f0a07ece/lycoris/modules/loha.py#L130C9-L143C75 + if len(shape) == 4: # Conv2d + self.hada_t1[adapter_name] = nn.Parameter(torch.empty(r, r, shape[2], shape[3])) + self.hada_w1_a[adapter_name] = nn.Parameter(torch.empty(r, shape[0])) # out_dim, 1-mode + self.hada_w1_b[adapter_name] = nn.Parameter(torch.empty(r, shape[1])) # in_dim , 2-mode + + self.hada_t2[adapter_name] = nn.Parameter(torch.empty(r, r, shape[2], shape[3])) + self.hada_w2_a[adapter_name] = nn.Parameter(torch.empty(r, shape[0])) # out_dim, 1-mode + self.hada_w2_b[adapter_name] = nn.Parameter(torch.empty(r, shape[1])) # in_dim , 2-mode + elif len(shape) == 3: # Conv1d + self.hada_t1[adapter_name] = nn.Parameter(torch.empty(r, r, shape[2], 1)) + self.hada_w1_a[adapter_name] = nn.Parameter(torch.empty(r, shape[0])) # out_dim, 1-mode + self.hada_w1_b[adapter_name] = nn.Parameter(torch.empty(r, shape[1])) # in_dim , 2-mode + + self.hada_t2[adapter_name] = nn.Parameter(torch.empty(r, r, shape[2], 1)) + self.hada_w2_a[adapter_name] = nn.Parameter(torch.empty(r, shape[0])) # out_dim, 1-mode + self.hada_w2_b[adapter_name] = nn.Parameter(torch.empty(r, shape[1])) # in_dim , 2-mode + else: # Linear + self.hada_w1_a[adapter_name] = nn.Parameter(torch.empty(shape[0], r)) + self.hada_w1_b[adapter_name] = nn.Parameter(torch.empty(r, shape[1])) + + self.hada_w2_a[adapter_name] = nn.Parameter(torch.empty(shape[0], r)) + self.hada_w2_b[adapter_name] = nn.Parameter(torch.empty(r, shape[1])) + + def reset_adapter_parameters(self, adapter_name: str): + # Original implementation performs initialization with normal distribution + # https://github.com/KohakuBlueleaf/LyCORIS/blob/3549fdef8f564761d68b695a08ef88b1122fdedc/lycoris/modules/loha.py#L158 + + # FedPara paper proposes to perform He initialization, let's stick with it + # It is enough to initialize only single matrix with zeros to make adapter do nothing after initialization + if adapter_name in self.hada_w1_a.keys(): + nn.init.kaiming_uniform_(self.hada_w1_a[adapter_name], a=math.sqrt(5)) + nn.init.kaiming_uniform_(self.hada_w1_b[adapter_name], a=math.sqrt(5)) + nn.init.kaiming_uniform_(self.hada_w2_a[adapter_name], a=math.sqrt(5)) + nn.init.zeros_(self.hada_w2_b[adapter_name]) + if adapter_name in self.hada_t1.keys(): + nn.init.kaiming_uniform_(self.hada_t1[adapter_name], a=math.sqrt(5)) + nn.init.kaiming_uniform_(self.hada_t2[adapter_name], a=math.sqrt(5)) + + def reset_adapter_parameters_random(self, adapter_name: str): + # Original implementation performs initialization with normal distribution + # https://github.com/KohakuBlueleaf/LyCORIS/blob/3549fdef8f564761d68b695a08ef88b1122fdedc/lycoris/modules/loha.py#L158 + + # FedPara paper proposes to perform He initialization, let's stick with it + # It is enough to initialize only single matrix with zeros to make adapter do nothing after initialization + if adapter_name in self.hada_w1_a.keys(): + nn.init.kaiming_uniform_(self.hada_w1_a[adapter_name], a=math.sqrt(5)) + nn.init.kaiming_uniform_(self.hada_w1_b[adapter_name], a=math.sqrt(5)) + nn.init.kaiming_uniform_(self.hada_w2_a[adapter_name], a=math.sqrt(5)) + nn.init.kaiming_uniform_(self.hada_w2_b[adapter_name], a=math.sqrt(5)) + if adapter_name in self.hada_t1.keys(): + nn.init.kaiming_uniform_(self.hada_t1[adapter_name], a=math.sqrt(5)) + nn.init.kaiming_uniform_(self.hada_t2[adapter_name], a=math.sqrt(5)) + + def update_layer( + self, + adapter_name: str, + r: int, + alpha: float, + config: LoHaConfig, + **kwargs, + ) -> None: + """Internal function to create loha adapter + + Args: + adapter_name (`str`): Name for the adapter to add. + r (`int`): Rank for the added adapter. + alpha (`float`): Alpha for the added adapter. + config (`LoHaConfig`): The adapter configuration for this layer. + """ + rank_dropout = config.rank_dropout + module_dropout = config.module_dropout + init_weights = config.init_weights + use_effective_conv2d = config.use_effective_conv2d + inference_mode = config.inference_mode + + 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.alpha[adapter_name] = alpha + self.scaling[adapter_name] = alpha / r + self.rank_dropout[adapter_name] = rank_dropout + self.module_dropout[adapter_name] = module_dropout + + # Determine shape of LoHa weights + base_layer = self.get_base_layer() + if isinstance(base_layer, nn.Linear): + shape = tuple(base_layer.weight.shape) + elif isinstance(base_layer, nn.Conv2d): + # For 1x1 convolutions, disable effective_conv2d to avoid unnecessary tensor reshaping overhead. + # Since 1x1 convolutions are essentially pointwise operations (matrix multiplications), + # they can be more efficiently handled with the flattened weight representation, + # similar to how Linear layers work. This optimization reduces computational cost + # without affecting the mathematical equivalence of the operation. + use_effective_conv2d = use_effective_conv2d and base_layer.kernel_size != (1, 1) + if use_effective_conv2d: + shape = (base_layer.out_channels, base_layer.in_channels, *base_layer.kernel_size) + else: + shape = ( + base_layer.out_channels, + base_layer.in_channels * base_layer.kernel_size[0] * base_layer.kernel_size[1], + ) + elif isinstance(base_layer, nn.Conv1d): + # For Conv1d with kernel_size=1, disable effective_conv2d for the same optimization reasons + # as 1x1 Conv2d. Kernel size 1 means no spatial/temporal context, making it equivalent + # to a Linear layer applied across the channel dimension. Using flattened representation + # avoids unnecessary reshaping and improves computational efficiency. + use_effective_conv2d = use_effective_conv2d and base_layer.kernel_size[0] != 1 + if use_effective_conv2d: + shape = (base_layer.out_channels, base_layer.in_channels, base_layer.kernel_size[0]) + else: + shape = ( + base_layer.out_channels, + base_layer.in_channels * base_layer.kernel_size[0], + ) + else: + raise TypeError(f"LoHa is not implemented for base layers of type {type(base_layer).__name__}") + + # Create weights with provided shape + self.create_adapter_parameters(adapter_name, r, shape) + + # Initialize weights + if init_weights: + self.reset_adapter_parameters(adapter_name) + else: + self.reset_adapter_parameters_random(adapter_name) + + # 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 get_delta_weight(self, adapter_name: str) -> torch.Tensor: + # https://github.com/KohakuBlueleaf/LyCORIS/blob/eb460098187f752a5d66406d3affade6f0a07ece/lycoris/modules/loha.py#L178 + if adapter_name in self.hada_t1.keys(): + weight = make_weight_cp( + self.hada_t1[adapter_name], + self.hada_w1_a[adapter_name], + self.hada_w1_b[adapter_name], + self.hada_t2[adapter_name], + self.hada_w2_a[adapter_name], + self.hada_w2_b[adapter_name], + scale=torch.tensor(self.scaling[adapter_name]), + ) + else: + weight = make_weight( + self.hada_w1_a[adapter_name], + self.hada_w1_b[adapter_name], + self.hada_w2_a[adapter_name], + self.hada_w2_b[adapter_name], + scale=torch.tensor(self.scaling[adapter_name]), + ) + + base_layer = self.get_base_layer() + + # Reshape to match base layer shape + weight = weight.reshape(base_layer.weight.shape) + + # Perform rank dropout during training - drop rows of addition weights + rank_dropout = self.rank_dropout[adapter_name] + if self.training and rank_dropout: + drop = (torch.rand(weight.size(0)) > rank_dropout).to(weight.dtype) + drop = drop.view(-1, *[1] * len(weight.shape[1:])).to(weight.device) + # TODO: Investigate if there should be a scaler like in normal dropout during training + # Original implementation doesn't have it + # https://github.com/KohakuBlueleaf/LyCORIS/blob/eb460098187f752a5d66406d3affade6f0a07ece/lycoris/modules/loha.py#L193 + drop /= drop.mean() + weight *= drop + + return 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: + result = self.base_layer(x, *args, **kwargs) + + # Execute all the adapters + for active_adapter in self.active_adapters: + if active_adapter not in self._available_adapters: + continue + + module_dropout = self.module_dropout[active_adapter] + + # Modify current execution weights + if (not self.training) or (self.training and torch.rand(1) > module_dropout): + result = result + self._get_delta_activations(active_adapter, x, *args, **kwargs) + + result = result.to(previous_dtype) + return result + + +class Linear(LoHaLayer): + """LoHa implemented in Linear layer""" + + def __init__( + self, + base_layer: nn.Module, + adapter_name: str, + config: LoHaConfig, + r: int = 0, + alpha: float = 0.0, + **kwargs, + ): + super().__init__(base_layer) + + # Create adapter and set it active + self._active_adapter = adapter_name + self.update_layer(adapter_name, r, alpha, config=config, **kwargs) + + def _get_delta_activations( + self, adapter_name: str, input: torch.Tensor, *args: Any, **kwargs: Any + ) -> torch.Tensor: + delta_weight = self.get_delta_weight(adapter_name) + input = self._cast_input_dtype(input, delta_weight.dtype) + # don't add bias here, because the bias is already included in the output of the base_layer + return F.linear(input, delta_weight) + + def supports_lora_conversion(self, adapter_name: str = "default") -> bool: + return True + + def __repr__(self) -> str: + rep = super().__repr__() + return "loha." + rep + + +class Conv2d(LoHaLayer): + """LoHa implemented in Conv2d layer""" + + def __init__( + self, + base_layer: nn.Module, + adapter_name: str, + config: LoHaConfig, + r: int = 0, + alpha: float = 0.0, + **kwargs, + ): + super().__init__(base_layer) + + # Create adapter and set it active + self._active_adapter = adapter_name + self.update_layer(adapter_name, r, alpha, config=config, **kwargs) + + def _get_delta_activations( + self, adapter_name: str, input: torch.Tensor, *args: Any, **kwargs: Any + ) -> torch.Tensor: + delta_weight = self.get_delta_weight(adapter_name) + input = self._cast_input_dtype(input, delta_weight.dtype) + # don't add bias here, because the bias is already included in the output of the base_layer + base_layer = self.get_base_layer() + return F.conv2d( + input, + delta_weight, + stride=base_layer.stride, + padding=base_layer.padding, + dilation=base_layer.dilation, + groups=base_layer.groups, + ) + + def __repr__(self) -> str: + rep = super().__repr__() + return "loha." + rep + + +class Conv1d(LoHaLayer): + """LoHa implemented in Conv1d layer""" + + def __init__( + self, + base_layer: nn.Module, + adapter_name: str, + config: LoHaConfig, + r: int = 0, + alpha: float = 0.0, + **kwargs, + ): + super().__init__(base_layer) + + # Create adapter and set it active + self._active_adapter = adapter_name + self.update_layer(adapter_name, r, alpha, config=config, **kwargs) + + def _get_delta_activations( + self, adapter_name: str, input: torch.Tensor, *args: Any, **kwargs: Any + ) -> torch.Tensor: + delta_weight = self.get_delta_weight(adapter_name) + input = self._cast_input_dtype(input, delta_weight.dtype) + # don't add bias here, because the bias is already included in the output of the base_layer + base_layer = self.get_base_layer() + return F.conv1d( + input, + delta_weight, + stride=base_layer.stride, + padding=base_layer.padding, + dilation=base_layer.dilation, + groups=base_layer.groups, + ) + + def __repr__(self) -> str: + rep = super().__repr__() + return "loha." + rep + + +# Below code is a direct copy from https://github.com/KohakuBlueleaf/LyCORIS/blob/eb460098187f752a5d66406d3affade6f0a07ece/lycoris/modules/loha.py#L9 + + +class HadaWeight(torch.autograd.Function): + @staticmethod + def forward(ctx, w1a, w1b, w2a, w2b, scale=torch.tensor(1)): # noqa: B008 + ctx.save_for_backward(w1a, w1b, w2a, w2b, scale) + diff_weight = ((w1a @ w1b) * (w2a @ w2b)) * scale + return diff_weight + + @staticmethod + def backward(ctx, grad_out): + (w1a, w1b, w2a, w2b, scale) = ctx.saved_tensors + grad_out = grad_out * scale + temp = grad_out * (w2a @ w2b) + grad_w1a = temp @ w1b.T + grad_w1b = w1a.T @ temp + + temp = grad_out * (w1a @ w1b) + grad_w2a = temp @ w2b.T + grad_w2b = w2a.T @ temp + + del temp + return grad_w1a, grad_w1b, grad_w2a, grad_w2b, None + + +class HadaWeightCP(torch.autograd.Function): + @staticmethod + def forward(ctx, t1, w1a, w1b, t2, w2a, w2b, scale=torch.tensor(1)): # noqa: B008 + ctx.save_for_backward(t1, w1a, w1b, t2, w2a, w2b, scale) + + rebuild1 = torch.einsum("i j k l, j r, i p -> p r k l", t1, w1b, w1a) + rebuild2 = torch.einsum("i j k l, j r, i p -> p r k l", t2, w2b, w2a) + + return rebuild1 * rebuild2 * scale + + @staticmethod + def backward(ctx, grad_out): + (t1, w1a, w1b, t2, w2a, w2b, scale) = ctx.saved_tensors + grad_out = grad_out * scale + + temp = torch.einsum("i j k l, j r -> i r k l", t2, w2b) + rebuild = torch.einsum("i j k l, i r -> r j k l", temp, w2a) + + grad_w = rebuild * grad_out + del rebuild + + grad_w1a = torch.einsum("r j k l, i j k l -> r i", temp, grad_w) + grad_temp = torch.einsum("i j k l, i r -> r j k l", grad_w, w1a.T) + del grad_w, temp + + grad_w1b = torch.einsum("i r k l, i j k l -> r j", t1, grad_temp) + grad_t1 = torch.einsum("i j k l, j r -> i r k l", grad_temp, w1b.T) + del grad_temp + + temp = torch.einsum("i j k l, j r -> i r k l", t1, w1b) + rebuild = torch.einsum("i j k l, i r -> r j k l", temp, w1a) + + grad_w = rebuild * grad_out + del rebuild + + grad_w2a = torch.einsum("r j k l, i j k l -> r i", temp, grad_w) + grad_temp = torch.einsum("i j k l, i r -> r j k l", grad_w, w2a.T) + del grad_w, temp + + grad_w2b = torch.einsum("i r k l, i j k l -> r j", t2, grad_temp) + grad_t2 = torch.einsum("i j k l, j r -> i r k l", grad_temp, w2b.T) + del grad_temp + return grad_t1, grad_w1a, grad_w1b, grad_t2, grad_w2a, grad_w2b, None + + +def make_weight(w1a, w1b, w2a, w2b, scale): + return HadaWeight.apply(w1a, w1b, w2a, w2b, scale) + + +def make_weight_cp(t1, w1a, w1b, t2, w2a, w2b, scale): + return HadaWeightCP.apply(t1, w1a, w1b, t2, w2a, w2b, scale) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/loha/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/loha/model.py new file mode 100644 index 0000000000000000000000000000000000000000..0efd7c480f6916d70d4b51a9a4919cfac758a992 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/loha/model.py @@ -0,0 +1,117 @@ +# 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 Union + +import torch +from torch import nn + +from peft.tuners.lycoris_utils import LycorisConfig, LycorisTuner +from peft.utils import TRANSFORMERS_MODELS_TO_LOHA_TARGET_MODULES_MAPPING +from peft.utils.other import get_pattern_key + +from .layer import Conv1d, Conv2d, Linear, LoHaLayer + + +class LoHaModel(LycorisTuner): + """ + Creates Low-Rank Hadamard Product model from a pretrained model. The method is partially described in + https://huggingface.co/papers/2108.06098 Current implementation heavily borrows from + https://github.com/KohakuBlueleaf/LyCORIS/blob/eb460098187f752a5d66406d3affade6f0a07ece/lycoris/modules/loha.py + + Args: + model (`torch.nn.Module`): The model to which the adapter tuner layers will be attached. + config ([`LoHaConfig`]): The configuration of the LoHa 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 LoHa model. + + Example: + ```py + >>> from diffusers import StableDiffusionPipeline + >>> from peft import LoHaModel, LoHaConfig + + >>> config_te = LoHaConfig( + ... r=8, + ... lora_alpha=32, + ... target_modules=["k_proj", "q_proj", "v_proj", "out_proj", "fc1", "fc2"], + ... rank_dropout=0.0, + ... module_dropout=0.0, + ... init_weights=True, + ... ) + >>> config_unet = LoHaConfig( + ... r=8, + ... lora_alpha=32, + ... target_modules=[ + ... "proj_in", + ... "proj_out", + ... "to_k", + ... "to_q", + ... "to_v", + ... "to_out.0", + ... "ff.net.0.proj", + ... "ff.net.2", + ... ], + ... rank_dropout=0.0, + ... module_dropout=0.0, + ... init_weights=True, + ... use_effective_conv2d=True, + ... ) + + >>> model = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5") + >>> model.text_encoder = LoHaModel(model.text_encoder, config_te, "default") + >>> model.unet = LoHaModel(model.unet, config_unet, "default") + ``` + + **Attributes**: + - **model** ([`~torch.nn.Module`]) -- The model to be adapted. + - **peft_config** ([`LoHaConfig`]): The configuration of the LoHa model. + """ + + prefix: str = "hada_" + tuner_layer_cls = LoHaLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_LOHA_TARGET_MODULES_MAPPING + layers_mapping: dict[type[torch.nn.Module], type[LoHaLayer]] = { + torch.nn.Conv2d: Conv2d, + torch.nn.Conv1d: Conv1d, + torch.nn.Linear: Linear, + } + + def _create_and_replace( + self, + config: LycorisConfig, + adapter_name: str, + target: Union[LoHaLayer, 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. + """ + r_key = get_pattern_key(config.rank_pattern.keys(), current_key) + alpha_key = get_pattern_key(config.alpha_pattern.keys(), current_key) + kwargs = { + "r": config.rank_pattern.get(r_key, config.r), + "alpha": config.alpha_pattern.get(alpha_key, config.alpha), + } + + if isinstance(target, LoHaLayer): + target.update_layer(adapter_name, config=config, **kwargs) + else: + new_module = self._create_new_module(config, adapter_name, target, **kwargs) + self._replace_module(parent, target_name, new_module, target) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lokr/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lokr/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f4fe0e92c6eacd0cc276ad3584230ea58ee4a8a6 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lokr/__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 LoKrConfig +from .layer import Conv2d, Linear, LoKrLayer +from .model import LoKrModel + + +__all__ = ["Conv2d", "Linear", "LoKrConfig", "LoKrLayer", "LoKrModel"] + +register_peft_method(name="lokr", config_cls=LoKrConfig, model_cls=LoKrModel, is_mixed_compatible=True) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lokr/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lokr/config.py new file mode 100644 index 0000000000000000000000000000000000000000..6d25dc5c129f711b59e848a38a63fac766d78754 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lokr/config.py @@ -0,0 +1,155 @@ +# 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.tuners.lycoris_utils import LycorisConfig +from peft.utils import PeftType + + +@dataclass +class LoKrConfig(LycorisConfig): + """ + Configuration class of [`LoKrModel`]. + + Args: + r (`int`): + LoKr rank. + alpha (`int`): + The alpha parameter for LoKr scaling. + rank_dropout (`float`): + The dropout probability for rank dimension during training. + module_dropout (`float`): + The dropout probability for disabling LoKr modules during training. + use_effective_conv2d (`bool`): + Use parameter effective decomposition for Conv2d (and Conv1d) with ksize > 1 ("Proposition 3" from FedPara + paper). + decompose_both (`bool`): + Perform rank decomposition of left kronecker product matrix. + decompose_factor (`int`): + Kronecker product decomposition factor. + rank_dropout_scale ('bool) + Whether to scale the rank dropout while training, defaults to `False`. + 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/Conv1D 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. + 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 adapter weights. This defaults to `True`. Use "lycoris" to initialize + weights in the style of the LYCORIS repository. Passing `False` is discouraged. + 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'`. + rank_pattern (`dict`): + The mapping from layer names or regexp expression to ranks which are different from the default rank + specified by `r`. For example, `{'^model.decoder.layers.0.encoder_attn.k_proj': 16}`. + alpha_pattern (`dict`): + The mapping from layer names or regexp expression to alphas which are different from the default alpha + specified by `alpha`. For example, `{'^model.decoder.layers.0.encoder_attn.k_proj': 16}`. + modules_to_save (`Optional[List[str]]`): + List of modules apart from adapter layers to be set as trainable and saved in the final checkpoint. + """ + + r: int = field(default=8, metadata={"help": "LoKr rank"}) + alpha: int = field(default=8, metadata={"help": "LoKr alpha"}) + rank_dropout: float = field( + default=0.0, metadata={"help": "The dropout probability for rank dimension during training"} + ) + module_dropout: float = field( + default=0.0, metadata={"help": "The dropout probability for disabling LoKr modules during training"} + ) + use_effective_conv2d: bool = field( + default=False, + metadata={ + "help": ( + "Use parameter effective decomposition for Conv2d (and Conv1d) with ksize > 1 " + '("Proposition 3" from FedPara paper)' + ) + }, + ) + decompose_both: bool = field( + default=False, + metadata={"help": "Perform rank decomposition of left kronecker product matrix."}, + ) + decompose_factor: int = field(default=-1, metadata={"help": "Kronecker product decomposition factor."}) + rank_dropout_scale: bool = field(default=False, metadata={"help": "Rank dropout scale"}) + 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 LoKr." + "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." + }, + ) + 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 LoKr."}, + ) + init_weights: Union[bool, Literal["lycoris"]] = field( + default=True, + metadata={ + "help": ( + "Whether to initialize the weights of the LoKr layers with their default initialization. Can be True, False or 'lycoris'." + "Default is True. Don't change this setting to False, 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 LoKr 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.LOKR + 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. ") diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lokr/layer.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lokr/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..ecc2696abbaa76d4cfc40901137026bb6cd59f49 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lokr/layer.py @@ -0,0 +1,501 @@ +# 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, Optional, Union + +import torch +import torch.nn.functional as F +from torch import nn + +from peft.tuners.lycoris_utils import LycorisLayer + +from .config import LoKrConfig + + +class LoKrLayer(nn.Module, LycorisLayer): + # All names of layers that may contain adapter weights + adapter_layer_names = ( + "lokr_w1", + "lokr_w1_a", + "lokr_w1_b", + "lokr_w2", + "lokr_w2_a", + "lokr_w2_b", + "lokr_t2", + ) + # other_param_names is defined on parent class + + def __init__(self, base_layer: nn.Module) -> None: + super().__init__() + LycorisLayer.__init__(self, base_layer) + + # LoKr info + self.lokr_w1 = nn.ParameterDict({}) + self.lokr_w1_a = nn.ParameterDict({}) + self.lokr_w1_b = nn.ParameterDict({}) + self.lokr_w2 = nn.ParameterDict({}) + self.lokr_w2_a = nn.ParameterDict({}) + self.lokr_w2_b = nn.ParameterDict({}) + self.lokr_t2 = nn.ParameterDict({}) + + @property + def _available_adapters(self) -> set[str]: + return { + *self.lokr_w1, + *self.lokr_w1_a, + *self.lokr_w1_b, + *self.lokr_w2, + *self.lokr_w2_a, + *self.lokr_w2_b, + *self.lokr_t2, + } + + def create_adapter_parameters( + self, + adapter_name: str, + r: int, + shape, + use_w1: bool, + use_w2: bool, + use_effective_conv2d: bool, + ): + if use_w1: + self.lokr_w1[adapter_name] = nn.Parameter(torch.empty(shape[0][0], shape[1][0])) + else: + self.lokr_w1_a[adapter_name] = nn.Parameter(torch.empty(shape[0][0], r)) + self.lokr_w1_b[adapter_name] = nn.Parameter(torch.empty(r, shape[1][0])) + + # Handle both Conv2d and Conv1d + if len(shape) == 4: # Conv2d + if use_w2: + self.lokr_w2[adapter_name] = nn.Parameter(torch.empty(shape[0][1], shape[1][1], *shape[2:])) + elif use_effective_conv2d: + self.lokr_t2[adapter_name] = nn.Parameter(torch.empty(r, r, shape[2], shape[3])) + self.lokr_w2_a[adapter_name] = nn.Parameter(torch.empty(r, shape[0][1])) # b, 1-mode + self.lokr_w2_b[adapter_name] = nn.Parameter(torch.empty(r, shape[1][1])) # d, 2-mode + else: + self.lokr_w2_a[adapter_name] = nn.Parameter(torch.empty(shape[0][1], r)) + self.lokr_w2_b[adapter_name] = nn.Parameter(torch.empty(r, shape[1][1] * shape[2] * shape[3])) + elif len(shape) == 3: # Conv1d + if use_w2: + self.lokr_w2[adapter_name] = nn.Parameter(torch.empty(shape[0][1], shape[1][1], shape[2])) + elif use_effective_conv2d: # Even for Conv1d, use the effective parameter for kernel dimension + # We pass (r, r, kernel_size, 1) in order to be compatible with the 2d assumptions made + # in make_weight_cp (only relevant for the effective conv2d case). + self.lokr_t2[adapter_name] = nn.Parameter(torch.empty(r, r, shape[2], 1)) + self.lokr_w2_a[adapter_name] = nn.Parameter(torch.empty(r, shape[0][1])) # b, 1-mode + self.lokr_w2_b[adapter_name] = nn.Parameter(torch.empty(r, shape[1][1])) # d, 2-mode + else: + self.lokr_w2_a[adapter_name] = nn.Parameter(torch.empty(shape[0][1], r)) + self.lokr_w2_b[adapter_name] = nn.Parameter(torch.empty(r, shape[1][1] * shape[2])) + else: + # Linear + if use_w2: + self.lokr_w2[adapter_name] = nn.Parameter(torch.empty(shape[0][1], shape[1][1])) + else: + self.lokr_w2_a[adapter_name] = nn.Parameter(torch.empty(shape[0][1], r)) + self.lokr_w2_b[adapter_name] = nn.Parameter(torch.empty(r, shape[1][1])) + + def reset_adapter_parameters(self, adapter_name: str): + if adapter_name in self.lokr_w1: + nn.init.zeros_(self.lokr_w1[adapter_name]) + else: + nn.init.zeros_(self.lokr_w1_a[adapter_name]) + nn.init.kaiming_uniform_(self.lokr_w1_b[adapter_name], a=math.sqrt(5)) + + if adapter_name in self.lokr_w2: + nn.init.kaiming_uniform_(self.lokr_w2[adapter_name], a=math.sqrt(5)) + else: + nn.init.kaiming_uniform_(self.lokr_w2_a[adapter_name], a=math.sqrt(5)) + nn.init.kaiming_uniform_(self.lokr_w2_b[adapter_name], a=math.sqrt(5)) + + if adapter_name in self.lokr_t2: + nn.init.kaiming_uniform_(self.lokr_t2[adapter_name], a=math.sqrt(5)) + + def reset_adapter_parameters_random(self, adapter_name: str): + if adapter_name in self.lokr_w1: + nn.init.kaiming_uniform_(self.lokr_w1[adapter_name], a=math.sqrt(5)) + else: + nn.init.kaiming_uniform_(self.lokr_w1_a[adapter_name], a=math.sqrt(5)) + nn.init.kaiming_uniform_(self.lokr_w1_b[adapter_name], a=math.sqrt(5)) + + if adapter_name in self.lokr_w2: + nn.init.kaiming_uniform_(self.lokr_w2[adapter_name], a=math.sqrt(5)) + else: + nn.init.kaiming_uniform_(self.lokr_w2_a[adapter_name], a=math.sqrt(5)) + nn.init.kaiming_uniform_(self.lokr_w2_b[adapter_name], a=math.sqrt(5)) + + if adapter_name in self.lokr_t2: + nn.init.kaiming_uniform_(self.lokr_t2[adapter_name], a=math.sqrt(5)) + + # Initializes weight matrices similar to the way initialized in the LyCORIS repository. + def reset_adapter_parameters_lycoris_way(self, adapter_name): + if adapter_name in self.lokr_w1: + nn.init.kaiming_uniform_(self.lokr_w1[adapter_name], a=math.sqrt(5)) + else: + nn.init.kaiming_uniform_(self.lokr_w1_a[adapter_name], a=math.sqrt(5)) + nn.init.kaiming_uniform_(self.lokr_w1_b[adapter_name], a=math.sqrt(5)) + + if adapter_name in self.lokr_w2: + nn.init.zeros_(self.lokr_w2[adapter_name]) + else: + nn.init.zeros_(self.lokr_w2_b[adapter_name]) + nn.init.kaiming_uniform_(self.lokr_w2_a[adapter_name], a=math.sqrt(5)) + + if adapter_name in self.lokr_t2: + nn.init.kaiming_uniform_(self.lokr_t2[adapter_name], a=math.sqrt(5)) + + def update_layer( + self, + adapter_name: str, + r: int, + alpha: float, + config: LoKrConfig, + **kwargs, + ) -> None: + """Internal function to create lokr adapter + + Args: + adapter_name (`str`): Name for the adapter to add. + r (`int`): Rank for the added adapter. + alpha (`float`): Alpha for the added adapter. + config (`LoKrConfig`): The adapter configuration for this layer. + """ + rank_dropout = config.rank_dropout + module_dropout = config.module_dropout + init_weights = config.init_weights + use_effective_conv2d = config.use_effective_conv2d + decompose_both = config.decompose_both + decompose_factor = config.decompose_factor + inference_mode = config.inference_mode + + 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.alpha[adapter_name] = alpha + self.scaling[adapter_name] = alpha / r + self.rank_dropout[adapter_name] = rank_dropout + self.module_dropout[adapter_name] = module_dropout + self.rank_dropout_scale[adapter_name] = config.rank_dropout_scale + base_layer = self.get_base_layer() + + # Determine shape of LoKr weights + if isinstance(base_layer, nn.Linear): + in_dim, out_dim = base_layer.in_features, base_layer.out_features + + in_m, in_n = factorization(in_dim, decompose_factor) + out_l, out_k = factorization(out_dim, decompose_factor) + shape = ((out_l, out_k), (in_m, in_n)) # ((a, b), (c, d)), out_dim = a*c, in_dim = b*d + + use_w1 = not (decompose_both and r < max(shape[0][0], shape[1][0]) / 2) + use_w2 = not (r < max(shape[0][1], shape[1][1]) / 2) + use_effective_conv2d = False + elif isinstance(base_layer, nn.Conv2d): + in_dim, out_dim = base_layer.in_channels, base_layer.out_channels + k_size = base_layer.kernel_size + + in_m, in_n = factorization(in_dim, decompose_factor) + out_l, out_k = factorization(out_dim, decompose_factor) + shape = ((out_l, out_k), (in_m, in_n), *k_size) # ((a, b), (c, d), *k_size) + + use_w1 = not (decompose_both and r < max(shape[0][0], shape[1][0]) / 2) + use_w2 = r >= max(shape[0][1], shape[1][1]) / 2 + # For 1x1 convolutions, disable effective_conv2d to avoid unnecessary tensor reshaping overhead. + # Since 1x1 convolutions are essentially pointwise operations (matrix multiplications), + # they can be more efficiently handled with the flattened weight representation, + # similar to how Linear layers work. This optimization reduces computational cost + # without affecting the mathematical equivalence of the operation. + use_effective_conv2d = use_effective_conv2d and base_layer.kernel_size != (1, 1) + elif isinstance(base_layer, nn.Conv1d): + in_dim, out_dim = base_layer.in_channels, base_layer.out_channels + k_size = (base_layer.kernel_size[0],) # Convert to a tuple with single element + + in_m, in_n = factorization(in_dim, decompose_factor) + out_l, out_k = factorization(out_dim, decompose_factor) + shape = ((out_l, out_k), (in_m, in_n), *k_size) # ((a, b), (c, d), k) + + use_w1 = not (decompose_both and r < max(shape[0][0], shape[1][0]) / 2) + use_w2 = r >= max(shape[0][1], shape[1][1]) / 2 + # For Conv1d with kernel_size=1, disable effective_conv2d for the same optimization reasons + # as 1x1 Conv2d. Kernel size 1 means no spatial/temporal context, making it equivalent + # to a Linear layer applied across the channel dimension. Using flattened representation + # avoids unnecessary reshaping and improves computational efficiency. + use_effective_conv2d = use_effective_conv2d and base_layer.kernel_size[0] != 1 + else: + raise TypeError(f"LoKr is not implemented for base layers of type {type(base_layer).__name__}") + + # Create weights with provided shape + self.create_adapter_parameters(adapter_name, r, shape, use_w1, use_w2, use_effective_conv2d) + + # Initialize weights + if init_weights: + if init_weights == "lycoris": + self.reset_adapter_parameters_lycoris_way(adapter_name) + else: + self.reset_adapter_parameters(adapter_name) + else: + self.reset_adapter_parameters_random(adapter_name) + + # 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 get_delta_weight(self, adapter_name: str) -> torch.Tensor: + # https://github.com/KohakuBlueleaf/LyCORIS/blob/e4259b870d3354a9615a96be61cb5d07455c58ea/lycoris/modules/lokr.py#L224 + if adapter_name in self.lokr_w1: + w1 = self.lokr_w1[adapter_name] + else: + w1 = self.lokr_w1_a[adapter_name] @ self.lokr_w1_b[adapter_name] + + if adapter_name in self.lokr_w2: + w2 = self.lokr_w2[adapter_name] + elif adapter_name in self.lokr_t2: + w2 = make_weight_cp(self.lokr_t2[adapter_name], self.lokr_w2_a[adapter_name], self.lokr_w2_b[adapter_name]) + else: + w2 = self.lokr_w2_a[adapter_name] @ self.lokr_w2_b[adapter_name] + + # Make weights with Kronecker product + weight = make_kron(w1, w2, self.scaling[adapter_name]) + + # Get base layer for reshaping + base_layer = self.get_base_layer() + + # Regular reshape to match base layer shape + weight = weight.reshape(base_layer.weight.shape) + + # Perform rank dropout during training - drop rows of addition weights + rank_dropout = self.rank_dropout[adapter_name] + if self.training and rank_dropout: + drop = (torch.rand(weight.size(0)) > rank_dropout).float() + drop = drop.view(-1, *[1] * len(weight.shape[1:])).to(weight.device) + if self.rank_dropout_scale[adapter_name]: + drop /= drop.mean() + weight *= drop + + return 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: + result = self.base_layer(x, *args, **kwargs) + + # Execute all the adapters + for active_adapter in self.active_adapters: + if active_adapter not in self._available_adapters: + continue + + module_dropout = self.module_dropout[active_adapter] + + # Modify current execution weights + if (not self.training) or (self.training and torch.rand(1) > module_dropout): + result = result + self._get_delta_activations(active_adapter, x, *args, **kwargs) + + result = result.to(previous_dtype) + return result + + +class Linear(LoKrLayer): + """LoKr implemented in Linear layer""" + + def __init__( + self, + base_layer: nn.Module, + adapter_name: str, + config: LoKrConfig, + device: Optional[Union[str, torch.device]] = None, + dtype: Optional[torch.dtype] = None, + r: int = 0, + alpha: float = 0.0, + **kwargs, + ): + super().__init__(base_layer) + + # Create adapter and set it active + self._active_adapter = adapter_name + self.update_layer(adapter_name, r, alpha, config=config, **kwargs) + + def _get_delta_activations( + self, adapter_name: str, input: torch.Tensor, *args: Any, **kwargs: Any + ) -> torch.Tensor: + delta_weight = self.get_delta_weight(adapter_name) + input = self._cast_input_dtype(input, delta_weight.dtype) + # don't add bias here, because the bias is already included in the output of the base_layer + return F.linear(input, delta_weight) + + def supports_lora_conversion(self, adapter_name: str = "default") -> bool: + return True + + def __repr__(self) -> str: + rep = super().__repr__() + return "lokr." + rep + + +class Conv2d(LoKrLayer): + """LoKr implemented in Conv2d layer""" + + def __init__( + self, + base_layer: nn.Module, + adapter_name: str, + config: LoKrConfig, + device: Optional[Union[str, torch.device]] = None, + dtype: Optional[torch.dtype] = None, + r: int = 0, + alpha: float = 0.0, + **kwargs, + ): + super().__init__(base_layer) + + # Create adapter and set it active + self._active_adapter = adapter_name + self.update_layer(adapter_name, r, alpha, config=config, **kwargs) + + def _get_delta_activations( + self, adapter_name: str, input: torch.Tensor, *args: Any, **kwargs: Any + ) -> torch.Tensor: + delta_weight = self.get_delta_weight(adapter_name) + input = self._cast_input_dtype(input, delta_weight.dtype) + # don't add bias here, because the bias is already included in the output of the base_layer + base_layer = self.get_base_layer() + return F.conv2d( + input, + delta_weight, + stride=base_layer.stride, + padding=base_layer.padding, + dilation=base_layer.dilation, + groups=base_layer.groups, + ) + + def __repr__(self) -> str: + rep = super().__repr__() + return "lokr." + rep + + +class Conv1d(LoKrLayer): + """LoKr implemented in Conv1d layer""" + + def __init__( + self, + base_layer: nn.Module, + adapter_name: str, + config: LoKrConfig, + device: Optional[Union[str, torch.device]] = None, + dtype: Optional[torch.dtype] = None, + r: int = 0, + alpha: float = 0.0, + **kwargs, + ): + super().__init__(base_layer) + + # Create adapter and set it active + self._active_adapter = adapter_name + self.update_layer(adapter_name, r, alpha, config=config, **kwargs) + + def _get_delta_activations( + self, adapter_name: str, input: torch.Tensor, *args: Any, **kwargs: Any + ) -> torch.Tensor: + delta_weight = self.get_delta_weight(adapter_name) + input = self._cast_input_dtype(input, delta_weight.dtype) + # don't add bias here, because the bias is already included in the output of the base_layer + base_layer = self.get_base_layer() + return F.conv1d( + input, + delta_weight, + stride=base_layer.stride, + padding=base_layer.padding, + dilation=base_layer.dilation, + groups=base_layer.groups, + ) + + def __repr__(self) -> str: + rep = super().__repr__() + return "lokr." + rep + + +# Below code is a direct copy from https://github.com/KohakuBlueleaf/LyCORIS/blob/eb460098187f752a5d66406d3affade6f0a07ece/lycoris/modules/lokr.py#L11 + + +def factorization(dimension: int, factor: int = -1) -> tuple[int, int]: + """Factorizes the provided number into the product of two numbers + + Args: + dimension (`int`): The number that needs to be factorized. + factor (`int`, optional): + Factorization divider. The algorithm will try to output two numbers, one of each will be as close to the + factor as possible. If -1 is provided, the decomposition algorithm would try to search dividers near the + square root of the dimension. Defaults to -1. + + Returns: + Tuple[`int`, `int`]: A tuple of two numbers, whose product is equal to the provided number. The first number is + always less than or equal to the second. + + Example: + ```py + >>> factorization(256, factor=-1) + (16, 16) + + >>> factorization(128, factor=-1) + (8, 16) + + >>> factorization(127, factor=-1) + (1, 127) + + >>> factorization(128, factor=4) + (4, 32) + ``` + """ + + if factor > 0 and (dimension % factor) == 0: + m = factor + n = dimension // factor + return m, n + if factor == -1: + factor = dimension + m, n = 1, dimension + length = m + n + while m < n: + new_m = m + 1 + while dimension % new_m != 0: + new_m += 1 + new_n = dimension // new_m + if new_m + new_n > length or new_m > factor: + break + else: + m, n = new_m, new_n + if m > n: + n, m = m, n + return m, n + + +def make_weight_cp(t, wa, wb): + rebuild2 = torch.einsum("i j k l, i p, j r -> p r k l", t, wa, wb) # [c, d, k1, k2] + return rebuild2 + + +def make_kron(w1, w2, scale=1.0): + if len(w2.shape) == 4: + w1 = w1.unsqueeze(2).unsqueeze(2) + w2 = w2.contiguous() + rebuild = torch.kron(w1, w2) + + return rebuild * scale diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lokr/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lokr/model.py new file mode 100644 index 0000000000000000000000000000000000000000..7cca89895be622ca559d90fbd01d814e891c3379 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lokr/model.py @@ -0,0 +1,118 @@ +# 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 Union + +import torch +from torch import nn + +from peft.tuners.lycoris_utils import LycorisConfig, LycorisTuner +from peft.utils import TRANSFORMERS_MODELS_TO_LOKR_TARGET_MODULES_MAPPING +from peft.utils.other import get_pattern_key + +from .layer import Conv1d, Conv2d, Linear, LoKrLayer + + +class LoKrModel(LycorisTuner): + """ + Creates Low-Rank Kronecker Product model from a pretrained model. The original method is partially described in + https://huggingface.co/papers/2108.06098 and in https://huggingface.co/papers/2309.14859 Current implementation + heavily borrows from + https://github.com/KohakuBlueleaf/LyCORIS/blob/eb460098187f752a5d66406d3affade6f0a07ece/lycoris/modules/lokr.py + + Args: + model (`torch.nn.Module`): The model to which the adapter tuner layers will be attached. + config ([`LoKrConfig`]): The configuration of the LoKr 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 LoKr model. + + Example: + ```py + >>> from diffusers import StableDiffusionPipeline + >>> from peft import LoKrModel, LoKrConfig + + >>> config_te = LoKrConfig( + ... r=8, + ... lora_alpha=32, + ... target_modules=["k_proj", "q_proj", "v_proj", "out_proj", "fc1", "fc2"], + ... rank_dropout=0.0, + ... module_dropout=0.0, + ... init_weights=True, + ... ) + >>> config_unet = LoKrConfig( + ... r=8, + ... lora_alpha=32, + ... target_modules=[ + ... "proj_in", + ... "proj_out", + ... "to_k", + ... "to_q", + ... "to_v", + ... "to_out.0", + ... "ff.net.0.proj", + ... "ff.net.2", + ... ], + ... rank_dropout=0.0, + ... module_dropout=0.0, + ... init_weights=True, + ... use_effective_conv2d=True, + ... ) + + >>> model = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5") + >>> model.text_encoder = LoKrModel(model.text_encoder, config_te, "default") + >>> model.unet = LoKrModel(model.unet, config_unet, "default") + ``` + + **Attributes**: + - **model** ([`~torch.nn.Module`]) -- The model to be adapted. + - **peft_config** ([`LoKrConfig`]): The configuration of the LoKr model. + """ + + prefix: str = "lokr_" + tuner_layer_cls = LoKrLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_LOKR_TARGET_MODULES_MAPPING + layers_mapping: dict[type[torch.nn.Module], type[LoKrLayer]] = { + torch.nn.Conv2d: Conv2d, + torch.nn.Conv1d: Conv1d, + torch.nn.Linear: Linear, + } + + def _create_and_replace( + self, + config: LycorisConfig, + adapter_name: str, + target: Union[LoKrLayer, 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. + """ + r_key = get_pattern_key(config.rank_pattern.keys(), current_key) + alpha_key = get_pattern_key(config.alpha_pattern.keys(), current_key) + kwargs = { + "r": config.rank_pattern.get(r_key, config.r), + "alpha": config.alpha_pattern.get(alpha_key, config.alpha), + } + + if isinstance(target, LoKrLayer): + target.update_layer(adapter_name, config=config, **kwargs) + else: + new_module = self._create_new_module(config, adapter_name, target, **kwargs) + self._replace_module(parent, target_name, new_module, target) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..94d6e16c3634bf6510df8f5925d916441a18baa3 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/__init__.py @@ -0,0 +1,83 @@ +# 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 .arrow import create_arrow_model +from .config import ( + ArrowConfig, + BdLoraConfig, + EvaConfig, + LoftQConfig, + LoraConfig, + LoraGAConfig, + LoraRuntimeConfig, + MontecloraConfig, + VeloraConfig, +) +from .conversion import convert_to_lora, save_as_lora +from .eva import get_eva_state_dict, initialize_lora_eva_weights +from .gptq import GPTQLoraLinear +from .layer import Conv2d, Conv3d, Embedding, Linear, LoraLayer, ParamWrapper +from .loraga import preprocess_loraga +from .model import LoraModel + + +__all__ = [ + "ArrowConfig", + "BdLoraConfig", + "Conv2d", + "Conv3d", + "Embedding", + "EvaConfig", + "GPTQLoraLinear", + "Linear", + "LoftQConfig", + "LoraConfig", + "LoraGAConfig", + "LoraLayer", + "LoraModel", + "LoraRuntimeConfig", + "MontecloraConfig", + "ParamWrapper", + "VeloraConfig", + "convert_to_lora", + "create_arrow_model", + "get_eva_state_dict", + "initialize_lora_eva_weights", + "preprocess_loraga", + "save_as_lora", +] + +register_peft_method(name="lora", config_cls=LoraConfig, model_cls=LoraModel, is_mixed_compatible=True) + + +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 == "EetqLoraLinear") and is_eetq_available(): + from .eetq import EetqLoraLinear + + return EetqLoraLinear + + raise AttributeError(f"module {__name__} has no attribute {name}") diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/aqlm.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/aqlm.py new file mode 100644 index 0000000000000000000000000000000000000000..0218ff7cf32e7d3a4a31a55cbf40153022853b41 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/aqlm.py @@ -0,0 +1,105 @@ +# 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") + if config.velora_config is not None: + raise ValueError(f"{self.__class__.__name__} does not support VeLoRA 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 + + +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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/arrow.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/arrow.py new file mode 100644 index 0000000000000000000000000000000000000000..40f51353dfc2608e694358548661aa4206994452 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/arrow.py @@ -0,0 +1,474 @@ +# 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 or 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_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. + """ + from torch import 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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/awq.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/awq.py new file mode 100644 index 0000000000000000000000000000000000000000..5ea99627a5572599c836e20b3708ff400cde2bf9 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/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 peft.utils.other import is_gptqmodel_awq_layer + +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") + if config.velora_config is not None: + raise ValueError(f"{self.__class__.__name__} does not support VeLoRA 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() and is_gptqmodel_awq_layer(target_base_layer): + new_module = AwqLoraLinear(target, adapter_name, config=config, **kwargs) + target.qweight = target_base_layer.qweight + + return new_module diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/bnb.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/bnb.py new file mode 100644 index 0000000000000000000000000000000000000000..15c9d201e6afe611ea7c7a47501ef2758338935b --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/bnb.py @@ -0,0 +1,591 @@ +# 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.velora_config is not None: + raise ValueError(f"{self.__class__.__name__} does not support VeLoRA.") + 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.velora_config is not None: + raise ValueError(f"{self.__class__.__name__} does not support VeLoRA.") + 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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/config.py new file mode 100644 index 0000000000000000000000000000000000000000..a376c0e06588754b94a44f22267b602235559823 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/config.py @@ -0,0 +1,1103 @@ +# 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 importlib +import warnings +from dataclasses import dataclass, field +from typing import Literal, Optional, Union + +from torch import nn + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class LoraRuntimeConfig: + """ + This is the sub-configuration class to store the runtime configurations for the model. + + Args: + ephemeral_gpu_offload (`bool`): + Whether to use ephemeral GPU offloading for models partially kept in CPU memory. + """ + + ephemeral_gpu_offload: bool = field( + default=False, + metadata={ + "help": ( + "Whether to use ephemeral GPU offloading for models partially kept in CPU memory. Ephemeral GPU offloading result in " + "the data involved in intense operations being momentarily copied over to the GPU, and the results copied " + "back to CPU. There is a momentary VRAM overhead, but operations are generally orders of magnitude faster " + "compared to performing them on the CPU. This is useful when parts of the model and/or components (such " + "as adapters) are kept in CPU memory until they are needed. Rather than perform expensive operations on " + "small data, the data is transferred to the GPU on-demand, the operation(s) performed, and the results " + "moved back to CPU memory. Currently only affects DoRA initialization." + ) + }, + ) + + +@dataclass +class VeloraConfig: + """ + This is the sub-configuration class to store the configuration for VeLoRA. Original paper can be found + [here](https://arxiv.org/abs/2405.17991). + + Args: + num_groups (`int`): + Number of feature groups used by VeLoRA to split the input activation depth before compression. Increase + this parameter to reduce the reconstruction error of input activations at the cost of increased memory + consumption. + scale (`float`): + Scale applied to the reconstructed activations in the VeLoRA backward pass. + init_type (`str`): + Projection initialization strategy for VeLoRA. Supported values are `'batch_average_once'`, + `'batch_average'`, and `'random'`. + """ + + num_groups: int = field( + default=64, + metadata={ + "help": "Number of feature groups used by VeLoRA to split the input activation depth before compression." + }, + ) + scale: float = field( + default=1.0, + metadata={"help": "Scale applied to the reconstructed activations in the VeLoRA backward pass."}, + ) + init_type: Literal["batch_average", "batch_average_once", "random"] = field( + default="batch_average", + metadata={ + "help": "Projection initialization strategy for VeLoRA. Supported values are " + "`'batch_average_once'`, `'batch_average'`, and `'random'`." + "batch_average uses the batch statistics during each forward pass for the projection." + "batch_average_once only updates the projection weights once in the first pass to reduce training time at the cost of less exact gradient approximations." + }, + ) + + def __post_init__(self): + if self.num_groups <= 0: + raise ValueError(f"`num_groups` should be positive, got {self.num_groups}.") + if self.scale <= 0: + raise ValueError(f"`scale` should be positive, got {self.scale}.") + if self.init_type not in {"batch_average_once", "batch_average", "random"}: + raise ValueError( + "Unsupported `init_type` " + f"{self.init_type!r}. Supported values are 'batch_average_once', " + "'batch_average', and 'random'." + ) + + +@dataclass +class LoftQConfig: + """ + This is the sub-configuration class to store the configuration of a [`LoraModel`]. + + Args: + bits_pattern (`dict`): The mapping from layer names or regexp expression to bits which are different from the + default bits specified by `bits`. For example, `{model.decoder.layers.0.encoder_attn.k_proj: 2`}. + bits (`int`): Quantization bits for LoftQ. + iter (`int`): Alternating iterations for LoftQ. + fake (`bool`): True: use fp16/fp32; used for first time to save weights. False: use bitsandbytes 4bit linear + models. weights can't be saved. Recommend to set to True, save the weights and load the saved weights in 4 + bits. + """ + + loftq_bits: int = field(default=4, metadata={"help": "Quantization bits for LoftQ"}) + loftq_iter: int = field(default=1, metadata={"help": "Alternating iterations for LoftQ"}) + + +@dataclass +class ArrowConfig: + """ + This is the sub-configuration class to store the configuration for Arrow and GenKnowSub algorithm. Arrow is a + routing algorithm to combine the trained LoRA modules to solve new tasks, proposed in + 'https://huggingface.co/papers/2405.11157'. GenKnowSub is a refinement on the trained modules before being combined + via Arrow, introduced in 'https://aclanthology.org/2025.acl-short.54/' + """ + + top_k: int = field( + default=3, + metadata={"help": "Number of top LoRA modules to combine in Arrow routing."}, + ) + + router_temperature: float = field( + default=1.0, + metadata={"help": "Softmax temperature for computing Arrow expert coefficients."}, + ) + + use_gks: bool = field( + default=False, + metadata={"help": "Enable GenKnowSub."}, + ) + + task_adapter_names: Optional[list[str]] = field( + default=None, + init=False, + metadata={"help": "list of task-specific LoRA adapter names. It will be set in create_arrow_model()."}, + ) + + gks_adapter_names: Optional[list[str]] = field( + default=None, + init=False, + metadata={ + "help": "list of general LoRA adapter names for GenKnowSub. It will be set in create_arrow_model()." + }, + ) + + rng_seed: Optional[int] = field( + default=None, + metadata={"help": "Optional RNG seed for reproducibility. If None, sampling is non-deterministic."}, + ) + + def __post_init__(self): + if self.top_k <= 0: + raise ValueError("top_k cannot be negative.") + if self.router_temperature <= 0: + raise ValueError("router_temperature must be greater than 0.") + + +@dataclass +class BdLoraConfig: + """ + Configuration for BD-LoRA (Block-Diagonal LoRA). BD-LoRA is a LoRA variant that can be used for efficient + multi-LoRA serving in inference engines. The speedup results from reduced inter-GPU communication by setting + certain LoRA modules to be block-diagonal. + + To determine which LoRA factors should be set as block-diagonal, follow these guidelines: + - For attention, set + - Q,K,V projections to be LoRA-B block-diagonal + - Out projection to be LoRA-A block-diagonal + - For MLPs, set + - Up, Gate projection to be LoRA-B block-diagonal + - Down projection to be LoRA-A block-diagonal + + For other modules and/or architectures, look into the code of your target inference engine. Modules that are + row-sharded should have LoRA-A block-diagonal, modules that are column-sharded should have LoRA-B block-diagonal. + + Args: + target_modules_bd_a: + Modules where the LoRA-A is block-diagonal. Matches each pattern in the list against the module name via + `pattern is in target_name`. Example: ['up_proj', 'q_proj', 'v_proj', 'k_proj'] + target_modules_bd_b: + Modules where the LoRA-B is block-diagonal. Matches each pattern in the list against the module name via + `pattern is in target_name`. Example: ['out_proj', 'down_proj'] + nblocks: Number of blocks in block-diagonal matrices + """ + + target_modules_bd_a: Optional[list[str]] = field( + default=None, + metadata={ + "help": "Modules where the LoRA-A is block-diagonal. Matches each pattern in the list against the " + "module name via `pattern is in target_name`. " + "Usually one should specify the q,k,v,up and gate projections here. " + "Example: ['up_proj', 'q_proj', 'v_proj', 'k_proj']" + }, + ) + target_modules_bd_b: Optional[list[str]] = field( + default=None, + metadata={ + "help": "Modules where the LoRA-B is block-diagonal. Matches each pattern in the list against the module " + "name via `pattern is in target_name`. Usually, one should specify out and down projections here. " + "Example: ['out_proj', 'down_proj']" + }, + ) + nblocks: int = ( + field( + default=1, + metadata={ + "help": "Number of blocks each block-diagonal matrix has. If using BD-LoRA to speed up inference, " + "set it to be equal to the desired sharding degree during serving." + }, + ), + ) + match_strict: bool = field( + default=True, + metadata={ + "help": "If set to true, requires each target_module to have either a block-diagonal LoRA-A or LoRA-B, " + "and raises an error otherwise. You can set this to False to mix LoRA and BD-LoRA training, " + "e.g. if some layers in your module do not benefit from BD-LoRA." + }, + ) + + def __post_init__(self): + overlap = set(self.target_modules_bd_a or []) & set(self.target_modules_bd_b or []) + if overlap: + raise ValueError( + "Found overlapping modules in target_modules_bd lists:" + f"{self.target_modules_bd_a} (A) and {self.target_modules_bd_b} (B)." + ) + + +@dataclass +class EvaConfig: + """ + This is the sub-configuration class to store the configuration for a data-driven initialization via EVA. EVA was + introduced in Explained Variance Adaptation. + + Args: + rho (`float`): + Rho value for EVA redistribution (>= 1.0). The maximum rank for a layer is lora_r * rho. Default is 2.0, + meaning the maximum rank allowed for a layer is 2r. Increasing rho will allow for a higher degree of + redistribution of ranks across layers. Some pre-trained models might be more sensitive to a rank + redistribution. It can therefore be beneficial to try rho=1.0 (no redistribution) if the performance is + lower than expected. + tau (`float`): + Cosine similarity threshold for early stopping. Compares the cosine similarity of right-singular vectors + between two consecutive SVD steps. If the cosine similarity is above this threshold, the SVD iteration is + stopped. Default is 0.99. + use_label_mask (`bool`): + Use label mask for EVA initialization. This means that positions where labels=label_mask_value are ignored + for the SVD computation. Setting use_label_mask=True is preferred in most cases and can be especially + beneficial for multi-turn conversations. The default value is True. Filtering out items based on the label + mask can sometimes lead to a small batch size and as a result instabilities in the SVD computation. For + cases where a large share of batch items would be filtered out, set use_label_mask=False. + label_mask_value (`int`): + If use_label_mask=True the value to look for to mask out ignored tokens. Default is -100. + whiten (`bool`): Apply whitening to singular vectors. Default is False. + Whitening has been shown to be beneficial for EVA in the vision domain. + adjust_scaling_factors (`bool`): + Adjust LoRA scaling factors after the rank redistribution. Setting this to True means the scaling factors + are adjusted so that all LoRA gradients have the same scale regardless of their rank. Default is True. + """ + + rho: float = field(default=2.0, metadata={"help": "Rho value for EVA redistribution"}) + tau: float = field(default=0.99, metadata={"help": "Cosine similarity threshold for early stopping"}) + use_label_mask: bool = field(default=True, metadata={"help": "Use label mask for EVA initialization"}) + label_mask_value: int = field( + default=-100, metadata={"help": "if use_label_mask=True the value to look for to mask out ignored tokens"} + ) + whiten: bool = field(default=False, metadata={"help": "Apply whitening to singular vectors"}) + adjust_scaling_factors: bool = field( + default=True, + metadata={"help": "Adjust LoRA scaling factors after the rank redistribution"}, + ) + + def __post_init__(self): + if self.rho < 1.0: + raise ValueError("`rho` must be >= 1.0") + if self.tau < 0.0 or self.tau > 1.0: + raise ValueError("`tau` must be between 0.0 and 1.0.") + + +@dataclass +class CordaConfig: + """ + This is the sub-configuration class to store the configuration of a [`LoraModel`]. + + Args: + cache_file (`Optional[str]`): + File to store the SVD cache. The SVD cache is much smaller than the residual model (for example, residual + model of Llama-3-8b is 15GB, while SVD cache is 1.4GB), but with SVD cache and original model weights, + residual model weights can be built quickly. If you need to reuse residual model weights with limited + storage, you can store the SVD cache instead. + covariance_file (`Optional[str]`): + File to store the covariance matrix. If you wish to train multiple models with different ranks, but they + sample from the same dataset, you can store the covariance matrix and reuse it for different ranks. Note + that covariance file is usually large (comparable to model size), so you will need sufficient storage. + corda_method (`Literal["ipm", "kpm"]`): + Method to build adapter. The KPM (Knowledge-Preserved Mode) not only achieves better performance than LoRA + on fine-tuning tasks, but also mitigates the catastrophic forgetting of pre-trained world knowledge. When + preserving pre-trained knowledge is not a concern, the IPM (Instruction-Previewed Mode) is favored because + it can further accelerate convergence and enhance the fine-tuning performance. Defaults to `'ipm'`. + verbose (`bool`): + If true, prints the progress of CorDA initialization. Defaults to `False`. + use_float16_for_covariance (`bool`): + If true, uses float16 for the covariance matrix. This can reduce the memory usage of the covariance matrix + by half, but may lead to numerical instability. Defaults to `False`. + prune_temporary_fields (`bool`): + If true, temporary fields generated in CorDA preprocessing will be pruned. Defaults to `True`. + """ + + cache_file: Optional[str] = field( + default=None, + metadata={ + "help": ( + "File to store the SVD cache. The SVD cache is much smaller than the residual model (for example, " + "residual model of Llama-3-8b is 15GB, while SVD cache is 1.4GB), but with SVD cache and original model " + "weights, residual model weights can be built quickly. If you need to reuse residual model weights with " + "limited storage, you can store the SVD cache instead." + ) + }, + ) + covariance_file: Optional[str] = field( + default=None, + metadata={ + "help": ( + "File to store the covariance matrix. If you wish to train multiple models with different ranks, but " + "they sample from the same dataset, you can store the covariance matrix and reuse it for different ranks. " + "Note that covariance file is usually large (comparable to model size), so you will need sufficient storage." + ) + }, + ) + corda_method: Literal["ipm", "kpm"] = field( + default="ipm", + metadata={ + "help": ( + "Method to build adapter. The KPM not only achieves better performance than LoRA on fine-tuning tasks, but " + "also mitigates the catastrophic forgetting of pre-trained world knowledge. When preserving pre-trained " + "knowledge is not a concern, the IPM is favored because it can further accelerate convergence and enhance " + "the fine-tuning performance." + ) + }, + ) + verbose: bool = field(default=False, metadata={"help": "If true, prints the progress of CorDA initialization."}) + use_float16_for_covariance: bool = field( + default=False, + metadata={ + "help": ( + "If true, uses float16 for the covariance matrix. This can reduce the memory usage of the covariance matrix " + "by half, but may lead to numerical instability." + ) + }, + ) + prune_temporary_fields: bool = field( + default=True, metadata={"help": "If true, temporary fields generated in CorDA preprocessing will be pruned."} + ) + + +@dataclass +class LoraConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`LoraModel`]. + + Args: + r (`int`): + Lora attention dimension (the "rank"). + 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/Conv1D modules are chosen (if + the model is a PreTrainedModel, the output layer excluded). 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. To avoid targeting any modules (because you want + to apply `target_parameters`), set `target_modules=[]`. + 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. + lora_alpha (`int`): + The alpha parameter for Lora scaling. + lora_dropout (`float`): + The dropout probability for Lora layers. + 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 for LoRA. Can be 'none', 'all' or 'lora_only'. If 'all' or 'lora_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. + use_rslora (`bool`): + When set to True, uses [Rank-Stabilized LoRA](https://huggingface.co/papers/2312.03732) which sets the + adapter scaling factor to `lora_alpha/math.sqrt(r)`, since it was proven to work better. Otherwise, it will + use the original default value of `lora_alpha/r`. + modules_to_save (`List[str]`): + List of modules apart from adapter layers to be set as trainable and saved in the final checkpoint. + init_lora_weights (`bool` | `Literal["gaussian", "eva", "olora", "pissa", "pissa_niter_[number of iters]", "corda", "loftq", "orthogonal"]`): + How to initialize the weights of the adapter layers. Passing True (default) results in the default + initialization from the reference implementation from Microsoft, with the LoRA B weight being set to 0. + This means that without further training, the LoRA adapter will be a no-op. Setting the initialization to + False leads to random initialization of LoRA A and B, meaning that LoRA is not a no-op before training; + this setting is intended for debugging purposes. Passing 'gaussian' results in Gaussian initialization + scaled by the LoRA rank for linear and layers. Pass `'loftq'` to use LoftQ initialization. Passing `'eva'` + results in a data-driven initialization of Explained + Variance Adaptation. EVA initializes LoRA based on the SVD of layer input activations and achieves SOTA + performance due to its ability to adapt to the finetuning data. Pass `'olora'` to use OLoRA initialization. + Passing `'pissa'` results in the initialization of Principal Singular values and Singular vectors Adaptation (PiSSA), which converges more rapidly than + LoRA and ultimately achieves superior performance. Moreover, PiSSA reduces the quantization error compared + to QLoRA, leading to further enhancements. Passing `'pissa_niter_[number of iters]'` initiates + Fast-SVD-based PiSSA initialization, where `[number of iters]` indicates the number of subspace iterations + to perform FSVD, and must be a nonnegative integer. When `[number of iters]` is set to 16, it can complete + the initialization of a 7B model within seconds, and the training effect is approximately equivalent to + using SVD. Passing `'corda'` results in the initialization of Context-Oriented Decomposition Adaptation, which + converges even more rapidly than PiSSA in Instruction-Previewed Mode, and preserves world knowledge better + than LoRA in Knowledge-Preserved Mode. Passing `"orthogonal"` results in LoRA A and B being intialized + orthogonally; in this, it resembles `"olora"`, but the base weights are left untouched (requires `r` to be + even, only supported for linear layers for now). + 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'`. + rank_pattern (`dict`): + The mapping from layer names or regexp expression to ranks which are different from the default rank + specified by `r`. For example, `{'^model.decoder.layers.0.encoder_attn.k_proj': 16}`. + alpha_pattern (`dict`): + The mapping from layer names or regexp expression to alphas which are different from the default alpha + specified by `lora_alpha`. For example, `{'^model.decoder.layers.0.encoder_attn.k_proj': 16}`. + megatron_config (`Optional[dict]`): + The TransformerConfig arguments for Megatron. It is used to create LoRA's parallel linear layer. You can + get it like this, `core_transformer_config_from_args(get_args())`, these two functions being from Megatron. + The arguments will be used to initialize the TransformerConfig of Megatron. You need to specify this + parameter when you want to apply LoRA to the ColumnParallelLinear and RowParallelLinear layers of megatron. + megatron_core (`Optional[str]`): + The core module from Megatron to use, defaults to `"megatron.core"`. + trainable_token_indices (`Optional[Union[List[int], dict[str, List[int]]]]`) + Lets you specify which token indices to selectively fine-tune without requiring to re-train the whole + embedding matrix using the `peft.TrainableTokensModel` method. You can specify token indices in two ways. + Either you specify a list of indices which will then target the model's input embedding layer (or, if not + found, `embed_tokens`). Alternatively, you can specify a dictionary where the key is the name of the + embedding module and the values are the list of token indices, e.g. `{'embed_tokens': [0, 1, ...]}`. Note + that training with FSDP requires `use_orig_params=True` to avoid issues with non-uniform `requires_grad`. + loftq_config (`Optional[LoftQConfig]`): + The configuration of LoftQ. If this is not None, then LoftQ will be used to quantize the backbone weights + and initialize Lora layers. Also pass `init_lora_weights='loftq'`. Note that you should not pass a + quantized model in this case, as LoftQ will quantize the model itself. + eva_config (`Optional[EvaConfig]`): + The configuration of EVA. At a minimum the dataset argument needs to be set (use the same dataset as for + finetuning). + corda_config (`Optional[CordaConfig]`): + The configuration of CorDA. If this is not None, then CorDA will be used to build the adapter layers. Also + pass `init_lora_weights='corda'`. + use_dora (`bool`): + Enable 'Weight-Decomposed Low-Rank Adaptation' (DoRA). This technique decomposes the updates of the weights + into two parts, magnitude and direction. Direction is handled by normal LoRA, whereas the magnitude is + handled by a separate learnable parameter. This can improve the performance of LoRA especially at low + ranks. Right now, DoRA only supports linear and Conv2D layers. DoRA introduces a bigger overhead than pure + LoRA, so it is recommended to merge weights for inference. For more information, see + https://huggingface.co/papers/2402.09353. + velora_config (`Optional[VeloraConfig]`): + Enable VeLoRA by providing a VeloraConfig. VeLoRA swaps in a custom backward pass for the LoRA A projection + that stores compressed activations instead of the full input activations. + alora_invocation_tokens (`List[int]`): + If not None, enable 'Activated LoRA' (aLoRA), with + alora_invocation_tokens being the tokenized invocation string for the adapter (must be present in all model + input strings). This technique selectively activates the adapter weights only on tokens during and after + the alora_invocation_tokens. When used in a CausalLM, this means that the KV cache prior to invocation is + interchangeable with that of the base model (and other aLoRA adapters operating this way). As a result, in + inference pipelines involving switching between base model inference and adapter inference (e.g. agentic + pipelines, see paper for examples), significant savings are realized (relative to LoRA) by saving prefill + operations. Overall adapter inference speedups of an order of magnitude or more can occur on vLLM, + depending on the length of the shared context. Note that merging is not possible due to the selective + application of the weights. + layer_replication (`List[Tuple[int, int]]`): + Build a new stack of layers by stacking the original model layers according to the ranges specified. This + allows expanding (or shrinking) the model without duplicating the base model weights. The new layers will + all have separate LoRA adapters attached to them. + runtime_config (`LoraRuntimeConfig`): + Runtime configurations (which are not saved or restored). + lora_bias (`bool`): + Defaults to `False`. Whether to enable the bias term for the LoRA B parameter. Typically, this should be + disabled. The main use case for this is when the LoRA weights were extracted from fully fine-tuned + parameters so the bias of those parameters can be taken into account. + target_parameters (`List[str]`, *optional*) + List of parameter names or regex expression of the parameter names to replace with LoRA. This argument + behaves similarly to `target_modules`, except that the parameter name should be passed. Generally, you + should use `target_modules` to target the module (e.g. `nn.Linear`). However, in some circumstances, this + is not possible. E.g., in many mixture of expert (MoE) layers in HF Transformers, instead of using + `nn.Linear`, an `nn.Parameter` is used. PEFT normally overwrites the `forward` method for LoRA, but for + `nn.Parameter`, there is none. Therefore, to apply LoRA to that parameter, it needs to be targeted with + `target_parameters`. As an example, for Llama4, you can pass: + `target_parameters=['feed_forward.experts.gate_up_proj', 'feed_forward.experts.down_proj]`. Passing a + string for regex matching is not implemented yet. + ensure_weight_tying (`bool`, *optional*) + Whether to tie weights or not after peft initialization. This will ensure that the adapters added to the + tied layers are also tied. This is only applicable for layers passed via `modules_to_save` and + `target_modules`. + + """ + + 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 LoRA. " + "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'. " + "This can also be a wildcard 'all-linear' which matches all linear/Conv1D " + "(if the model is a PreTrainedModel, the output layer excluded). " + "If 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. " + "To avoid targeting any modules (because you want to apply `target_parameters`), set " + "`target_modules=[]`." + ), + }, + ) + 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 Lora."}, + ) + lora_alpha: int = field(default=8, metadata={"help": "Lora alpha"}) + lora_dropout: float = field(default=0.0, metadata={"help": "Lora dropout"}) + 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", "lora_only"] = field( + default="none", metadata={"help": "Bias type for Lora. Can be 'none', 'all' or 'lora_only'"} + ) + use_rslora: bool = field( + default=False, + metadata={ + "help": ( + "When set to True, uses [Rank-Stabilized LoRA](https://huggingface.co/papers/2312.03732)" + " which sets the adapter scaling factor to `lora_alpha/math.sqrt(r)`, since it" + " was proven to work better. Otherwise, it will use the original default" + " value of `lora_alpha/r`." + ) + }, + ) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": "List of modules apart from LoRA 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_lora_weights: ( + bool + | Literal["gaussian", "eva", "olora", "pissa", "pissa_niter_[number of iters]", "corda", "loftq", "orthogonal"] + ) = field( + default=True, + metadata={ + "help": ( + "How to initialize the weights of the LoRA layers. " + "Passing True (default) results in the default initialization from the reference implementation from " + "Microsoft, with the LoRA B weight being set to 0. This means that without further training, the LoRA " + "adapter will be a no-op. " + "Setting the initialization to False leads to random initialization of LoRA A and B, meaning that LoRA " + "is not a no-op before training; this setting is intended for debugging purposes. " + "Passing `'gaussian'` results in Gaussian initialization scaled by the LoRA rank for linear and layers. " + "Passing `'eva'` results in a data-driven initialization of Explained Variance Adaptation. " + "Passing `'olora'` results in OLoRA initialization. " + "Passing `'pissa'` results in PiSSA initialization. " + "Passing `'pissa_niter_[number of iters]'` initiates Fast-SVD-based PiSSA initialization, where " + "[number of iters] indicates the number of subspace iterations to perform fsvd, and must be a " + "nonnegative integer. " + "Passing `'corda'` results in CorDA initialization. " + "Pass `'loftq'` to use LoftQ initialization. " + "Pass `'orthogonal'` for orthogonal initialization of LoRA A and B." + ), + }, + ) + 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. " + "This only works when target_modules is a list of str." + }, + ) + 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 only works when target_modules is a list of str. This should target the `nn.ModuleList` of the " + "model, which is often called `'layers'` or `'h'`." + }, + ) + rank_pattern: Optional[dict] = field( + default_factory=dict, + metadata={ + "help": ( + "The mapping from layer names or regexp expression to ranks which are different from the default rank specified by `r`. " + "For example, `{'^model.decoder.layers.0.encoder_attn.k_proj': 16}`." + ) + }, + ) + alpha_pattern: Optional[dict] = field( + default_factory=dict, + metadata={ + "help": ( + "The mapping from layer names or regexp expression to alphas which are different from the default alpha specified by `lora_alpha`. " + "For example, `{'^model.decoder.layers.0.encoder_attn.k_proj': 16}`." + ) + }, + ) + megatron_config: Optional[dict] = field( + default=None, + metadata={ + "help": ( + "The TransformerConfig from Megatron. It is used to create LoRA's parallel linear layer." + "You can get it like this, `core_transformer_config_from_args(get_args())`, " + "these two functions being from Megatron." + "You need to specify this parameter when you want to apply LoRA to the ColumnParallelLinear and " + "RowParallelLinear layers of megatron." + "It should be noted that we may not be able to use the `save_pretrained` and `from_pretrained` " + "functions, because TransformerConfig may not necessarily be serialized." + "But when using megatron, we can use `get_peft_model_state_dict` function and " + "megatron's framework, they can also save and load models and configurations." + ) + }, + ) + megatron_core: Optional[str] = field( + default="megatron.core", + metadata={ + "help": ( + "The core module from Megatron, it is used to create LoRA's parallel linear layer. " + "It only needs to be passed in when you need to use your own modified megatron core module. " + "Otherwise, it will use the default value `megatron.core`. " + ) + }, + ) + trainable_token_indices: Optional[Union[list[int], dict[str, list[int]]]] = field( + default=None, + metadata={ + "help": ( + "Lets you specify which token indices to selectively fine-tune without requiring to re-train the " + "whole embedding matrix using the `peft.TrainableTokensModel` method. You can specify token indices " + "in two ways. Either you specify a list of indices which will then target the model's input embedding " + "layer (or, if not found, `embed_tokens`). Alternatively, you can specify a dictionary where the key " + "is the name of the embedding module and the values are the list of token indices, e.g. " + "`{'embed_tokens': [0, 1, ...]}`. Note that training with FSDP requires `use_orig_params=True` to " + "avoid issues with non-uniform `requires_grad`." + ) + }, + ) + # dict type is used when loading config.json + loftq_config: Union[LoftQConfig, dict] = field( + default_factory=dict, + metadata={ + "help": ( + "The configuration of LoftQ. If this is passed, then LoftQ will be used to quantize the backbone " + "weights and initialize Lora layers. Also set `init_lora_weights='loftq'` in this case." + ) + }, + ) + eva_config: Optional[EvaConfig] = field( + default=None, + metadata={ + "help": ( + "The configuration of EVA. If this is passed, then EVA will be used to initialize the LoRA layers. " + "Also set `init_lora_weights='eva'` in this case. " + ) + }, + ) + corda_config: Optional[CordaConfig] = field( + default=None, + metadata={ + "help": ( + "The configuration of CorDA. If this is passed, then CorDA will be used to build the adapter layers. " + "Also set `init_lora_weights='corda'` in this case." + ) + }, + ) + lora_ga_config: Optional[LoraGAConfig] = field( + default=None, + metadata={ + "help": ( + "The configuration of LoRA-GA. If this is passed, then LoRA-GA will be used to initialize the adapter layers. " + "Also set `init_lora_weights='lora_ga'` in this case." + ) + }, + ) + use_dora: bool = field( + default=False, + metadata={ + "help": ( + "Enable 'Weight-Decomposed Low-Rank Adaptation' (DoRA). This technique decomposes the updates of the " + "weights into two parts, magnitude and direction. Direction is handled by normal LoRA, whereas the " + "magnitude is handled by a separate learnable parameter. This can improve the performance of LoRA, " + "especially at low ranks. Right now, DoRA only supports linear and Conv2D layers. DoRA introduces a bigger" + "overhead than pure LoRA, so it is recommended to merge weights for inference." + ) + }, + ) + velora_config: Optional[Union[VeloraConfig, dict]] = field( + default=None, + metadata={ + "help": ( + "Enable VeLoRA as a LoRA variant by providing a VeloraConfig. VeLoRA swaps in a custom backward pass " + "for the LoRA A projection that stores compressed activations instead of the full input activations." + ) + }, + ) + alora_invocation_tokens: Optional[list[int]] = field( + default=None, + metadata={ + "help": ( + "If not None, enable 'Activated LoRA' (aLoRA), with " + "alora_invocation_tokens being the tokenized invocation string for the adapter (must be present in all model " + "input strings). This technique selectively activates the adapter weights only on tokens during and after " + "the alora_invocation_tokens. When used in a CausalLM, this means that the KV cache prior to invocation is " + "interchangeable with that of the base model (and other aLoRA adapters operating this way). As a result, in " + "inference pipelines involving switching between base model inference and adapter inference (e.g. agentic " + "pipelines, see paper for examples), significant savings are realized (relative to LoRA) by saving prefill " + "operations. Overall adapter inference speedups of an order of magnitude or more can occur on vLLM, " + "depending on the length of the shared context. Note that merging is not possible due to the selective " + "application of the weights." + ) + }, + ) + use_qalora: bool = field( + default=False, + metadata={ + "help": ( + "It is only implemented in GPTQ for now. Enable Quantization-Aware Low-Rank Adaptation (QALoRA)." + "This technique combines quantization-aware training " + "with LoRA to improve performance for quantized models. This can improve the performance of LoRA, " + "especially at low ranks. Right now, QALoRA only supports linear layers." + ) + }, + ) + qalora_group_size: int = field( + default=16, + metadata={ + "help": ( + "Group size parameter for QALoRA pooling, controlling the dimension reduction factor. " + "Input dimensions are pooled into groups of this size, reducing the computational cost. " + "Higher values provide more compression but may reduce model quality. " + "This parameter determines how many original features are averaged together to create " + "one pooled feature. Only used when `use_qalora=True`." + ) + }, + ) + + monteclora_config: Optional[MontecloraConfig] = field( + default=None, + metadata={ + "help": ( + "The configuration of Monteclora (Monte Carlo Low-Rank Adaptation). If passed, Monteclora will be " + "used to add variational Monte Carlo sampling on top of the LoRA adapters. See `MontecloraConfig` " + "for details on the individual hyperparameters." + ) + }, + ) + # Enables replicating layers in a model to expand it to a larger model. + layer_replication: Optional[list[tuple[int, int]]] = field( + default=None, + metadata={ + "help": ( + "This enables using LoRA to effectively expand a transformer model to a larger size by repeating some layers. " + "The transformation handles models (currently Llama, Bert or Falcon compatible architectures) with " + "a module list in the model which it modifies to expand the number of modules. " + "Base weights are shared so the memory usage is close to the original model. The intended use is these base weights " + "remain fixed during finetuning but each layer has a separate LoRA adapter so the layers can be specialed via " + "the adapter layers fit during fine tuning." + "The format is a list of [start, end) pairs which specify the layer ranges to stack. For example:\n" + " Original model has 5 layers labelled by their position in the model: `[0, 1, 2, 3, 4]`\n" + " layer_replication: `[[0, 4], [2, 5]]`\n" + " Final model will have this arrangement of original layers: `[0, 1, 2, 3, 2, 3, 4]`\n" + "This format is based on what is used for pass-through merges in mergekit. It makes it simple to select sequential " + "ranges of a model and stack them while reusing layers at either end of each sequence." + ) + }, + ) + runtime_config: LoraRuntimeConfig = field( + default_factory=LoraRuntimeConfig, metadata={"help": "Runtime configurations"} + ) + lora_bias: bool = field( + default=False, + metadata={ + "help": ( + "Whether to enable the bias term for the LoRA B parameter. Typically, this should be disabled. The " + "main use case for this is when the LoRA weights were extracted from fully fine-tuned parameters so " + "the bias of those parameters can be taken into account." + ) + }, + ) + target_parameters: Optional[list[str]] = field( + default=None, + metadata={ + "help": ( + "List of parameter names or regex expression of the parameter names to replace with LoRA. " + "This argument behaves similarly to `target_modules`, except that the parameter name should be passed. " + "Generally, you should use `target_modules` to target the module (e.g. `nn.Linear`). However, in some " + "circumstances, this is not possible. E.g., in many mixture of expert (MoE) layers in HF Transformers, " + "instead of using `nn.Linear`, an `nn.Parameter` is used. PEFT normally overwrites the `forward` " + "method for LoRA, but for `nn.Parameter`, there is none. Therefore, to apply LoRA to that parameter, " + "it needs to be targeted with `target_parameters`. As an example, for Llama4, you can pass: " + "`target_parameters=['feed_forward.experts.gate_up_proj', 'feed_forward.experts.down_proj]`. Passing a " + "string for regex matching is not implemented yet." + ) + }, + ) + use_bdlora: Optional[BdLoraConfig] = field( + default=None, + metadata={ + "help": ( + "Enable BD-LoRA (Block-Diagonal LoRA) by providing a BdLoraConfig. This technique uses block-diagonal matrices for LoRA-A or LoRA-B " + "factors to enable faster multi-LoRA serving by eliminating communication overheads in distributed settings." + ) + }, + ) + arrow_config: Optional[ArrowConfig] = field( + default=None, metadata={"help": "The necessary config to apply arrow routing on the model."} + ) + ensure_weight_tying: bool = field( + default=False, + metadata={ + "help": ( + "Whether to tie weights or not after peft initialization. " + "This will ensure that the adapters added to the tied layers " + "are also tied. This is only applicable for layers passed via " + "`modules_to_save`, `target_modules` and `trainable_token_indices`." + ) + }, + ) + + def to_dict(self): + """ + Returns the configuration for your adapter model as a dictionary. Removes runtime configurations. + """ + rv = super().to_dict() + rv.pop("runtime_config") + return rv + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.LORA + if isinstance(self.monteclora_config, dict): + self.monteclora_config = MontecloraConfig(**self.monteclora_config) + 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 + ) + + if self.ensure_weight_tying: + self.modules_to_tie = None + self.target_modules_to_tie = None + + if isinstance(self.velora_config, dict): + self.velora_config = VeloraConfig(**self.velora_config) + elif self.velora_config is not None and not isinstance(self.velora_config, VeloraConfig): + raise TypeError("`velora_config` must be a `VeloraConfig`, a dict, or None.") + + if isinstance(self.target_parameters, str): + raise TypeError("`target_parameters` must be a list of strings or None.") + + # if target_modules is a regex expression, then layers_to_transform should be None + if isinstance(self.target_modules, str) and self.layers_to_transform is not None: + raise ValueError("`layers_to_transform` cannot be used when `target_modules` is a str.") + + # if target_modules is a regex expression, then layers_pattern should be None + if isinstance(self.target_modules, str) and self.layers_pattern is not None: + raise ValueError("`layers_pattern` cannot be used when `target_modules` is a str.") + + # 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.use_dora and self.megatron_config: + raise ValueError("DoRA does not support megatron_core, please set `use_dora=False`.") + + # handle init_lora_weights and loftq_config + if self.init_lora_weights == "loftq": + if not importlib.util.find_spec("scipy"): + raise ImportError("The required package 'scipy' is not installed. Please install it to continue.") + if not self.loftq_config: + raise ValueError("`loftq_config` must be specified when `init_lora_weights` is 'loftq'.") + if not isinstance(self.loftq_config, dict): + # convert loftq_config to dict + self.loftq_config = vars(self.loftq_config) + elif self.loftq_config: + self.loftq_config = {} + warnings.warn("`loftq_config` specified but will be ignored when `init_lora_weights` is not 'loftq'.") + + elif self.init_lora_weights == "eva" and self.eva_config is None: + warnings.warn("`init_lora_weights` is 'eva' but `eva_config` is not specified. Using default EVA config.") + self.eva_config = EvaConfig() + elif self.init_lora_weights != "eva" and self.eva_config is not None: + warnings.warn("`eva_config` specified but will be ignored when `init_lora_weights` is not 'eva'.") + + elif self.init_lora_weights == "corda" and self.corda_config is None: + warnings.warn( + "`init_lora_weights` is 'corda' but `corda_config` is not specified. Using default CorDA config." + ) + self.corda_config = CordaConfig() + elif self.init_lora_weights != "corda" and self.corda_config is not None: + warnings.warn("`corda_config` specified but will be ignored when `init_lora_weights` is not 'corda'.") + + if self.lora_bias: + if self.init_lora_weights not in (True, False): + raise ValueError( + f"The argument lora_bias=True is only supported with init_lora_weights=True or False, got " + f"init_lora_weights={self.init_lora_weights} instead." + ) + if self.use_dora: + raise ValueError("The argument lora_bias=True is not supported for DoRA, please pass use_dora=False") + + if self.alora_invocation_tokens is not None and self.task_type != "CAUSAL_LM": + warnings.warn("aLoRA is currently only supported for CAUSAL_LM task.") + + # Using post training conversion of modified base weights to restore their initial values PiSSA/CorDA/OLoRA/LoRA-GA cannot + # be correctly done when using rslora + rank_pattern/alpha_pattern. We can't really know if the user intends + # this when they'll eventually call save_pretrained (i.e. if they'll pass + # path_initial_model_for_weight_conversionl). Therefore, we only warn but don't raise an error here. + if ( + self.use_rslora + and (self.rank_pattern or self.alpha_pattern) + and ( + (isinstance(self.init_lora_weights, str) and (self.init_lora_weights.startswith("pissa"))) + or (self.init_lora_weights == "olora") + or (self.init_lora_weights == "corda") + or (self.init_lora_weights == "lora_ga") + ) + ): + msg = ( + "Using Rank-Stabilized LoRA with rank_pattern/alpha_pattern and post-training conversion of modified " + "base weights PiSSA/CorDA/OLoRA/LoRA-GA means that you won't be able to pass " + "`path_initial_model_for_weight_conversion` to `save_pretrained` to restore the initial values of the " + "base weights; if you intend to do this, please ensure not to use rslora or rank_pattern/alpha_pattern." + ) + warnings.warn(msg) + + self._custom_modules: Optional[dict[type[nn.Module], type[nn.Module]]] = None + + def _register_custom_module(self, mapping: dict[type[nn.Module], type[nn.Module]]) -> None: + """ + Experimental API to support providing custom LoRA layers. + + This API is subject to change, you should carefully read the docs before deciding to use it: + + https://huggingface.co/docs/peft/developer_guides/custom_models + + To register custom LoRA module types, call this method with a `mapping` argument that is a dict that maps from + the target layer type to the custom LoRA layer type. The dict can contain multiple items if you wish to target + multiple layer types. The target layer type can be any nn.Module that we currently don't support in PEFT, + whether that is an official PyTorch layer type or a custom layer type. The custom LoRA module class has to be + implemented by the user and follow the PEFT conventions for LoRA layers. + + """ + if self._custom_modules is None: + self._custom_modules = {} + self._custom_modules.update(mapping) + + +@dataclass +class LoraGAConfig: + """ + This is the sub-configuration class to store the configuration for LoRA-GA initialization. + + LoRA-GA (Low-Rank Adaptation with Gradient Approximation) uses gradient information during initialization to + achieve faster convergence (2-4x speedup) by aligning the initial adapter weights with the direction of full + fine-tuning gradients. + + Reference: https://arxiv.org/abs/2407.05000 + + Args: + direction (`Literal["ArBr", "A2rBr", "ArB2r", "random"]`): + Strategy for distributing gradient SVD components to lora_A and lora_B matrices. + - "ArBr": Alternating indices (A takes odd, B takes even) + - "A2rBr": A takes indices [r:2r], B takes indices [:r] + - "ArB2r": A takes indices [:r], B takes indices [r:2r] (recommended) + - "random": Random selection of indices + Default: "ArB2r" + scale (`Literal["stable", "weight_svd", "gd_scale", "unit"]`): + Scaling strategy for adapter initialization. + - "stable": Stable scaling with gamma parameter + - "weight_svd": Scale based on weight matrix singular values + - "gd_scale": Gradient descent based scaling + - "unit": No additional scaling + Default: "stable" + stable_gamma (`int`): + Gamma parameter for stable scaling method. Default: 16 + """ + + direction: Literal["ArBr", "A2rBr", "ArB2r", "random"] = field( + default="ArB2r", metadata={"help": "Component distribution strategy from gradient SVD"} + ) + scale: Literal["stable", "weight_svd", "gd_scale", "unit"] = field( + default="stable", metadata={"help": "Scaling strategy for initialization"} + ) + stable_gamma: int = field(default=16, metadata={"help": "Gamma parameter for stable scaling"}) + + +@dataclass +class MontecloraConfig: + """ + This is the sub-configuration class to store the configuration for Monteclora (Monte Carlo Low-Rank Adaptation). + Monteclora introduces variational inference into LoRA by adding Monte Carlo sampling to the adapter weights. + + In practice you can think of Monteclora as adding stochastic, learned perturbations on top of the LoRA weights to + obtain a better-calibrated and better-regularized adapter. The argments below let you trade off stability, + regularization strength, and compute cost. + + Args: + num_samples (`int`): + Number of Monte Carlo samples to draw per forward pass. Higher values usually give smoother training and + better uncertainty estimates but increase compute and memory usage. Lower this if training is too slow or + memory constrained; increase it if training is stable and you want stronger Monte Carlo averaging. + use_entropy (`bool`): + Whether to add an entropy regularization term that keeps the Monte Carlo weights from collapsing to a + single sample. Turn this on if you observe the sampler becoming very peaky or want stronger regularization; + leave it off to mimic standard LoRA more closely. + dirichlet_prior (`float`): + Concentration parameter for the Dirichlet prior over sample/expert weights. Larger values push the weights + towards being more uniform (stronger regularization, less sparsity), while smaller positive values + encourage sparser, more peaked weights. Increase if the sampler overfits; decrease (but keep > 0) if it is + too conservative. + sample_scaler (`float`): + Overall scaling factor for the sampled perturbations applied to the LoRA weights. Increasing this makes the + Monte Carlo noise stronger (more regularization and exploration, but also more training instability); + decreasing it moves the behavior closer to standard deterministic LoRA. Setting it very close to 0 largely + disables the effect of Monteclora. + kl_loss_weight (`float`): + Weight of the KL-divergence term between the variational distribution and its prior. Larger values put more + emphasis on matching the prior (stronger regularization, potentially underfitting); smaller values rely + more on the data likelihood (weaker regularization, potentially overfitting). Tune this if you find + Monteclora over- or under-regularizing the adapter. + buffer_size (`int`): + Size of the internal buffer used by the Monte Carlo sampler (e.g. for storing recent statistics). Larger + values can stabilize the estimated variational parameters at the cost of additional memory; reduce this if + you are memory constrained. + """ + + num_samples: int = field( + default=8, + metadata={ + "help": ( + "Number of Monte Carlo samples to draw per forward pass. Higher values usually give smoother " + "training and better uncertainty estimates but increase compute and memory usage. Lower this if " + "training is too slow or memory constrained; increase it if training is stable and you want " + "stronger Monte Carlo averaging." + ) + }, + ) + use_entropy: bool = field( + default=False, + metadata={ + "help": ( + "Whether to add an entropy regularization term that keeps the Monte Carlo weights from collapsing " + "to a single sample. Turn this on if you observe the sampler becoming very peaky or want stronger " + "regularization." + ) + }, + ) + dirichlet_prior: float = field( + default=0.1, + metadata={"help": "Prior parameter for Dirichlet distribution used in expert weight sampling."}, + ) + sample_scaler: float = field( + default=1e-4, + metadata={ + "help": "Scaling factor for the Monte Carlo samples. Controls the magnitude of variational perturbations." + }, + ) + kl_loss_weight: float = field( + default=1e-5, + metadata={"help": "Weight for the KL divergence loss component in the variational objective."}, + ) + buffer_size: int = field( + default=150, + metadata={"help": "Size of the buffer for the Monte Carlo sampler."}, + ) + + def __post_init__(self): + if self.num_samples <= 0: + raise ValueError("`num_samples` must be greater than 0.") + if self.dirichlet_prior <= 0: + raise ValueError("`dirichlet_prior` must be greater than 0.") + if self.buffer_size <= 0: + raise ValueError("`buffer_size` must be greater than 0.") diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/conversion.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/conversion.py new file mode 100644 index 0000000000000000000000000000000000000000..6408e6f1ad54c9254692400adfc5deb04991500f --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/conversion.py @@ -0,0 +1,440 @@ +# 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 os +import pathlib +import warnings + +import torch +from safetensors.torch import save_file +from tqdm import tqdm +from transformers.pytorch_utils import Conv1D + +from peft.tuners.tuners_utils import BaseTunerLayer +from peft.utils import SAFETENSORS_WEIGHTS_NAME +from peft.utils.other import ModulesToSaveWrapper + +from .config import LoraConfig + + +def _find_cutoff_index(S: torch.Tensor, threshold: float) -> int: + # assumes that the singular values are sorted + if S.dim() != 1: + raise ValueError("Input vector must be 1d.") + + energy = S**2 + cs = torch.cumsum(energy, dim=0) + total = cs[-1] + + cutoff = threshold * total + # smallest index i with cs[i] >= cutoff + k = torch.searchsorted(cs, cutoff).item() + # k is the index of the first item that surpasses the threshold; since we want to include it, add + 1 + return k + 1 + + +@torch.no_grad() +def _convert_miss_module_to_lora( + module, rank: int | float, adapter_name: str = "default" +) -> tuple[torch.Tensor, torch.Tensor, int]: + """Convert a single MiSS layer to LoRA A and B matrices. + + For standard and mini modes, the MiSS forward pass (reshape+sum @ miss) is already a rank-r factorization, so the + exact factors are returned directly without SVD. + + For bat mode, the delta weight depends on the base weight, so SVD is used. + """ + miss_fn = module.miss_fn + miss_block = module.miss_block[adapter_name] + in_features = module.in_features + out_features = module.out_features + r_miss = module.miss_r[adapter_name] + orig_dtype = miss_block.dtype + device = miss_block.device + + if miss_fn == "bat": + base_weight = module.get_base_layer().weight.data.clone() + delta_weight = module.get_delta_weight(adapter_name, base_weight).float() + + U, S, V = torch.linalg.svd(delta_weight, full_matrices=False) + + if isinstance(rank, int): + effective_rank = rank + else: + effective_rank = _find_cutoff_index(S, threshold=rank) + + if effective_rank > U.shape[1]: + raise ValueError( + f"The chosen rank {effective_rank} is larger than the weight shape ({U.shape[1]}), please choose a " + "lower rank." + ) + + lora_B = U[:, :effective_rank] * S[:effective_rank] + lora_A = V[:effective_rank] + return lora_A.to(orig_dtype).contiguous(), lora_B.to(orig_dtype).contiguous(), effective_rank + + # Standard or mini: exact conversion using the native rank r + miss = miss_block.float() + r = miss.size(0) + + if miss_fn == "mini": + mini_r = module.miss_mini_r[adapter_name] + miss = miss.repeat(1, out_features // mini_r) + + # lora_A: structured summation matrix, shape (r, in_features) + # lora_A[j, i] = 1 if i % r == j + lora_A = torch.zeros(r, in_features, device=device, dtype=torch.float32) + indices = torch.arange(in_features, device=device) + lora_A[indices % r, indices] = 1.0 + + # lora_B = miss.T, shape (out_features, r) + lora_B = miss.T + + return lora_A.to(orig_dtype).contiguous(), lora_B.to(orig_dtype).contiguous(), r + + +@torch.no_grad() +def _convert_module_to_lora( + module: BaseTunerLayer, rank: float, adapter_name: str = "default" +) -> tuple[torch.Tensor, torch.Tensor, int]: + """Convert a single BaseTunerLayer's adapter weight to a LoRA weight, return A, B, and the effective rank.""" + from peft.tuners.miss.layer import MissLinear + + if isinstance(module, MissLinear): + return _convert_miss_module_to_lora(module, rank, adapter_name) + + delta_weight = module.get_delta_weight(adapter_name) + # Note: Explore different algorithms (truncated, randomized, ...) to see if they are more efficient + + orig_dtype = delta_weight.dtype + delta_weight = delta_weight.float() # SVD not implemented for half-precision types + U, S, V = torch.linalg.svd(delta_weight, full_matrices=False) + if isinstance(rank, int): + effective_rank = rank + else: + # float => interpret as threshold + effective_rank = _find_cutoff_index(S, threshold=rank) + + if effective_rank > U.shape[1]: + raise ValueError( + f"The chosen rank {effective_rank} is larger than the weight shape ({U.shape[1]}), please choose a lower " + "rank." + ) + + lora_B = U[:, :effective_rank] * S[:effective_rank] + lora_A = V[:effective_rank] + lora_A, lora_B = lora_A.to(orig_dtype), lora_B.to(orig_dtype) + + if isinstance(module.get_base_layer(), Conv1D): + # Conv1D => original weight is transposed compared to Linear + return lora_B.T.contiguous(), lora_A.T.contiguous(), effective_rank + return lora_A.contiguous(), lora_B.contiguous(), effective_rank + + +def convert_to_lora( + model: torch.nn.Module, + rank: float, + adapter_name: str = "default", + progressbar: bool = False, + compile_kwargs=None, +) -> tuple[LoraConfig, dict[str, torch.Tensor]]: + """ + Convert a non-LoRA model with PEFT layers to a LoRA checkpoint. + + This is only supported for some specific PEFT methods that allow an equivalent conversion. Essentially, this comes + down to PEFT methods that work by updating the base weight with a delta weight. Also, right now, only linear layers + are supported. + + The LoRA adapter will try to approximate the initial adapter as close as possible. The higher the rank, the better + the approximation. It is expected that the approximation will never reach the full performance of the original + adapter, and that the parameter efficiency of the LoRA adapter will be less than that of the original adapter (i.e. + for a similar performance, it will require more parameters). The conversion can still be useful in many situations: + + - In PEFT, LoRA supports more features than most other methods, e.g. mixed adapter batches. Thus the converted + adapter can be used with those features. + - Some downstream packages support LoRA adapters, but not other PEFT methods, e.g. Diffusers. The conversion allows + to use a non-LoRA adapter with those packages. + + The LoRA scaling factor is already baked into the LoRA weights, thus the scaling will always be one (i.e. rank and + alpha are chosen to be identical). + + Note: This function does not support sharded models (yet). + + Args: + model: + The model to be converted. Should be a model that has PEFT layers that support conversion. + rank (`int` or `float`): + The desired rank for the returned LoRA adapter. A higher rank results in a LoRA adapter that more + accurately mirrors the original adapter. It will, however, also require more memory, compute, and disk + space. Therefore, choose a value that represents the best trade off for your use case and validate the + final adapter. If a float is passed, it is interpreted as an explained variance / energy threshold: we pick + the smallest rank k such that the top k singular values account for at least that fraction of the total + squared singular values. This effectively results in lower ranks being assigned if a few singular can + capture the adaptation of this layer. A lower float means the rank is lower and vice versa. Be aware that + dynamic ranks can lead to very unequal ranks per layer, which means that some layers may require a + disproportionally high amount of memory for activations. Choosing a fixed (int) rank is better to achieve + predictable memory requirement. + adapter_name (`str`, *optional*): + The name of the adapter to be converted. Can only convert a single adapter at a time. Defaults to + `"default"`. + progressbar (`bool`): + whether to show a progressbar indicating the progress of the conversion (it can take a few minutes for big + models). + compile_kwargs (`dict`, *optional*): + If provided, compile the function to convert individual modules to LoRA with the given kwargs being passed + to `torch.compile`. This can potentially speed up the conversion on large models. + + Returns: + lora_config (`LoraConfig`) + The `LoraConfig` that corresponds to the converted LoRA adapter. + state_dict (`dict[str, torch.Tensor]`) + The `state_dict` containing the LoRA weights. + + Raises + TypeError: + If the provided model does not have any layers that can be converted to LoRA, a `TypeError` is raised. + ValueError: + If an invalid rank was chosen (too high or too low). + """ + from peft import PeftType # local to avoid circular import + + ########## + # CHECKS # + ########## + + if isinstance(rank, float) and not (0 < rank <= 1): + raise ValueError( + f"If rank is a float, it is interpreted as a threshold. It must be between 0 and 1 but got {rank}." + ) + elif rank == 0: + raise ValueError("Passing a rank of 0 doesn't make sense, please pass a valid value.") + + # check if LoRA conversion is supported at all + modules_not_supporting_lora = [] + num_modules_with_support = 0 + num_modules_total = 0 + for module in model.modules(): + num_modules_total += 1 + if not isinstance(module, BaseTunerLayer): + continue + + if module.supports_lora_conversion(adapter_name): + num_modules_with_support += 1 + else: + modules_not_supporting_lora.append(module) + + unsupported = {repr(type(module)) for module in modules_not_supporting_lora} + if unsupported: + raise TypeError(f"Some module types on this model do not support LoRA conversion: {', '.join(unsupported)}.") + + if num_modules_with_support == 0: + raise TypeError("Could not detect any layer that supports LoRA conversion.") + + peft_config = getattr(model, "peft_config", {}).get(adapter_name) + if (peft_config is not None) and (peft_config.peft_type == PeftType.LORA): + warnings.warn( + "Converting a PEFT adapter to LoRA that is already a LoRA adapter. There is typically no need for that." + ) + + config_bias = getattr(peft_config, "bias", getattr(peft_config, "lora_bias", "none")) + if config_bias != "none": + # TODO: remove if/when we remove support for bias completely + raise ValueError(f"The adapter's config sets bias={config_bias}, this is not supported right now.") + + ############### + # PREPARATION # + ############### + + peft_prefix = "base_model.model." + config_kwargs = { + "rank_pattern": {}, + "alpha_pattern": {}, + "exclude_modules": set(), + } + + if peft_config is not None: + # use the model's PEFT config, if it exists, to initialize the new LoraConfig + peft_config = model.peft_config[adapter_name] + config_kwargs["target_modules"] = copy.copy(peft_config.target_modules) + config_kwargs["base_model_name_or_path"] = peft_config.base_model_name_or_path + if hasattr(peft_config, "layers_pattern"): + # those two go hand in hand + config_kwargs["layers_pattern"] = peft_config.layers_pattern + config_kwargs["layers_to_transform"] = peft_config.layers_to_transform + if isinstance(rank, int): + # hard-coded rank + lora_config = LoraConfig(r=rank, lora_alpha=rank, **config_kwargs) + else: + # r and lora_alpha shouldn't matter, as the rank will be determined by rank/alpha pattern + lora_config = LoraConfig(r=1, lora_alpha=1, **config_kwargs) + else: + # create a new LoraConfig from scratch, inferring the target modules from the model + lora_config = LoraConfig( + r=rank if isinstance(rank, int) else 1, # 1 is a dummy value, actual values will come from rank_pattern + target_modules=[], + **config_kwargs, + ) + + if compile_kwargs is not None: + convert_module_to_lora = torch.compile(_convert_module_to_lora, **compile_kwargs) + else: + convert_module_to_lora = _convert_module_to_lora + + ############## + # CONVERSION # + ############## + + state_dict = {} + for name, module in tqdm( + model.named_modules(), disable=not progressbar, desc="Converting to LoRA", total=num_modules_total + ): + if not isinstance(module, BaseTunerLayer): + continue + if not hasattr(module, "get_delta_weight"): + # if we arrive here, it means that the layer actually does not support LoRA conversion, which should not + # happen + raise TypeError( + f"Module of type {type(module)} does not have a get_delta_weight method, which is required for " + "conversion. Please open an issue: https://github.com/huggingface/peft/issues" + ) + + lora_A, lora_B, effective_rank = convert_module_to_lora(module, rank=rank, adapter_name=adapter_name) + if effective_rank == 0: + # This shouldn't really happen, as we ensure that the rank is greater than 0 (int) or, for thresholds + # (float), at least one SV is included. But better be safe than sorry, as, in principle, it is fine to + # exclude some layers. Also makes this more future proof. + lora_config.exclude_modules.add(name.removeprefix(peft_prefix)) + continue + + # the rank was dynamically adjusted, store it in rank and alpha pattern + if (effective_rank != rank) or isinstance(lora_config.target_modules, str): + # we need to add an entry to rank/alpha pattern iff: + # 1) The effective rank differs from the general rank + # 2) target modules is a string, as we cannot simply append the name to target_modules regex + lora_config.rank_pattern[name.removeprefix(peft_prefix)] = effective_rank + lora_config.alpha_pattern[name.removeprefix(peft_prefix)] = effective_rank + else: + # effective rank is the same and target_modules are a set, just add the name + lora_config.target_modules.add(name.removeprefix(peft_prefix)) + + # don't include adapter_name in key + state_dict[f"{name}.lora_A.weight"] = lora_A + state_dict[f"{name}.lora_B.weight"] = lora_B + + if not state_dict: + # no layer was converted, which should not happen + raise ValueError( + "Did not convert a single layer, this means that something went wrong. Please open an issue: " + "https://github.com/huggingface/peft/issues" + ) + + ################## + # NON-LORA PARTS # + ################## + + if (peft_config is not None) and getattr(peft_config, "modules_to_save", None): + # logic to take care of modules_to_save; might not cover all edge cases, like sharded model + lora_config.modules_to_save = copy.copy(peft_config.modules_to_save) + + for module_name, module in model.named_modules(): + if isinstance(module, ModulesToSaveWrapper): + for param_name, param in module.modules_to_save.named_parameters(): + # it is expected that '.modules_to_save.' is not part of the key + prefix, _, _ = module_name.partition(".modules_to_save.") + # remove the adapter name + _, _, suffix = param_name.rpartition(".") + state_dict[f"{prefix}.{suffix}"] = param.data + + return lora_config, state_dict + + +def save_as_lora( + path: str | os.PathLike, + model: torch.nn.Module, + rank: float, + adapter_name: str = "default", + progressbar: bool = False, + compile_kwargs=None, +) -> None: + """ + Convert a non-LoRA model with PEFT layers to a LoRA, then save the checkpoint file and PEFT config. + + This is only supported for some specific PEFT methods that allow an equivalent conversion. Essentially, this comes + down to PEFT methods that work by updating the base weight with a delta weight. Also, right now, only linear layers + are supported. + + The LoRA adapter will try to approximate the initial adapter as close as possible. The higher the rank, the better + the approximation. It is expected that the approximation will never reach the full performance of the original + adapter, and that the parameter efficiency of the LoRA adapter will be less than that of the original adapter (i.e. + for a similar performance, it will require more parameters). The conversion can still be useful in many situations: + + - In PEFT, LoRA supports more features than most other methods, e.g. mixed adapter batches. Thus the converted + adapter can be used with those features. + - Some downstream packages support LoRA adapters, but not other PEFT methods, e.g. Diffusers. The conversion allows + to use a non-LoRA adapter with those packages. + + The LoRA scaling factor is already baked into the LoRA weights, thus the scaling will always be one (i.e. rank and + alpha are chosen to be identical). + + You can load the converted LoRA weight like this: + + ```py + >>> lora_path = ... + >>> save_as_lora(lora_path, model, rank=...) + >>> base_model = AutoModel.from_pretrained(...) + >>> lora_model = PeftModel.from_pretrained(base_model, lora_path) + ``` + + Note: This function does not support sharded models (yet). + + Args: + model: + The model to be converted. Should be a model that has PEFT layers that support conversion. + rank (`int` or `float`): + The desired rank for the returned LoRA adapter. A higher rank results in a LoRA adapter that more + accurately mirrors the original adapter. It will, however, also require more memory, compute, and disk + space. Therefore, choose a value that represents the best trade off for your use case and validate the + final adapter. If a float is passed, it is interpreted as an explained variance / energy threshold: we pick + the smallest rank k such that the top k singular values account for at least that fraction of the total + squared singular values. This effectively results in lower ranks being assigned if a few singular can + capture the adaptation of this layer. A lower float means the rank is lower and vice versa. Be aware that + dynamic ranks can lead to very unequal ranks per layer, which means that some layers may require a + disproportionally high amount of memory for activations. Choosing a fixed (int) rank is better to achieve + predictable memory requirement. + adapter_name (`str`, *optional*): + The name of the adapter to be converted. Can only convert a single adapter at a time. Defaults to + `"default"`. + progressbar (`bool`): + whether to show a progressbar indicating the progress of the conversion (it can take a few minutes for big + models). + compile_kwargs (`dict`, *optional*): + If provided, compile the function to convert individual modules to LoRA with the given kwargs being passed + to `torch.compile`. This can potentially speed up the conversion on large models. + + Raises + TypeError: + If the provided model does not have any layers that can be converted to LoRA, a `TypeError` is raised. + ValueError: + If an invalid rank was chosen (too high or too low). + """ + path = pathlib.Path(path) + if not path.exists(): + os.makedirs(path) + + lora_config, state_dict = convert_to_lora( + model, rank=rank, adapter_name=adapter_name, progressbar=progressbar, compile_kwargs=compile_kwargs + ) + save_file(state_dict, path / SAFETENSORS_WEIGHTS_NAME) + lora_config.save_pretrained(str(path)) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/corda.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/corda.py new file mode 100644 index 0000000000000000000000000000000000000000..9a28abe82ec439f61062bf921648db52ebae4a88 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/corda.py @@ -0,0 +1,370 @@ +# 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. + +# Reference code: https://github.com/iboing/CorDA/blob/main/cordalib/decomposition.py +# Reference paper: https://huggingface.co/papers/2406.05223 + +import os +from collections.abc import Callable, Iterable +from typing import Any, Optional + +import torch +from attr import dataclass +from torch import nn +from tqdm import tqdm +from transformers.pytorch_utils import Conv1D + +from peft.tuners.lora.config import LoraConfig +from peft.tuners.lora.model import LoraModel +from peft.utils.other import get_pattern_key + + +@dataclass +class CordaEigens: + S_WC: torch.Tensor + U_WC: torch.Tensor + V_WC: torch.Tensor + + +def target_modules(model: nn.Module, config: LoraConfig) -> Iterable[nn.Module]: + """ + Iterate over CorDA 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.type + + +@torch.no_grad() +def preprocess_corda( + model: nn.Module, + lora_config: LoraConfig, + run_model: Optional[Callable[[], None]] = None, + hooked_model: Optional[nn.Module] = None, +): + """ + Build necessary CorDA fields for a model. + + For each `M * N` linear layer, a `M * M` covariance matrix will be built temporarily during the preprocessing + process, consuming roughly another `2 * MODEL_SIZE` memory for typical LLMs if model weight is FP16 and covariance + is FP32. If that's too much, consider specifying `use_float16_for_covariance` in `lora_config.corda_config`. + + Args: + model (`nn.Module`): + Model to preprocess. + lora_config (`LoraConfig`): + Lora configuration of the model. `lora_config.corda_config` should be set. + run_model (`Optional[Callable[[], None]]`): + Callback to run the model when building covariance. Typically you should run model inference on your sample + dataset in this callback. Experiments have shown that when token count per sample is 2048, hidden dimension + is 4096, collecting 256 distinct samples is enough. If you collect too few or too repetitive samples, the + covariance matrix may be low-ranked and unstabilize preprocessing. You can estimate sample count as + `HIDDEN_DIM / TOKEN_PER_SAMPLE * 128`. `run_model` can be `None` only if covariance file in + `lora_config.corda_config` is already created. + hooked_model (`Optional[nn.Module]`): + Model to hook when building covariance. If none, original model will be hooked. This is only useful when + you want to hook a different model than the one you are training, typically you should leave this `None`. + + Upon completion, the following fields are set for each target module: + eigens.S_WC (`torch.Tensor`): + Singular values of the weight matrix. + eigens.U_WC (`torch.Tensor`): + Left singular vectors of the weight matrix. + eigens.V_WC (`torch.Tensor`): + Right singular vectors of the weight matrix, multiplied by inverse of covariance matrix. + """ + cache_file = lora_config.corda_config.cache_file + covariance_file = lora_config.corda_config.covariance_file + corda_method = lora_config.corda_config.corda_method + verbose = lora_config.corda_config.verbose + prune_temporary_fields = lora_config.corda_config.prune_temporary_fields + + # If cache exists, skip building + 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 target_modules(model, lora_config): + module.eigens = CordaEigens( + S_WC=cache[f"{name}.eigens.S_WC"], + U_WC=cache[f"{name}.eigens.U_WC"], + V_WC=cache[f"{name}.eigens.V_WC"], + ) + else: + # Specify CorDA method for each layer + if corda_method is None: + raise ValueError("corda_method is required when cache_file is not provided.") + for name, module in target_modules(model, lora_config): + module.corda_method = corda_method + + # Specify CorDA rank for each layer + for name, module in target_modules(model, lora_config): + r_key = get_pattern_key(lora_config.rank_pattern.keys(), name) + module.rank = lora_config.rank_pattern.get(r_key, lora_config.r) + + # Calculate covariance matrix + calib_cov_distribution(model, lora_config, run_model, hooked_model, covariance_file) + + # Calculate eigens + collect_eigens(model, lora_config, verbose) + + # Crop CorDA eigens so that there's less to save + crop_corda_eigens(model, lora_config) + + # Remove redundant fields if exist + if prune_temporary_fields: + for name, module in target_modules(model, lora_config): + if hasattr(module, "sample_count"): + del module.sample_count + if hasattr(module, "covariance_matrix"): + del module.covariance_matrix + if hasattr(module, "corda_method"): + del module.corda_method + if hasattr(module, "rank"): + del module.rank + + # Save cache to disk + if cache_file is not None: + cache: dict[str, Any] = {} + for name, module in target_modules(model, lora_config): + cache[f"{name}.eigens.S_WC"] = module.eigens.S_WC + cache[f"{name}.eigens.U_WC"] = module.eigens.U_WC + cache[f"{name}.eigens.V_WC"] = module.eigens.V_WC + + os.makedirs(os.path.dirname(cache_file), exist_ok=True) + torch.save(cache, cache_file) + + +@torch.no_grad() +def calib_cov_distribution( + model: nn.Module, + config: LoraConfig, + run_model: Optional[Callable[[], None]], + hooked_model: Optional[nn.Module], + covariance_file: Optional[str], +): + if covariance_file is not None and os.path.exists(covariance_file) and os.path.getsize(covariance_file) > 0: + all_covariance_matrix = torch.load(covariance_file, map_location=get_model_device(model)) + for name, module in target_modules(model, config): + module.covariance_matrix = all_covariance_matrix[name] + return + + if run_model is None: + raise ValueError("run_model must be specified when covariance file and cache file aren't built.") + if hooked_model is None: + hooked_model = model + hooked_model.eval() + + def hook(module, input, output): + input = input[0].detach().squeeze(0).data ## (context_length = 2048, dim) + if not config.corda_config.use_float16_for_covariance: + input = input.float() + input = input / torch.max(input).abs() + + # check if input is valid + if torch.isnan(input).any() or torch.isinf(input).any(): + raise ValueError("Invalid value found in input, please check your input data.") + + # calculate covariance and check if it's valid + covariance = input.t().matmul(input) + if torch.isnan(covariance).any() or torch.isinf(covariance).any(): + raise ValueError( + "Invalid value found in covariance. Please file an issue at https://github.com/huggingface/peft/issues." + ) + + # add to module + module.sample_count += 1 + module.covariance_matrix += covariance + + # free memory + del covariance, input + + handles = [] + for name, module in target_modules(hooked_model, config): + module.sample_count = 0 + module.covariance_matrix = 0 + handles.append(module.register_forward_hook(hook)) + + run_model() + + # Clear the hooks + for handle in handles: + handle.remove() + + # In some edge cases you might need to hook a model different from the model to add adapters, + # this case you would specify `hooked_model` and set it to a different model from `model`. + if hooked_model is not model: + targets = {} + for name, module in target_modules(model, config): + targets[name] = module + for name, module in target_modules(hooked_model, config): + # There can be modules used only in inference, but not training + # Exclude modules not in target model to prevent KeyError in this case + if name in targets: + targets[name].sample_count = module.sample_count + targets[name].covariance_matrix = module.covariance_matrix + + # Divide by sample count + for name, module in target_modules(model, config): + module.covariance_matrix /= module.sample_count + + # Save covariance to disk + if covariance_file is not None: + all_covariance_matrix = {} + for name, module in target_modules(model, config): + all_covariance_matrix[name] = module.covariance_matrix + os.makedirs(os.path.dirname(covariance_file), exist_ok=True) + torch.save(all_covariance_matrix, covariance_file) + + +@torch.no_grad() +def collect_eigens( + model: nn.Module, + config: LoraConfig, + verbose: bool, +): + """Call collect_eigens_for_layer and store result in key `eigens` of each layer.""" + linear_modules = [] + for name, module in target_modules(model, config): + linear_modules.append((name, module)) + if verbose: + linear_modules = tqdm(linear_modules, desc="Collecting eigens") + for name, module in linear_modules: + module.eigens = collect_eigens_for_layer(module, config) + + +@torch.no_grad() +def collect_eigens_for_layer( + linear: nn.Module, + config: LoraConfig, +) -> CordaEigens: + w = linear.weight.data.float() + # Conv1D stores weights as (in_features, out_features), transposed compared to Linear + # We need to transpose it to match Linear's (out_features, in_features) layout for SVD + if isinstance(linear, Conv1D): + w = w.T + out_dim = w.size(0) + in_dim = w.size(1) + min_dim = min(in_dim, out_dim) + + if not hasattr(linear, "covariance_matrix"): + raise ValueError( + "Covariance matrix not found in linear module. Please do not call this function directly, " + "instead call `preprocess_corda`. If your usage is correct but this error still encounters, " + "please file an issue at https://github.com/huggingface/peft/issues." + ) + covariance_matrix = linear.covariance_matrix.float() + + damp = 0.01 + while True: + compensate = torch.diag( + torch.ones(covariance_matrix.size(0)).to(covariance_matrix.device) + * torch.mean(torch.diag(covariance_matrix)) + * damp + ) + fix_covariance_matrix = covariance_matrix + compensate + cov_inv = torch.linalg.inv(fix_covariance_matrix) + inv_error = torch.dist( + fix_covariance_matrix @ cov_inv, torch.eye(covariance_matrix.size(0)).to(get_model_device(linear)) + ).item() + if inv_error < 0.05: + break + else: + damp = damp * 2 + w = w @ fix_covariance_matrix ## w: out_dim, in_dim; covariance_matrix: in_dim, in_dim + + U, S, Vh = torch.linalg.svd(w, full_matrices=False) + V = (Vh @ cov_inv).transpose(0, 1) + + # Sanity check, temporarily U and V are large, they will be crop after rank search + r = min_dim + if U.size(0) != out_dim or U.size(1) != r: + raise ValueError( + f"Matrix U size mismatch: {U.size()} vs. ({out_dim}, {r}), " + "please file an issue at https://github.com/huggingface/peft/issues." + ) + if S.size(0) != r: + raise ValueError( + f"Matrix S size mismatch: {S.size()} vs. ({r},), " + "please file an issue at https://github.com/huggingface/peft/issues." + ) + if V.size(0) != in_dim or V.size(1) != r: + raise ValueError( + f"Matrix V size mismatch: {V.size()} vs. ({in_dim}, {r}), " + "please file an issue at https://github.com/huggingface/peft/issues." + ) + + # Offload U and V to CPU, they consume too much memory + U = U.cpu() + V = V.cpu() + return CordaEigens( + S_WC=S, + U_WC=U, + V_WC=V, + ) + + +@torch.no_grad() +def crop_corda_eigens(model: nn.Module, config: LoraConfig): + for name, module in target_modules(model, config): + # We don't expect saving sliced tensor writes the whole tensor to disk, + # so it's necessary to copy the tensors. + # Reference: https://github.com/pytorch/pytorch/issues/40157 + if module.corda_method == "ipm": + module.eigens.S_WC = module.eigens.S_WC[: module.rank].clone() + module.eigens.U_WC = module.eigens.U_WC[:, : module.rank].clone().to(get_model_device(model)) + module.eigens.V_WC = module.eigens.V_WC[:, : module.rank].clone().to(get_model_device(model)) + elif module.corda_method == "kpm": + module.eigens.S_WC = module.eigens.S_WC[-module.rank :].clone() + module.eigens.U_WC = module.eigens.U_WC[:, -module.rank :].clone().to(get_model_device(model)) + module.eigens.V_WC = module.eigens.V_WC[:, -module.rank :].clone().to(get_model_device(model)) + else: + raise ValueError(f"Invalid corda_method found: {module.corda_method}, it should be 'ipm' or 'kpm'.") + + # Sanity check + # For Conv1D, weight is stored as (in_features, out_features), transposed compared to Linear + # But U and V are computed on the transposed weight, so we need to account for this + weight_out_dim = module.weight.size(1) if isinstance(module, Conv1D) else module.weight.size(0) + weight_in_dim = module.weight.size(0) if isinstance(module, Conv1D) else module.weight.size(1) + + if module.eigens.S_WC.size(0) != module.rank: + raise ValueError( + f"rank mismatch: {module.eigens.S_WC.size(0)} vs. {module.rank}," + "please file an issue at https://github.com/huggingface/peft/issues." + ) + if module.eigens.U_WC.size(0) != weight_out_dim: + raise ValueError( + f"U size mismatch: {module.eigens.U_WC.size(0)} vs. {weight_out_dim}," + "please file an issue at https://github.com/huggingface/peft/issues." + ) + if module.eigens.U_WC.size(1) != module.rank: + raise ValueError( + f"U size mismatch: {module.eigens.U_WC.size(1)} vs. {module.rank}," + "please file an issue at https://github.com/huggingface/peft/issues." + ) + if module.eigens.V_WC.size(0) != weight_in_dim: + raise ValueError( + f"V size mismatch: {module.eigens.V_WC.size(0)} vs. {weight_in_dim}," + "please file an issue at https://github.com/huggingface/peft/issues." + ) + if module.eigens.V_WC.size(1) != module.rank: + raise ValueError( + f"V size mismatch: {module.eigens.V_WC.size(1)} vs. {module.rank}," + "please file an issue at https://github.com/huggingface/peft/issues." + ) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/dora.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/dora.py new file mode 100644 index 0000000000000000000000000000000000000000..f7a397fe51b5c6959c93d57e06660e40fafa0d8d --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/eetq.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/eetq.py new file mode 100644 index 0000000000000000000000000000000000000000..fe182fb50fd2efdc75d1c8b66b7fc96cb89e7f3b --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/eetq.py @@ -0,0 +1,123 @@ +# 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.lora.layer import LoraLayer +from peft.tuners.tuners_utils import BaseTunerLayer + +from .config import LoraConfig + + +if is_eetq_available(): + from eetq import EetqLinear + + try: + from transformers.integrations.eetq import EetqLinear as TransformersEetqLinear + + # in newer transformers versions, EETQ quantization uses a transformers-specific class + eetq_classes = (EetqLinear, TransformersEetqLinear) + except ImportError: + eetq_classes = (EetqLinear,) + + class EetqLoraLinear(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") + if config.velora_config is not None: + raise ValueError(f"{self.__class__.__name__} does not support VeLoRA 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 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 "lora." + rep + + +def dispatch_eetq( + 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_eetq_available() and isinstance(target_base_layer, eetq_classes): + new_module = EetqLoraLinear(target, adapter_name, config=config, **kwargs) + target.weight = target_base_layer.weight + + if hasattr(target, "bias"): + target.bias = target_base_layer.bias + + return new_module diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/eva.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/eva.py new file mode 100644 index 0000000000000000000000000000000000000000..bc895d1a724da84bd81d7ebd95ccc7ad2875301c --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/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 TypeError( + 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 TypeError("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 ("labels" in model_input): + 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 TypeError( + 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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/gptq.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/gptq.py new file mode 100644 index 0000000000000000000000000000000000000000..7f787183957d260c85d2a1d20c875f060c298db2 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/gptq.py @@ -0,0 +1,133 @@ +# 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.tuners.lora.layer import LoraLayer +from peft.tuners.tuners_utils import BaseTunerLayer + +from ...import_utils import is_gptqmodel_available +from .config import LoraConfig +from .layer import LoraVariant + + +class GPTQLoraLinear(torch.nn.Module, LoraLayer): + def __init__( + self, + base_layer, + adapter_name: str, + config: LoraConfig, + r: int = 0, + lora_alpha: int = 1, + **kwargs, + ): + super().__init__() + LoraLayer.__init__(self, base_layer) + + if config.use_dora: + raise ValueError(f"{self.__class__.__name__} does not support DoRA yet, please set it to False") + if config.velora_config is not None: + raise ValueError(f"{self.__class__.__name__} does not support VeLoRA yet, please set it to False") + + # 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 resolve_lora_variant(self, *, config: LoraConfig, **kwargs) -> Optional[LoraVariant]: + if config.velora_config is not None: + raise ValueError(f"{self.__class__.__name__} does not support VeLoRA.") + if config.use_dora and config.use_qalora: + raise NotImplementedError( + f"DoRA and QA-LoRA at the same time is not supported for {self.__class__.__name__} (yet)." + ) + elif config.use_dora: + from .variants import DoraLinearVariant + + variant = DoraLinearVariant() + elif config.use_qalora: + from .variants import QALoraLinearVariant + + variant = QALoraLinearVariant() + else: + variant = None + return variant + + def forward(self, x: torch.Tensor): + # note: logic differs from default Linear because merging is not supported + result = self.quant_linear_module(x) + + if self.disable_adapters: + return result + + lora_A_keys = self.lora_A.keys() + + for active_adapter in self.active_adapters: + if active_adapter not in lora_A_keys: + continue + torch_result_dtype = result.dtype + + 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] + + 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, + ) + + result = result.to(torch_result_dtype) + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "lora." + rep + + +def dispatch_gptq( + 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 import BaseQuantLinear + + if isinstance(target_base_layer, BaseQuantLinear): + new_module = GPTQLoraLinear(target, adapter_name, config=config, **kwargs) + target.qweight = target_base_layer.qweight + + return new_module diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/hqq.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/hqq.py new file mode 100644 index 0000000000000000000000000000000000000000..0e29127b4315558e77b24406416d57dadaea0e6a --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/hqq.py @@ -0,0 +1,246 @@ +# 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 config.velora_config is not None: + raise ValueError(f"{self.__class__.__name__} does not support VeLoRA.") + 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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/inc.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/inc.py new file mode 100644 index 0000000000000000000000000000000000000000..60d92ea851d207aa987e750c4fbd73bf1d6cb6c0 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/inc.py @@ -0,0 +1,80 @@ +# 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 .config import LoraConfig +from .layer import Linear + + +if is_inc_available(): + + class IncLoraLinear(Linear): + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + config: LoraConfig, + **kwargs, + ): + super().__init__(base_layer, adapter_name, config=config, **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 LoRA 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 LoRA from INC layers is not yet implemented") + + +def dispatch_inc(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_inc_available(): + from neural_compressor.torch.algorithms.fp8_quant._quant_common.helper_modules import ( + PatchedLinear, + ) + + if isinstance(target_base_layer, PatchedLinear): + new_module = IncLoraLinear(target, adapter_name, config=config, **kwargs) + + return new_module diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/intruders.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/intruders.py new file mode 100644 index 0000000000000000000000000000000000000000..81f0ae479087ef8ed2010dc7f6aeeec5c3d21635 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/layer.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..1a071583085eabd266a6358631b42de7d44d21fb --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/layer.py @@ -0,0 +1,2536 @@ +# 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 copy +import math +import warnings +from collections.abc import Callable +from contextlib import contextmanager +from typing import Any, Optional, Union + +import torch +import torch.distributed as dist +import torch.nn.functional as F +from torch import nn, svd_lowrank +from transformers.pytorch_utils import Conv1D + +from peft.import_utils import is_transformers_ge_v5_4_0 +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 import ALLOWED_COMPUTE_DTYPES, UPCAST_DTYPES +from peft.utils.integrations import ( + dequantize_module_weight, + gather_params_ctx, + get_bnb_param_type, + skip_init_on_device, +) +from peft.utils.loftq_utils import loftq_init +from peft.utils.other import transpose +from peft.utils.warning import PeftWarning + +from .config import LoraConfig + + +VARIANT_KWARG_KEYS = ["alora_offsets"] + + +class LoraVariant: + """ + Base class for LoRA variants, e.g. DoRA. + + This class should be subclassed and the methods below should be implemented accordingly. The methods should be + implemented as static methods, this makes it easier to combine variants. + + Note for developers: These methods are prone to change and should thus considered to be "private". Use at your own + discretion. + """ + + @staticmethod + def init(module: LoraLayer, adapter_name: str) -> None: + """Initialization code for the LoRA variant, it's called within `update_layer`""" + raise NotImplementedError + + @staticmethod + def merge_safe(module: LoraLayer, active_adapter: str, orig_weight: torch.Tensor) -> torch.Tensor: + """Safe merging of the weights from `merge(..., safe_merge=True)`, should return a new tensor""" + raise NotImplementedError + + @staticmethod + def merge_unsafe(module: LoraLayer, active_adapter: str, orig_weight: torch.Tensor) -> None: + """Unsafe merging of the weights from `merge(..., safe_merge=False)`, should modify the weight in-place""" + + @staticmethod + def unmerge(module: LoraLayer, active_adapter: str, orig_weight: torch.Tensor) -> torch.Tensor: + """Remove the adapter weights from the original weights, then return them""" + + @staticmethod + def forward( + module: LoraLayer, + active_adapter: str, + x: torch.Tensor, + result: torch.Tensor, + **kwargs, + ) -> torch.Tensor: + """ + The forward pass of the LoRA variant, should return the overall result (not just the diff) + + Args: + module (LoraLayer): The module on which the forward pass is called + active_adapter (str): The name of the active adapter + x (torch.Tensor): The input to the forward call + result (torch.Tensor): The result from the base model + **kwargs: Additional arguments passed from [`LoraLayer.forward`]. + """ + raise NotImplementedError + + +class LoraLayer(BaseTunerLayer): + # All names of layers that may contain (trainable) adapter weights + adapter_layer_names: tuple[str, ...] = ("lora_A", "lora_B", "lora_embedding_A", "lora_embedding_B") + # All names of other parameters that may contain adapter-related parameters + other_param_names: tuple[str, ...] = ("r", "lora_alpha", "scaling", "lora_dropout") + + def __init__(self, base_layer: nn.Module, ephemeral_gpu_offload: bool = False, **kwargs) -> None: + self.base_layer = base_layer + self.r = {} + self.lora_alpha = {} + self.scaling = {} + self.lora_dropout = nn.ModuleDict({}) + self.lora_A = nn.ModuleDict({}) + self.lora_B = nn.ModuleDict({}) + # For Embedding layer + self.lora_embedding_A = nn.ParameterDict({}) + self.lora_embedding_B = nn.ParameterDict({}) + # Mark the weight as unmerged + self._disable_adapters = False + self.merged_adapters = [] + self.use_dora: dict[str, bool] = {} # not actively used anymore after #2443, keep it for BC + self.use_rslora: dict[str, bool] = {} + self.lora_bias: dict[str, bool] = {} + self.lora_magnitude_vector = torch.nn.ModuleDict() # for DoRA + self._caches: dict[str, Any] = {} # small ad hoc cache; values are not part of the state_dict + self.ephemeral_gpu_offload: bool = ephemeral_gpu_offload + # flag to enable/disable casting of input to weight dtype during forward call + self.cast_input_dtype_enabled: bool = True + self.lora_variant: dict[str, LoraVariant] = {} + self.kwargs = kwargs + + base_layer = self.get_base_layer() + in_features, out_features = self._get_in_out_features(base_layer) + self.in_features = in_features + self.out_features = out_features + + def _get_in_out_features(self, module: nn.Module) -> tuple[int, int] | tuple[None, None]: + return _get_in_out_features(module) + + def resolve_lora_variant(self, *, config: LoraConfig, **kwargs) -> Optional[LoraVariant]: + """Return a matching LoRA variant for this layer type. + + Given the init arguments of this layer, return the correct LoRA variant, if any. E.g., if `use_dora=True`, this + method should return the DoRA variant for the given layer. If `use_alora=True`, same for aLoRA. + + If there is no fitting variant, return None. + + Note: If this layer type does not support the LoRA variant at all, please raise an error during __init__ as is + convention, and not here. + + """ + return None + + def update_layer( + self, + adapter_name: str, + r: int, + lora_alpha: int, + config: LoraConfig, + **kwargs, + ) -> None: + # collect the kwargs + lora_dropout = config.lora_dropout + init_lora_weights = config.init_lora_weights + use_rslora = config.use_rslora + lora_bias = config.lora_bias + inference_mode = config.inference_mode + + target_name = kwargs.get("target_name", "") # preserve target_name before overwriting kwargs + kwargs["target_name"] = target_name # restore target_name + tied_adapter = kwargs.get("tied_adapter", None) + + # This code works for linear layers, override for other layer types + if r <= 0: + raise ValueError(f"`r` should be a positive integer value but the value passed is {r}") + + if lora_bias and (getattr(self.get_base_layer(), "bias", None) is None): + warnings.warn( + f"`lora_bias=True` was passed but the targeted layer of type {type(self.get_base_layer()).__name__} " + "has no bias. This means that merging LoRA weights won't be possible.", + PeftWarning, + ) + + lora_variant = self.resolve_lora_variant(config=config) + if lora_variant is not None: + self.lora_variant[adapter_name] = lora_variant + + self.r[adapter_name] = r + self.lora_alpha[adapter_name] = lora_alpha + if lora_dropout > 0.0: + lora_dropout_layer = nn.Dropout(p=lora_dropout) + else: + lora_dropout_layer = nn.Identity() + + self.lora_dropout.update(nn.ModuleDict({adapter_name: lora_dropout_layer})) + + # Actual trainable parameters + self.lora_A[adapter_name] = nn.Linear(self.in_features, r, bias=False) + self.lora_B[adapter_name] = nn.Linear(r, self.out_features, bias=lora_bias) + + # Tying adapters is only implemented for Linear layers + # where the source is the embedding layer. + # Currently, this is the most prevelant way of tying layers (weight tying) + if tied_adapter: + lora_A_params = tied_adapter["lora_A"] + lora_B_params = tied_adapter["lora_B"] + + self.lora_A[adapter_name].weight = torch.nn.Parameter(lora_A_params) + self.lora_B[adapter_name].weight = torch.nn.Parameter(lora_B_params) + + self.lora_bias[adapter_name] = lora_bias + + if use_rslora: + self.scaling[adapter_name] = lora_alpha / math.sqrt(r) + else: + self.scaling[adapter_name] = lora_alpha / r + + self.use_rslora[adapter_name] = use_rslora + + self.use_dora[adapter_name] = config.use_dora + + # for inits that require access to the base weight, use gather_param_ctx so that the weight is gathered when using DeepSpeed + if isinstance(init_lora_weights, str) and init_lora_weights.startswith("pissa"): + with gather_params_ctx(self.get_base_layer().weight): + self.pissa_init(adapter_name, init_lora_weights) + elif isinstance(init_lora_weights, str) and init_lora_weights.startswith("corda"): + with gather_params_ctx(self.get_base_layer().weight): + self.corda_init(adapter_name, init_lora_weights) + elif isinstance(init_lora_weights, str) and init_lora_weights.lower() == "olora": + with gather_params_ctx(self.get_base_layer().weight): + self.olora_init(adapter_name) + elif init_lora_weights == "loftq": + with gather_params_ctx(self.get_base_layer().weight): + self.loftq_init(adapter_name, config) + elif init_lora_weights == "eva": + nn.init.zeros_(self.lora_B[adapter_name].weight) + elif init_lora_weights == "orthogonal": + with gather_params_ctx(self.get_base_layer().weight): + self.orthogonal_init(adapter_name) + elif init_lora_weights == "lora_ga": + with gather_params_ctx(self.get_base_layer().weight): + self.lora_ga_init(adapter_name, config.lora_ga_config) + elif init_lora_weights: + self.reset_lora_parameters(adapter_name, init_lora_weights) + # call this before init of the lora variants + self._move_adapter_to_device_of_base_layer(adapter_name) + + if adapter_name in self.lora_variant: + self.lora_variant[adapter_name].init(self, adapter_name=adapter_name, config=config, **kwargs) + + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + # Check for adapters that were added or removed from the arrow_model. + # The arrow model may be modified after creation by adding new experts + # (pre-trained or trainable) or by removing existing ones. Whenever such + # a change occurs, on_adapter_change() is called to update the set of + # active task-specific experts and, if needed, to handle recomputing prototypes + # and doing general knowledge subtraction (GKS) again. + if hasattr(self, "lora_arrow"): + for adapter in self.lora_variant: + if adapter in self.lora_arrow: + self.lora_arrow[adapter].on_adapter_change(self.lora_A, self.lora_B) + + def reset_lora_parameters(self, adapter_name, init_lora_weights): + if init_lora_weights is not False: + if adapter_name in self.lora_A.keys(): + if init_lora_weights is True: + # initialize A the same way as the default for nn.Linear and B to zero + # https://github.com/microsoft/LoRA/blob/a0a92e0f26c067cf94747bdbf1ce73793fa44d19/loralib/layers.py#L124 + nn.init.kaiming_uniform_(self.lora_A[adapter_name].weight, a=math.sqrt(5)) + elif init_lora_weights.lower() == "gaussian": + nn.init.normal_(self.lora_A[adapter_name].weight, std=1 / self.r[adapter_name]) + else: + raise ValueError(f"Unknown initialization {init_lora_weights=}") + nn.init.zeros_(self.lora_B[adapter_name].weight) + if self.lora_bias[adapter_name]: + nn.init.zeros_(self.lora_B[adapter_name].bias) + if adapter_name in self.lora_embedding_A.keys(): + # Initialize A to zeros and B the same way as the default for nn.Embedding, see: + # https://github.com/microsoft/LoRA/blob/4c0333854cb905966f8cc4e9a74068c1e507c7b7/loralib/layers.py#L59-L60 + nn.init.zeros_(self.lora_embedding_A[adapter_name]) + nn.init.normal_(self.lora_embedding_B[adapter_name]) + if self.lora_bias[adapter_name]: + # embeddings are not supported at the moment, but still adding this for consistency + nn.init.zeros_(self.lora_embedding_B[adapter_name].bias) + + # Always synchronize non-sharded LoRA weights across TP ranks, regardless of + # init_lora_weights, since each rank initializes weights independently. + # We could skip some broadcast, for instance when the lora weights are initialized to zero, + # but this is a minor optimization and would add extra complexity to the code. + if dist.is_available() and dist.is_initialized(): + base_layer = self.get_base_layer() + tp_plan = getattr(base_layer, "_hf_tp_plan", None) + device_mesh = getattr(base_layer, "_hf_device_mesh", None) + if device_mesh is not None: + if tp_plan not in ["colwise", "rowwise", "embedding_rowwise"]: + warnings.warn( + f'tp_plan "{tp_plan}" found on the base layer is not supported for LoRA weight ' + 'synchronization. Expected one of "colwise", "rowwise", "embedding_rowwise". ' + "LoRA weights may not be synchronized across ranks." + ) + pg = device_mesh.get_group() + src = dist.get_global_rank(pg, 0) + if tp_plan == "colwise" and adapter_name in self.lora_A: + # The adapter weights need to be on device for broadcasting + self._move_adapter_to_device_of_base_layer(adapter_name) + dist.broadcast(self.lora_A[adapter_name].weight.data, src=src, group=pg) + elif tp_plan == "rowwise" and adapter_name in self.lora_B: + # The adapter weights need to be on device for broadcasting + self._move_adapter_to_device_of_base_layer(adapter_name) + dist.broadcast(self.lora_B[adapter_name].weight.data, src=src, group=pg) + elif tp_plan == "embedding_rowwise" and adapter_name in self.lora_embedding_B: + self._move_adapter_to_device_of_base_layer(adapter_name) + dist.broadcast(self.lora_embedding_B[adapter_name].data, src=src, group=pg) + + def olora_init(self, adapter_name): + base_layer = self.get_base_layer() + orig_weight = base_layer.weight + bnb_param_type = get_bnb_param_type(orig_weight) + dtype = orig_weight.dtype + + if bnb_param_type: + # check without importing bitsandbytes and robust to bnb_4bit_quant_storage=float* + weight_tensor = dequantize_module_weight(base_layer) + elif dtype in [torch.float32, torch.float16, torch.bfloat16]: + weight_tensor = orig_weight + else: + raise TypeError(f"Unsupported data type for the base layer. Got {dtype}.") + + scale_factor = self.scaling[adapter_name] + r = self.r[adapter_name] + weight_tensor = weight_tensor.to(torch.float32) + Q, R = torch.linalg.qr(weight_tensor.data) + + Qr, Rr = Q[:, :r], R[:r] + + self.lora_A[adapter_name].weight.data = Rr.contiguous() + self.lora_B[adapter_name].weight.data = Qr.contiguous() + + weight_tensor.data -= scale_factor * self.lora_B[adapter_name].weight @ self.lora_A[adapter_name].weight + if bnb_param_type == "4bit": + weight_tensor = orig_weight.__class__( + weight_tensor, + quant_type=orig_weight.quant_type, + quant_storage=orig_weight.quant_storage, + compress_statistics=orig_weight.compress_statistics, + module=orig_weight.module, + ).to(orig_weight.device) + base_layer.weight = weight_tensor + elif bnb_param_type == "8bit": + weight_tensor = orig_weight.__class__( + weight_tensor, + requires_grad=orig_weight.requires_grad, + has_fp16_weights=orig_weight.has_fp16_weights, + ).to(orig_weight.device) + base_layer.weight = weight_tensor + else: + weight_tensor = weight_tensor.to(dtype) + base_layer.weight.data = weight_tensor + + def pissa_init(self, adapter_name, init_lora_weights): + weight = self.get_base_layer().weight + dtype = weight.dtype + if dtype not in [torch.float32, torch.float16, torch.bfloat16]: + raise TypeError( + "Please initialize PiSSA under float32, float16, or bfloat16. " + "Subsequently, re-quantize the residual model to help minimize quantization errors." + ) + weight = transpose(weight.to(torch.float32), self.fan_in_fan_out) + if init_lora_weights == "pissa": + # USV^T = W <-> VSU^T = W^T, where W^T = weight.data in R^{out_channel, in_channel}, + V, S, Uh = torch.linalg.svd(weight.data, full_matrices=False) + Vr = V[:, : self.r[adapter_name]] + Sr = S[: self.r[adapter_name]] + Sr /= self.scaling[adapter_name] + Uhr = Uh[: self.r[adapter_name]] + elif len(init_lora_weights.split("_niter_")) == 2: + Vr, Sr, Ur = svd_lowrank( + weight.data, self.r[adapter_name], niter=int(init_lora_weights.split("_niter_")[-1]) + ) + Sr /= self.scaling[adapter_name] + Uhr = Ur.t() + else: + raise ValueError( + f"init_lora_weights should be 'pissa' or 'pissa_niter_[number of iters]', got {init_lora_weights} instead." + ) + + lora_A = torch.diag(torch.sqrt(Sr)) @ Uhr + lora_B = Vr @ torch.diag(torch.sqrt(Sr)) + self.lora_A[adapter_name].weight.data = lora_A + self.lora_B[adapter_name].weight.data = lora_B + weight = weight.data - self.scaling[adapter_name] * lora_B @ lora_A + weight = transpose(weight.to(dtype), self.fan_in_fan_out) + self.get_base_layer().weight.data = weight + + def corda_init(self, adapter_name, init_lora_weights): + linear = self.get_base_layer() + weight = linear.weight + dtype = weight.dtype + if dtype not in [torch.float32, torch.float16, torch.bfloat16]: + raise TypeError( + "Please initialize CorDA under float32, float16, or bfloat16. " + "Subsequently, re-quantize the residual model to help minimize quantization errors." + ) + weight = weight.to(torch.float32) + # For Conv1D, weight is stored as (in_features, out_features), transposed compared to Linear + if isinstance(linear, Conv1D): + out_dim = weight.data.size(1) + in_dim = weight.data.size(0) + else: + out_dim = weight.data.size(0) + in_dim = weight.data.size(1) + + # Calculate WC from covariance matrix + if not hasattr(linear, "eigens"): + raise ValueError( + "`eigens` attribute not found for layer, please run `preprocess_corda` first. " + "More information can be found at examples/corda_finetuning/README.md." + ) + eigens = linear.eigens + U = eigens.U_WC + S = eigens.S_WC + V = eigens.V_WC + r = self.r[adapter_name] + + # nan or inf check + if torch.isnan(S).any() or torch.isinf(S).any(): + raise ValueError( + "Invalid value found in matrix S. Please file an issue at https://github.com/huggingface/peft/issues." + ) + if torch.isnan(U).any() or torch.isinf(U).any(): + raise ValueError( + "Invalid value found in matrix U. Please file an issue at https://github.com/huggingface/peft/issues." + ) + if torch.isnan(V).any() or torch.isinf(V).any(): + raise ValueError( + "Invalid value found in matrix V. Please file an issue at https://github.com/huggingface/peft/issues." + ) + + # Sanity check + if U.size(0) != out_dim or U.size(1) != r: + raise ValueError( + f"Matrix U size mismatch: {U.size()} vs. ({out_dim}, {r}). Please make sure the `lora_config` and " + "`model` argument of `preprocess_corda` is consistent with `get_peft_model`. If you're using cache " + "in `preprocess_corda`, please make sure the cache is built with the same model and LoRA rank." + ) + if S.size(0) != r: + raise ValueError( + f"Matrix S size mismatch: {S.size()} vs. ({r},). Please make sure the `lora_config` and `model` argument " + "of `preprocess_corda` is consistent with `get_peft_model`. If you're using cache in `preprocess_corda`, " + "please make sure the cache is built with the same model and LoRA rank." + ) + if V.size(0) != in_dim or V.size(1) != r: + raise ValueError( + f"Matrix V size mismatch: {V.size()} vs. ({in_dim}, {r}). Please make sure the `lora_config` and " + "`model` argument of `preprocess_corda` is consistent with `get_peft_model`. If you're using cache " + "in `preprocess_corda`, please make sure the cache is built with the same model and LoRA rank." + ) + + # Apply alpha + S /= self.scaling[adapter_name] + + # Init lora_A and lora_B weights + lora_A = V.t().mul(S.sqrt().view(-1, 1)).contiguous() + lora_B = U.mul(S.sqrt()).contiguous() + self.lora_A[adapter_name].weight.data = lora_A + self.lora_B[adapter_name].weight.data = lora_B + + # For Conv1D, lora_B @ lora_A gives (out_dim, in_dim) but weight is (in_dim, out_dim) + # So we need to transpose before subtraction + delta = self.scaling[adapter_name] * lora_B @ lora_A + delta = transpose(delta, fan_in_fan_out=self.fan_in_fan_out) + weight = weight.data - delta + weight = weight.to(dtype) + self.get_base_layer().weight.data = weight + + # Remove redundant fields + del linear.eigens + + def loftq_init(self, adapter_name, config: LoraConfig): + weight = self.get_base_layer().weight + kwargs = { + "num_bits": config.loftq_config["loftq_bits"], + "reduced_rank": self.r[adapter_name], + "num_iter": config.loftq_config["loftq_iter"], + } + + qweight, lora_A, lora_B = loftq_init(weight, **kwargs) + if adapter_name in self.lora_A.keys(): + # initialize A the same way as the default for nn.Linear and B to zero + self.lora_A[adapter_name].weight.data = lora_A + self.lora_B[adapter_name].weight.data = lora_B + if adapter_name in self.lora_embedding_A.keys(): + # initialize a the same way as the default for nn.linear and b to zero + self.lora_embedding_A[adapter_name].weight.data = lora_A + self.lora_embedding_B[adapter_name].weight.data = lora_B + self.get_base_layer().weight.data = qweight + + @torch.no_grad() + def orthogonal_init(self, adapter_name): + # https://datta0.github.io/posts/rethink-lora-init/#orthogonal-initialisation + rank = self.r[adapter_name] + if rank % 2 != 0: + raise ValueError(f"Orthogonal initialization requires the LoRA rank to be even, got {rank} instead.") + + X = torch.randn(rank, rank) + Q, _ = torch.linalg.qr(X) + q_odd = Q[0::2, :] # Odd rows + q_even = Q[1::2, :] # Even rows + dtype = self.get_base_layer().weight.dtype + lora_A = torch.randn(self.in_features, rank // 2).mm(q_odd).T / 10.0 + lora_B = torch.randn(rank // 2, self.out_features).T.mm(q_even) / 10.0 + self.lora_A[adapter_name].weight = nn.Parameter(lora_A.contiguous().to(dtype)) + self.lora_B[adapter_name].weight = nn.Parameter(lora_B.contiguous().to(dtype)) + + def lora_ga_init(self, adapter_name, lora_ga_config): + """ + Initialize LoRA weights using gradient approximation. + + Uses SVD on the gradient matrix to initialize adapters in a way that aligns with the direction of full + fine-tuning. + + Expects that `preprocess_loraga` has been called before this, which attaches the `loraga_grad` attribute to the + base layer. + + If gradients are not available (e.g., when loading from a saved adapter), falls back to gaussian + initialization. The weights will be overwritten by the state_dict anyway. + """ + base_layer = self.get_base_layer() + + # Check for gradient attached by preprocess_loraga + if not hasattr(base_layer, "_peft_loraga_grad"): + # When loading from saved adapter, gradients won't be available + # Fall back to gaussian initialization (weights will be overwritten by state_dict) + self.reset_lora_parameters(adapter_name, init_lora_weights=True) + return + + grad = base_layer._peft_loraga_grad + + # Check for lora_ga_config + if lora_ga_config is None: + raise ValueError( + "lora_ga_config must be provided when init_lora_weights='lora_ga'. " + "Please pass lora_ga_config=LoraGAConfig(...) to LoraConfig." + ) + direction = lora_ga_config.direction + scale = lora_ga_config.scale + stable_gamma = lora_ga_config.stable_gamma + dtype = self.get_base_layer().weight.dtype + + grad = grad.to(torch.float32) + weight = self.get_base_layer().weight + + grad = transpose(grad, self.fan_in_fan_out) + + r = self.r[adapter_name] + + # torch.svd_lowrank returns (U, S, V) where grad ≈ U @ diag(S) @ V.T + # So V is shape (in_features, k) and we need V.T which is (k, in_features) for lora_A + U, S, V = torch.svd_lowrank(grad, q=min(4 * r, min(grad.shape)), niter=4) + + # V is (in_features, k), we need Vh = V.T which is (k, in_features) + Vh = V.t() + + U = U[:, : 2 * r] + S = S[: 2 * r] + Vh = Vh[: 2 * r, :] + + if direction == "ArBr": + # Alternating: A takes rows at odd indices [1,3,5,7], B takes columns at even indices [0,2,4,6] + lora_A_weight = Vh[1 : 2 * r : 2, :] # Shape: (r, in_features) + lora_B_weight = U[:, 0 : 2 * r : 2] # Shape: (out_features, r) + S_B = S[0 : 2 * r : 2] + lora_B_weight = lora_B_weight @ torch.diag(S_B) + + elif direction == "A2rBr": + # A takes second half rows [r:2r], B takes first half columns [:r] + lora_A_weight = Vh[r : 2 * r, :] # Shape: (r, in_features) + lora_B_weight = U[:, :r] # Shape: (out_features, r) + S_B = S[:r] + lora_B_weight = lora_B_weight @ torch.diag(S_B) + + elif direction == "ArB2r": + # A takes first half rows [:r], B takes second half columns [r:2r] + lora_A_weight = Vh[:r, :] # Shape: (r, in_features) + lora_B_weight = U[:, r : 2 * r] # Shape: (out_features, r) + S_B = S[r : 2 * r] + lora_B_weight = lora_B_weight @ torch.diag(S_B) + + elif direction == "random": + indices = torch.randperm(2 * r)[:r] + lora_A_weight = Vh[indices, :] # Shape: (r, in_features) + S_B = S[indices] + lora_B_weight = U[:, indices] @ torch.diag(S_B) # Shape: (out_features, r) + + scaling_factor = self.scaling[adapter_name] + out_features = weight.shape[0] + + if scale == "stable": + scale_factor = (out_features**0.25) / (stable_gamma**0.5) + lora_B_weight = lora_B_weight * scale_factor + + elif scale == "weight_svd": + weight_data = transpose(weight.data.to(torch.float32), self.fan_in_fan_out) + _, weight_S, _ = torch.svd_lowrank(weight_data, q=r, niter=4) + if S_B[0] > 0: + scale_factor = weight_S[0] / S_B[0] + lora_B_weight = lora_B_weight * scale_factor + + elif scale == "gd_scale": + lora_A_weight = lora_A_weight / scaling_factor + lora_B_weight = lora_B_weight / scaling_factor + + # Convert to target dtype first to ensure weight offset matches adapter precision + lora_A_weight = lora_A_weight.to(dtype) + lora_B_weight = lora_B_weight.to(dtype) + + # Assign LoRA weights + # lora_A should be (r, in_features), lora_B should be (out_features, r) + self.lora_A[adapter_name].weight.data = lora_A_weight.contiguous() + self.lora_B[adapter_name].weight.data = lora_B_weight.contiguous() + + # Modify base weights: W_new = W_old - scaling * (B @ A) + # Important: compute offset in fp32 using dtype-converted weights to match forward pass precision + weight_data = transpose(weight.data.to(torch.float32), self.fan_in_fan_out) + weight_offset = scaling_factor * (lora_B_weight.float() @ lora_A_weight.float()) + weight_data = weight_data - weight_offset + weight_data = transpose(weight_data.to(dtype), self.fan_in_fan_out) + self.get_base_layer().weight.data = weight_data + + # Remove redundant fields + del base_layer._peft_loraga_grad + + def _cache_store(self, key: str, value: Any) -> None: + # cache intermediate values, e.g. weight norm of DoRA + self._caches[key] = value + + def _cache_pop(self, key: str) -> Any: + # retrieve and remove from ad hoc cache + value = self._caches.pop(key) + return value + + def set_scale(self, adapter: str, scale: float) -> None: + """Set the scale of the given adapter to the initial scale multiplied by the provided factor + + The initial scale is determined by the configured `r` (rank) and `lora_alpha`. + """ + if adapter not in self.scaling: + # Ignore the case where the adapter is not in the layer + return + if self.use_rslora.get(adapter, False): + self.scaling[adapter] = scale * self.lora_alpha[adapter] / math.sqrt(self.r[adapter]) + else: + self.scaling[adapter] = scale * self.lora_alpha[adapter] / self.r[adapter] + + def scale_layer(self, scale: float) -> None: + """Multiply the current scale of all active adapters by the provided factor""" + if scale == 1: + return + + for active_adapter in self.active_adapters: + if active_adapter not in self.lora_A.keys(): + continue + + self.scaling[active_adapter] *= scale + + def unscale_layer(self, scale: Optional[float | int] = None) -> None: + """Divide the current scale of all active adapters by the provided factor. If `scale=None` is passed, reset to + initial scale + + The initial scale is determined by the configured `r` (rank) and `lora_alpha`. + + """ + for active_adapter in self.active_adapters: + if active_adapter not in self.lora_A.keys(): + continue + + if scale is None: + if self.use_rslora.get(active_adapter, False): + self.scaling[active_adapter] = self.lora_alpha[active_adapter] / math.sqrt(self.r[active_adapter]) + else: + self.scaling[active_adapter] = self.lora_alpha[active_adapter] / self.r[active_adapter] + else: + self.scaling[active_adapter] = self.scaling[active_adapter] / scale + + def _check_forward_args(self, x, *args, **kwargs): + """Check if the arguments are compatible with the configs and state of the model""" + adapter_names = kwargs.get("adapter_names", None) + if adapter_names is None: + return + + if len(x) != len(adapter_names): + msg = ( + "Length of `adapter_names` should be the same as the number of inputs, but got " + f"{len(adapter_names)} and {len(x)} respectively." + ) + raise ValueError(msg) + + if self.merged: + # It is unclear what would be the right thing to do if users pass adapter_names and there are merged + # adapters. Therefore, it is better to raise an error in this case. + msg = "Cannot pass `adapter_names` when there are merged adapters, please call `unmerge_adapter` first." + raise ValueError(msg) + + # DoRA is not supported (yet), check that it's not being used. Don't check "__base__", as this is the + # placeholder for the base model. + unique_adapters = {name for name in adapter_names if name != "__base__"} + for adapter_name in unique_adapters: + if self.use_dora.get(adapter_name, False): + msg = "Cannot pass `adapter_names` when DoRA is enabled." + raise ValueError(msg) + + 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) + torch_result_dtype = result.dtype + + 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]) + alora_offsets = variant_kwargs.get("alora_offsets", None) + 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] + + # 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]].to(lora_A.weight.dtype) + if active_adapter not in self.lora_variant: # vanilla LoRA + lora_output = lora_B(lora_A(dropout(sub_batch))) * scaling + result[sub_batch_indices_list[i]] += lora_output.to(torch_result_dtype) + else: + if alora_offsets is not None: + variant_kwargs["alora_offsets"] = [alora_offsets[j] for j in sub_batch_indices_list[i]] + lora_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, + ) + result[sub_batch_indices_list[i]] = lora_output.to(torch_result_dtype) + + return result + + +# Below code is based on https://github.com/microsoft/LoRA/blob/main/loralib/layers.py +# and modified to work with PyTorch FSDP + + +# ------------------------------------------------------------------------------------------ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. +# ------------------------------------------------------------------------------------------ + + +class Linear(nn.Module, LoraLayer): + # Lora implemented in a dense layer + def __init__( + self, + base_layer, + adapter_name: str, + config: LoraConfig, + r: int = 0, + lora_alpha: int = 1, + is_target_conv_1d_layer: bool = False, + **kwargs, + ) -> None: + super().__init__() + LoraLayer.__init__(self, base_layer, **kwargs) + self.fan_in_fan_out = config.fan_in_fan_out + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + r, + lora_alpha=lora_alpha, + config=config, + **kwargs, + ) + self.is_target_conv_1d_layer = is_target_conv_1d_layer + + def resolve_lora_variant(self, config: LoraConfig, **kwargs) -> Optional[LoraVariant]: + if config.velora_config is not None: + from .variants import VeloraLinearVariant + + return VeloraLinearVariant() + + if config.arrow_config is not None: + from .variants import ArrowLinearVariant + + return ArrowLinearVariant() + + if config.monteclora_config is not None: + from .variants import MontecloraLinearVariant + + return MontecloraLinearVariant() + if config.use_bdlora is not None: + from .variants import BdLoraLinearVariant + + return BdLoraLinearVariant() + + 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 in self.lora_A.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() + orig_dtype = orig_weight.dtype + if active_adapter not in self.lora_variant: # vanilla LoRA + delta_weight = self.get_delta_weight(active_adapter) + orig_weight += delta_weight.to(orig_dtype) + else: + orig_weight = self.lora_variant[active_adapter].merge_safe(self, active_adapter, orig_weight) + + if not torch.isfinite(orig_weight).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = orig_weight + + if self.lora_bias[active_adapter]: + if getattr(base_layer, "bias", None) is None: + raise RuntimeError( + "Impossible to merge LoRA with `lora_bias=True` because the base layer has no bias." + ) + new_bias = base_layer.bias + self.lora_B[active_adapter].bias * self.scaling[active_adapter] + if not torch.isfinite(new_bias).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + base_layer.bias.data = new_bias.to(orig_dtype) + + else: + if active_adapter not in self.lora_variant: # vanilla LoRA + delta_weight = self.get_delta_weight(active_adapter) + base_layer.weight.data += delta_weight + else: + self.lora_variant[active_adapter].merge_unsafe(self, active_adapter, base_layer.weight) + + if self.lora_bias[active_adapter]: + if getattr(base_layer, "bias", None) is None: + raise RuntimeError( + "Impossible to merge LoRA with `lora_bias=True` because the base layer has no bias." + ) + base_layer.bias.data += self.lora_B[active_adapter].bias * self.scaling[active_adapter] + + 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 in self.lora_A.keys(): + weight = self.get_base_layer().weight + if active_adapter not in self.lora_variant: # vanilla LoRA + orig_dtype = weight.dtype + delta_weight = self.get_delta_weight(active_adapter) + weight.data -= delta_weight.to(orig_dtype) + else: + unmerged = self.lora_variant[active_adapter].unmerge(self, active_adapter, weight) + weight.data = unmerged + + if self.lora_bias[active_adapter]: + self.get_base_layer().bias.data -= self.lora_B[active_adapter].bias * self.scaling[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. + """ + device = self.lora_B[adapter].weight.device + dtype = self.lora_B[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) + + weight_A = self.lora_A[adapter].weight + weight_B = self.lora_B[adapter].weight + + if cast_to_fp32: + weight_A = weight_A.float() + weight_B = weight_B.float() + + output_tensor = transpose(weight_B @ weight_A, self.fan_in_fan_out) * self.scaling[adapter] + + if cast_to_fp32: + output_tensor = output_tensor.to(dtype=dtype) + + # cast back the weights + self.lora_A[adapter].weight.data = weight_A.to(dtype) + self.lora_B[adapter].weight.data = weight_B.to(dtype) + + return output_tensor + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> 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) + torch_result_dtype = result.dtype + + lora_A_keys = self.lora_A.keys() + for active_adapter in self.active_adapters: + if active_adapter not in 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] + 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, + **variant_kwargs, + **kwargs, + ) + + result = result.to(torch_result_dtype) + + return result + + def supports_lora_conversion(self, adapter_name: str = "default") -> bool: + return True + + def __repr__(self) -> str: + rep = super().__repr__() + return "lora." + rep + + +class _LoraEmbeddingAHolder(nn.Module): + """ + A "fake" module to hold the lora_embedding_A weights for the TP hooks. + """ + + def __init__(self, lora_embedding_A_weight): + super().__init__() + self.weight = lora_embedding_A_weight.T # lora_embedding_A shape is (r, vocab_size) + + +class Embedding(nn.Module, LoraLayer): + # LoRA implemented in a Embedding layer + def __init__( + self, + base_layer: nn.Module, + adapter_name: str, + config: LoraConfig, + r: int = 0, + lora_alpha: int = 1, + init_lora_weights: Union[bool, str] = True, + **kwargs, + ) -> None: + if config.lora_bias: + # lora_bias=True is not supported (yet) for embedding layers, as they use nn.Parameter + raise ValueError(f"lora_bias={config.lora_bias} is not supported for {self.__class__.__name__}.") + + super().__init__() + LoraLayer.__init__(self, base_layer) + self.fan_in_fan_out = config.fan_in_fan_out + + tp_plan = getattr(base_layer, "_hf_tp_plan", None) + + self.device_mesh = getattr(base_layer, "_hf_device_mesh", None) + self.tp_layer = None + + self.input_fns = {} + self.output_fns = {} + + if tp_plan is not None: + if not is_transformers_ge_v5_4_0: + raise RuntimeError("Tensor Parallel with LoRA is only supported for transformers v5.4.0 and above. ") + + if tp_plan != "embedding_rowwise": + raise ValueError( + f'Unsupported tensor parallel plan {tp_plan} for embedding layers. Only "embedding_rowwise" is ' + "supported." + ) + + from transformers.integrations.tensor_parallel import ALL_PARALLEL_STYLES + + self.tp_layer = copy.deepcopy(ALL_PARALLEL_STYLES[tp_plan]) + + 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.velora_config is not None: + raise ValueError("VeLoRA does not support adapting embedding layers.") + if not config.use_dora: + return None + + from .variants import DoraEmbeddingVariant + + return DoraEmbeddingVariant() + + def update_layer( + self, + adapter_name: str, + r: int, + lora_alpha: int, + config: LoraConfig, + **kwargs, + ) -> None: + lora_dropout = config.lora_dropout + init_lora_weights = config.init_lora_weights + use_rslora = config.use_rslora + lora_bias = config.lora_bias + inference_mode = config.inference_mode + + if r <= 0: + raise ValueError(f"`r` should be a positive integer value but the value passed is {r}") + + lora_variant = self.resolve_lora_variant(config=config) + if lora_variant is not None: + self.lora_variant[adapter_name] = lora_variant + + self.r[adapter_name] = r + self.lora_alpha[adapter_name] = lora_alpha + if lora_dropout > 0.0: + lora_dropout_layer = nn.Dropout(p=lora_dropout) + else: + lora_dropout_layer = nn.Identity() + + self.lora_dropout[adapter_name] = lora_dropout_layer + # Actual trainable parameters + weight_A = torch.randn((r, self.in_features)) + weight_B = torch.randn((self.out_features, r)) + self.lora_embedding_A[adapter_name] = nn.Parameter(weight_A) + self.lora_embedding_B[adapter_name] = nn.Parameter(weight_B) + self.lora_bias[adapter_name] = lora_bias + + if use_rslora: + self.scaling[adapter_name] = lora_alpha / math.sqrt(r) + else: + self.scaling[adapter_name] = lora_alpha / r + + self.use_rslora[adapter_name] = use_rslora + + self.use_dora[adapter_name] = config.use_dora + + if init_lora_weights == "loftq": + self.loftq_init(adapter_name) + elif init_lora_weights == "lora_ga": + # Embedding layers don't support LoRA-GA, fall back to standard initialization + self.reset_lora_parameters(adapter_name, True) + elif init_lora_weights: + self.reset_lora_parameters(adapter_name, init_lora_weights) + + # call this before init of the lora variants + self._move_adapter_to_device_of_base_layer(adapter_name) + + if adapter_name in self.lora_variant: + self.lora_variant[adapter_name].init(self, adapter_name=adapter_name, config=config, **kwargs) + + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + # If there is tensor parallelism, we register the hooks for `self._embed`. + if self.tp_layer is not None: + mod = _LoraEmbeddingAHolder(self.lora_embedding_A[adapter_name]) + + def input_fn(inputs): + return self.tp_layer._prepare_input_fn(mod, inputs, self.device_mesh) + + def output_fn(outputs): + return self.tp_layer._prepare_output_fn(mod, outputs, self.device_mesh) + + self.input_fns[adapter_name] = input_fn + self.output_fns[adapter_name] = output_fn + + 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.lora_embedding_A.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_weight = base_layer.weight.data.clone() + if active_adapter not in self.lora_variant: # vanilla LoRA + orig_weight += self.get_delta_weight(active_adapter).to(orig_dtype) + else: + orig_weight = self.lora_variant[active_adapter].merge_safe(self, active_adapter, orig_weight) + + if not torch.isfinite(orig_weight).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = orig_weight + else: + if active_adapter not in self.lora_variant: # vanilla LoRA + base_layer.weight.data += self.get_delta_weight(active_adapter).to(orig_dtype) + else: + self.lora_variant[active_adapter].merge_unsafe(self, active_adapter, base_layer.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 + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + orig_dtype = self.get_base_layer().weight.dtype + if active_adapter in self.lora_embedding_A.keys(): + weight = self.get_base_layer().weight + if active_adapter not in self.lora_variant: # vanilla LoRA + weight.data -= self.get_delta_weight(active_adapter).to(orig_dtype) + else: + unmerged = self.lora_variant[active_adapter].unmerge(self, active_adapter, weight) + weight.data = unmerged + + 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.lora_embedding_B[adapter].device + dtype = self.lora_embedding_A[adapter].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) + + weight_A = self.lora_embedding_A[adapter] + weight_B = self.lora_embedding_B[adapter] + + if cast_to_fp32: + weight_A = weight_A.float() + weight_B = weight_B.float() + + output_tensor = transpose(weight_B @ weight_A, True) * self.scaling[adapter] + + if cast_to_fp32: + output_tensor = output_tensor.to(dtype=dtype) + + # cast back the weights + self.lora_embedding_A[adapter] = weight_A.to(dtype) + self.lora_embedding_B[adapter] = weight_B.to(dtype) + + return output_tensor + + 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) + + # Some embedding layers (e.g., Gemma3TextScaledWordEmbedding) apply scaling in their forward method. + # Since base_layer(x) already includes this scaling, we need to apply it to LoRA contributions too. + embed_scale = self._get_embed_scale() + + 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_embedding_A.keys(): + continue + + embedding_A = self.lora_embedding_A[active_adapter].T + embedding_B = self.lora_embedding_B[active_adapter].T + scaling = self.scaling[active_adapter] + + # 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]] + after_A = self._embed(sub_batch, embedding_A) + adapter_output = (after_A @ embedding_B) * scaling + + # Apply embed_scale to match the base layer's scaling + if embed_scale is not None: + adapter_output = adapter_output * embed_scale.to(adapter_output.dtype) + + result[sub_batch_indices_list[i]] += adapter_output + + return result + + def _embed( + self, + input: torch.Tensor, + weight: torch.Tensor, + input_fn: Callable[[tuple[torch.Tensor]], torch.Tensor] | None = None, + output_fn: Callable[[torch.Tensor], torch.Tensor] | None = None, + ) -> torch.Tensor: + base_layer = self.get_base_layer() + if input_fn is not None: + input = input_fn((input,)) + output = 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, + ) + if output_fn is not None: + output = output_fn(output) + return output + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + # TODO: no dtype conversion here, unlike in Linear, is that correct? + 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, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + torch_result_dtype = result.dtype + + # Some embedding layers (e.g., Gemma3TextScaledWordEmbedding) apply scaling in their forward method. + # Since base_layer(x) already includes this scaling, we need to apply it to LoRA contributions too. + embed_scale = self._get_embed_scale() + + for active_adapter in self.active_adapters: + if active_adapter not in self.lora_embedding_A: + continue + + if active_adapter not in self.lora_variant: # vanilla LoRA + embedding_A = self.lora_embedding_A[active_adapter].T + embedding_B = self.lora_embedding_B[active_adapter].T + scaling = self.scaling[active_adapter] + # input and ouput function hooks for TP support. + input_fn = self.input_fns.get(active_adapter, None) + output_fn = self.output_fns.get(active_adapter, None) + after_A = self._embed(x, embedding_A, input_fn=input_fn, output_fn=output_fn) + adapter_output = (after_A @ embedding_B) * scaling + + # Apply embed_scale to match the base layer's scaling + if embed_scale is not None: + adapter_output = adapter_output * embed_scale.to(adapter_output.dtype) + + result = result + adapter_output + else: + result = self.lora_variant[active_adapter].forward( + self, + active_adapter=active_adapter, + x=x, + result=result, + **variant_kwargs, + **kwargs, + ) + result = result.to(torch_result_dtype) + + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "lora." + rep + + +class _ConvNd(nn.Module, LoraLayer): + # Lora implemented in a conv(2,3)d layer + def __init__( + self, + base_layer: nn.Module, + adapter_name: str, + config: LoraConfig, + r: int = 0, + lora_alpha: int = 1, + **kwargs, + ) -> None: + super().__init__() + LoraLayer.__init__(self, base_layer) + if kwargs.get("use_alora", False): + raise ValueError("aLoRA does not support adapting conv layers.") + if config.velora_config is not None: + raise ValueError("VeLoRA does not support adapting conv layers.") + if base_layer.groups > 1: + warnings.warn("LoRA adapter added to ConvNd layer with groups > 1. Merging is not supported.") + + if r % base_layer.groups != 0: + raise ValueError( + f"Targeting a {base_layer.__class__.__name__} with groups={base_layer.groups} and rank {r}. " + "Currently, support is limited to conv layers where the rank is divisible by groups. " + "Either choose a different rank or do not target this specific layer." + ) + + self._active_adapter = adapter_name + self._kernel_dim = base_layer.weight.dim() + + self.update_layer( + adapter_name, + r, + lora_alpha=lora_alpha, + config=config, + ) + + def update_layer( + self, + adapter_name: str, + r: int, + lora_alpha: int, + config: LoraConfig, + **kwargs, + ) -> None: + lora_dropout = config.lora_dropout + init_lora_weights = config.init_lora_weights + use_rslora = config.use_rslora + lora_bias = config.lora_bias + inference_mode = config.inference_mode + + if r <= 0: + raise ValueError(f"`r` should be a positive integer value but the value passed is {r}") + + if lora_bias and (getattr(self.get_base_layer(), "bias", None) is None): + warnings.warn( + f"`lora_bias=True` was passed but the targeted layer of type {type(self.get_base_layer()).__name__} " + "has no bias. This means that merging LoRA weights won't be possible.", + PeftWarning, + ) + + lora_variant = self.resolve_lora_variant(config=config) + if lora_variant is not None: + self.lora_variant[adapter_name] = lora_variant + + self.r[adapter_name] = r + self.lora_alpha[adapter_name] = lora_alpha + if lora_dropout > 0.0: + lora_dropout_layer = nn.Dropout(p=lora_dropout) + else: + lora_dropout_layer = nn.Identity() + + self.lora_dropout[adapter_name] = lora_dropout_layer + # Actual trainable parameters + base_layer = self.get_base_layer() + kernel_size = base_layer.kernel_size + stride = base_layer.stride + padding = base_layer.padding + conv_layer = type(base_layer) + out_kernel = out_stride = (1,) * (self._kernel_dim - 2) + self.lora_A[adapter_name] = conv_layer(self.in_features, r, kernel_size, stride, padding, bias=False) + self.lora_B[adapter_name] = conv_layer( + r, self.out_features, out_kernel, out_stride, groups=base_layer.groups, bias=lora_bias + ) + self.lora_bias[adapter_name] = lora_bias + + if use_rslora: + self.scaling[adapter_name] = lora_alpha / math.sqrt(r) + else: + self.scaling[adapter_name] = lora_alpha / r + + self.use_rslora[adapter_name] = use_rslora + + self.use_dora[adapter_name] = config.use_dora + + if init_lora_weights == "loftq": + self.loftq_init(adapter_name) + elif init_lora_weights == "lora_ga": + # Conv layers don't support LoRA-GA, fall back to standard initialization + self.reset_lora_parameters(adapter_name, True) + elif init_lora_weights: + self.reset_lora_parameters(adapter_name, init_lora_weights) + + # call this before init of the lora variants + self._move_adapter_to_device_of_base_layer(adapter_name) + + if adapter_name in self.lora_variant: + self.lora_variant[adapter_name].init(self, adapter_name=adapter_name, config=config, **kwargs) + + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def _get_dora_factor_view(self): + return (-1,) + (1,) * (self._kernel_dim - 1) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights inside 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.lora_A.keys(): + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.dtype + + if base_layer.groups > 1: + # https://github.com/huggingface/peft/pull/2403 + raise NotImplementedError("Merging is not supported for _ConvNd layers with groups > 1!") + + 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() + if active_adapter not in self.lora_variant: # vanilla LoRA + delta_weight = self.get_delta_weight(active_adapter) + orig_weight += delta_weight.to(orig_dtype) + else: + orig_weight = self.lora_variant[active_adapter].merge_safe(self, active_adapter, orig_weight) + + if not torch.isfinite(orig_weight).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = orig_weight + + if self.lora_bias[active_adapter]: + if getattr(base_layer, "bias", None) is None: + raise RuntimeError( + "Impossible to merge LoRA with `lora_bias=True` because the base layer has no bias." + ) + new_bias = base_layer.bias + self.lora_B[active_adapter].bias * self.scaling[active_adapter] + if not torch.isfinite(new_bias).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + base_layer.bias.data = new_bias.to(orig_dtype) + + else: + if active_adapter not in self.lora_variant: # vanilla LoRA + delta_weight = self.get_delta_weight(active_adapter) + base_layer.weight.data += delta_weight.to(orig_dtype) + else: + self.lora_variant[active_adapter].merge_unsafe(self, active_adapter, base_layer.weight) + + if self.lora_bias[active_adapter]: + if getattr(base_layer, "bias", None) is None: + raise RuntimeError( + "Impossible to merge LoRA with `lora_bias=True` because the base layer has no bias." + ) + base_layer.bias.data += self.lora_B[active_adapter].bias * self.scaling[active_adapter] + + 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 in self.lora_A.keys(): + weight = self.get_base_layer().weight + if active_adapter not in self.lora_variant: # vanilla LoRA + orig_dtype = weight.dtype + delta_weight = self.get_delta_weight(active_adapter) + weight.data -= delta_weight.to(orig_dtype) + else: + unmerged = self.lora_variant[active_adapter].unmerge(self, active_adapter, weight) + weight.data = unmerged + + if self.lora_bias[active_adapter]: + self.get_base_layer().bias.data -= self.lora_B[active_adapter].bias * self.scaling[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. + """ + device = self.lora_B[adapter].weight.device + dtype = self.lora_A[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) + + weight_A = self.lora_A[adapter].weight + weight_B = self.lora_B[adapter].weight + + if cast_to_fp32: + weight_A = weight_A.float() + weight_B = weight_B.float() + + # https://github.com/bmaltais/kohya_ss/blob/feb6728762a8f463d15ba936d189d4c3abfaa1ab/networks/lora.py#L117 + if self.get_base_layer().weight.size()[2:4] == (1, 1): + # conv2d 1x1 + output_tensor = (weight_B.squeeze(3).squeeze(2) @ weight_A.squeeze(3).squeeze(2)).unsqueeze(2).unsqueeze( + 3 + ) * self.scaling[adapter] + else: + output_tensor = self.conv_fn(weight_A.transpose(0, 1), weight_B) + + if self.get_base_layer().groups > 1: + output_tensor = output_tensor * self.scaling[adapter] + else: + output_tensor = output_tensor.transpose(0, 1) * self.scaling[adapter] + + if cast_to_fp32: + output_tensor = output_tensor.to(dtype=dtype) + + # cast back the weights + self.lora_A[adapter].weight.data = weight_A.to(dtype) + self.lora_B[adapter].weight.data = weight_B.to(dtype) + + return output_tensor + + 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, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + + else: + result = self.base_layer(x, *args, **kwargs) + torch_result_dtype = result.dtype + + 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] + 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, + **variant_kwargs, + **kwargs, + ) + + result = result.to(torch_result_dtype) + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "lora." + rep + + +class Conv2d(_ConvNd): + # Lora implemented in a conv2d layer + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + if not self._kernel_dim == 4: + raise ValueError(f"Conv2d layer kernel must have 4 dimensions, not {self._kernel_dim}") + self.conv_fn = F.conv2d + + def resolve_lora_variant(self, *, config: LoraConfig, **kwargs) -> Optional[LoraVariant]: + if config.velora_config is not None: + raise ValueError("VeLoRA does not support adapting conv layers.") + if not config.use_dora: + return None + + from .variants import DoraConv2dVariant + + return DoraConv2dVariant() + + +class Conv1d(_ConvNd): + # Lora implemented in a conv1d layer + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + if not self._kernel_dim == 3: + raise ValueError(f"Conv1d layer kernel must have 3 dimensions, not {self._kernel_dim}") + self.conv_fn = F.conv1d + + def resolve_lora_variant(self, *, config: LoraConfig, **kwargs) -> Optional[LoraVariant]: + if config.velora_config is not None: + raise ValueError("VeLoRA does not support adapting conv layers.") + if not config.use_dora: + return None + + from .variants import DoraConv1dVariant + + return DoraConv1dVariant() + + +class Conv3d(_ConvNd): + # Lora implemented in a conv3d layer + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + if not self._kernel_dim == 5: + raise ValueError(f"Conv3d layer kernel must have 5 dimensions, not {self._kernel_dim}") + self.conv_fn = F.conv3d + + def resolve_lora_variant(self, *, config: LoraConfig, **kwargs) -> Optional[LoraVariant]: + if config.velora_config is not None: + raise ValueError("VeLoRA does not support adapting conv layers.") + if not config.use_dora: + return None + + from .variants import DoraConv3dVariant + + return DoraConv3dVariant() + + +class MultiheadAttention(nn.Module, LoraLayer): + """LoRA implemented in a multihead attention layer + + This is currently only implemented for the case of `_qkv_same_embed_dim = True`, i.e. query, key, and value having + the same dimension. + + Note: LoRA is applied to both the in_proj (query/key/value) and out_proj. There is currently no way to specify only + one of them. Don't try to apply LoRA to the out_proj of MultiheadAttention by targeting that layer specifically, + since the forward method of that layer is not being used, hence the LoRA adapter would be ignored. + + This is a little bit hacky because of the way that MultiheadAttention is implemented in PyTorch: There are no + `nn.Linear` layers which we can hook onto or, in case of output projection, `.forward` is not used. This + implementation works around these problems by merging the weights before the forward call and unmerging them after + the forward call. + """ + + def __init__( + self, + base_layer, + adapter_name: str, + config: LoraConfig, + r: int = 0, + lora_alpha: int = 1, + **kwargs, + ) -> None: + # TODO work with separate weights + if not getattr(base_layer, "_qkv_same_embed_dim", True): + # default for this value appears to be True: + # https://github.com/pytorch/pytorch/blob/701ba5203fe68d55d655bd4d6c008be94cf34ea5/torch/nn/modules/activation.py#L1128-L1130 + raise ValueError( + f"Only same embed for query/key/value is supported as of now for {self.__class__.__name__}." + ) + if config.use_dora: + # TODO: probably not so hard to implement + raise ValueError(f"{self.__class__.__name__} does not support DoRA (yet), please set use_dora to False") + if config.velora_config is not None: + raise ValueError(f"{self.__class__.__name__} does not support VeLoRA, please set `velora_config=None`.") + if kwargs.get("use_alora", False): + raise ValueError(f"{self.__class__.__name__} does not support aLoRA (yet), please set use_alora to False") + super().__init__() + LoraLayer.__init__(self, base_layer, **kwargs) + + # Note: LoRA is applied to both in_proj and out_proj. There is currently no way to only specify one of them. + if isinstance(base_layer.out_proj, nn.Linear): + self.base_layer.out_proj = Linear( + base_layer.out_proj, + adapter_name, + r=r, + lora_alpha=lora_alpha, + config=config, + **kwargs, + ) + else: + raise TypeError(f"out_proj must be an instance of nn.Linear for {self.__class__.__name__}.") + + self._active_adapter = adapter_name + self.update_layer(adapter_name, r, lora_alpha=lora_alpha, config=config) + + @property + def embed_dim(self) -> int: + return self.get_base_layer().embed_dim + + @property + def kdim(self) -> Optional[int]: + return self.get_base_layer().kdim + + @property + def vdim(self) -> Optional[int]: + return self.get_base_layer().vdim + + @property + def _qkv_same_embed_dim(self) -> bool: + return self.get_base_layer()._qkv_same_embed_dim + + @property + def num_heads(self) -> int: + return self.get_base_layer().num_heads + + @property + def dropout(self) -> float: + return self.get_base_layer().dropout + + @property + def batch_first(self) -> bool: + return self.get_base_layer().batch_first + + @property + def head_dim(self) -> int: + return self.get_base_layer().head_dim + + @property + def in_proj_weight(self) -> nn.Parameter: + return self.get_base_layer().in_proj_weight + + @property + def in_proj_bias(self) -> nn.Parameter: + return self.get_base_layer().in_proj_bias + + @property + def out_proj(self) -> nn.Module: + return self.get_base_layer().out_proj.get_base_layer() + + @property + def bias_k(self) -> Optional[nn.Parameter]: + return self.get_base_layer().bias_k + + @property + def bias_v(self) -> Optional[nn.Parameter]: + return self.get_base_layer().bias_v + + def merge_masks(self, *args, **kwargs) -> tuple[Optional[torch.Tensor], Optional[int]]: + return self.get_base_layer().merge_masks(*args, **kwargs) + + @property + def add_zero_attn(self) -> bool: + return self.get_base_layer().add_zero_attn + + def update_layer(self, *args, **kwargs) -> None: + super().update_layer(*args, **kwargs) + # Note: LoRA is applied to both in_proj and out_proj. There is currently no way to only specify one of them. + self.base_layer.out_proj.update_layer(*args, **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`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + # Implementation follows this: + # https://github.com/Baijiong-Lin/LoRA-Torch/blob/4bfed6820b64fcf47064c30f30606a190a4f0d2e/loratorch/layers.py#L73-L79 + # Notably, instead of mutating the weight, we delete the original weight and replace it by the merged weight + # TODO: work with separate weights + for active_adapter in adapter_names: + if active_adapter in self.lora_A.keys(): + base_layer = self.get_base_layer() + orig_dtype = base_layer.out_proj.weight.dtype + if safe_merge: + # TODO: work with separate weights + # merging in_proj (nn.Parameter) + orig_weight_in = base_layer.in_proj_weight.data.detach().clone() + orig_weight_in += self.get_delta_weight(active_adapter).to(orig_dtype) + if not torch.isfinite(orig_weight_in).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + # merging out_proj (subclass of nn.Linear) + orig_weight_out = base_layer.out_proj.weight.data.detach().clone() + orig_weight_out += base_layer.out_proj.get_delta_weight(active_adapter).to(orig_dtype) + if not torch.isfinite(orig_weight_out).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + # unregister parameter implicitly and overwrite using merged weights; gradients are computed after + # forward and, thus, after unmerging (see forward()), therefore this is safe to do. + del base_layer.in_proj_weight + base_layer.in_proj_weight = orig_weight_in + + del base_layer.out_proj.get_base_layer().weight + base_layer.out_proj.get_base_layer().weight = orig_weight_out + base_layer.out_proj.merge(adapter_names=[active_adapter]) + else: + # merging in_proj (nn.Parameter) + # TODO: work with separate weights + delta_weight = self.get_delta_weight(active_adapter).to(orig_dtype) + weight_merged = base_layer.in_proj_weight.data.detach() + delta_weight + + # unregister parameter implicitly and overwrite using merged weights; gradients are computed after + # forward and, thus, after unmerging (see forward()), therefore this is safe to do. + del base_layer.in_proj_weight + base_layer.in_proj_weight = weight_merged + + # merging out_proj (subclass of nn.Linear) + delta_weight = base_layer.out_proj.get_delta_weight(active_adapter).to(orig_dtype) + weight_merged = base_layer.out_proj.weight.data.detach() + delta_weight + del base_layer.out_proj.get_base_layer().weight + base_layer.out_proj.get_base_layer().weight = weight_merged + base_layer.out_proj.merge(adapter_names=[active_adapter]) + 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 + + # TODO work with separate weights + base_layer = self.get_base_layer() + orig_dtype = base_layer.out_proj.base_layer.weight.dtype + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter in self.lora_A.keys(): + # Ensure that requires_grad=False for the base weights after unmerging. This may not matter since + # requires_grad was False when the optimizer was initialized, but still let's try to be correct here. + + # in_proj + delta_weight = self.get_delta_weight(active_adapter).to(orig_dtype) + old_weight = base_layer.in_proj_weight.data - delta_weight + del base_layer.in_proj_weight + base_layer.register_parameter("in_proj_weight", nn.Parameter(old_weight, requires_grad=False)) + + # out_proj + delta_weight = base_layer.out_proj.get_delta_weight(active_adapter).to(orig_dtype) + old_weight = base_layer.out_proj.base_layer.weight.data - delta_weight + del base_layer.out_proj.base_layer.weight + base_layer.out_proj.base_layer.register_parameter( + "weight", nn.Parameter(old_weight, requires_grad=False) + ) + + self.get_base_layer().out_proj.unmerge() + + def unload_and_optionally_merge_module( + self, merge: bool, safe_merge: bool, adapter_names: Optional[list[str]] + ) -> nn.MultiheadAttention: + """ + Merging and unloading of the MultiheadAttention module + + This requires an extra step for MultiheadAttention, which is why there is this special method instead of + relying on the normal merge_and_unload code path. + """ + if merge: + self.merge(safe_merge=safe_merge, adapter_names=adapter_names) + base_layer = self.get_base_layer() + + # extra steps: re-register weights, take care of out_proj layer + # in_proj + weight = base_layer.in_proj_weight + del base_layer.in_proj_weight + base_layer.register_parameter("in_proj_weight", nn.Parameter(weight.data, requires_grad=weight.requires_grad)) + + # out_proj + out_proj_layer = base_layer.out_proj.get_base_layer() + weight = out_proj_layer.weight + del out_proj_layer.weight + out_proj_layer.register_parameter("weight", nn.Parameter(weight.data, requires_grad=weight.requires_grad)) + + base_layer.out_proj = out_proj_layer + return base_layer + + 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.lora_B[adapter].weight.device + dtype = self.lora_B[adapter].weight.dtype + + # In case users wants to merge the adapter weights that are in + # float16 while being on CPU, we need to cast the weights to float32, perform the merge and then cast back to + # float16 because the `@` and matmul operation in general is not supported in torch + cpu + fp16. + cast_to_fp32 = device.type == "cpu" and dtype == torch.float16 + + weight_A = self.lora_A[adapter].weight + weight_B = self.lora_B[adapter].weight + + if cast_to_fp32: + weight_A = weight_A.float() + weight_B = weight_B.float() + + output_tensor = (weight_B @ weight_A) * self.scaling[adapter] + + if cast_to_fp32: + output_tensor = output_tensor.to(dtype=dtype) + + # cast back the weights + self.lora_A[adapter].weight.data = weight_A.to(dtype) + self.lora_B[adapter].weight.data = weight_B.to(dtype) + + return output_tensor + + def _check_forward_args(self, x, *args, **kwargs): + if "adapter_names" in kwargs: + raise TypeError(f"lora.{self.__class__.__name__} does not support mixed adapter batches.") + super()._check_forward_args(x, *args, **kwargs) + + def forward(self, query: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + previous_dtype = query.dtype + self._check_forward_args(query, *args, **kwargs) + + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(query, *args, **kwargs) + elif self.merged: + result = self.base_layer(query, *args, **kwargs) + else: + out_proj = self.get_base_layer().out_proj + if out_proj.active_adapters != self.active_adapters: + # We have a case that in_proj and out_proj have diverging merged adapters. We cannot + # really deal with this correctly, thus it's better to raise than possibly create a hard to debug mess + cls_name = self.get_base_layer().__class__.__name__ + raise ValueError( + f"The out_proj layer of {cls_name} has merged layers but {cls_name} itself doesn't; please ensure " + "that either both or none have merged layers" + ) + + # Merge all adapters that are active for this module, i.e. the LoRA weights for in_proj and out_proj. + # in_proj uses nn.Parameters, therefore, there is no forward method to be used and we have to explicitly + # merge for the LoRA weights to have an effect: + # https://github.com/pytorch/pytorch/blob/6ebb26d572d5fcdc6ac0d1297bdf8d1eb5d20722/torch/nn/modules/activation.py#L1020 + # For out_proj, we have an nn.Linear (or rather: NonDynamicallyQuantizableLinear), but its forward method + # is not used: + # https://github.com/pytorch/pytorch/blob/6ebb26d572d5fcdc6ac0d1297bdf8d1eb5d20722/torch/nn/modules/activation.py#L1267-L1271 + # Therefore, its LoRA weights also need to be merged to have an effect. + active_adapters = [a for a in self.active_adapters if a in self.lora_A] + try: + self.merge(adapter_names=active_adapters) + result = self.base_layer(query, *args, **kwargs) + finally: + # it's safe to call unmerge(), which unmerges all adapters, because we checked that not self.merged, + # i.e. there is was no merged layer before + self.unmerge() + + result = (result[0].to(previous_dtype), result[1].to(previous_dtype) if result[1] is not None else result[1]) + return result + + # The decorator is needed in case low_cpu_mem_usage=True is used, as we don't want the base layer weights to be + # moved to meta device. This requires the use of PEFT's implementation of init_empty_weight instead of using the one + # from accelerate. + @skip_init_on_device + def _restore_weights(self): + # Restore the weights as registered parameters on the base layer. + # This is necessary because the way that weights are merged/unmerged (which is necessary for forward to work + # correctly), the Module "forgets" these attributes. Therefore, we need to call register_parameter explicitly. + # We cannot call register_parameter for merging/unmerging because that cuts them off from the autograd graph. + # Note that this is hacky, since we need to ensure that _restore_weights is called by each method that needs it. + + # in_proj + # TODO work with separate weights + base_layer = self.get_base_layer() + weight = base_layer.in_proj_weight + del base_layer.in_proj_weight + base_layer.register_parameter("in_proj_weight", nn.Parameter(weight.data, requires_grad=weight.requires_grad)) + + # out_proj + base_layer = base_layer.out_proj.get_base_layer() + weight = base_layer.weight + del base_layer.weight + base_layer.register_parameter("weight", nn.Parameter(weight.data, requires_grad=weight.requires_grad)) + + def state_dict(self, *args, **kwargs): + self._restore_weights() + return super().state_dict(*args, **kwargs) + + def named_modules(self, *args, **kwargs): + # Note: no need to also implement modules(), as modules() calls named_modules() under the hood + self._restore_weights() + return super().named_modules(*args, **kwargs) + + def __repr__(self) -> str: + rep = super().__repr__() + return "lora." + rep + + +class _LoraParameterProxy(nn.Module): + """This proxies an `nn.Parameter` that is targeted with LoRA. + Intended to be used in conjunction with `nn.utils.parametrize`, see `ParamWrapper`. + """ + + def __init__(self, delta_weight): + super().__init__() + self.delta_weight = delta_weight + + @staticmethod + def _low_prec_add(x, y): + # addition in fp8 is not directly supported, need to use a higher precision + orig_dtype = x.dtype + upcast_dtype = y.dtype + if upcast_dtype not in ALLOWED_COMPUTE_DTYPES: + raise RuntimeError( + f"There is an attempt to upcast the targeted parameter to {upcast_dtype} " + f"but the only supported are: {ALLOWED_COMPUTE_DTYPES}." + ) + + # this operation can be quite costly + x = x.to(upcast_dtype) + z = x + y + # clamp to valid range before casting down, as this is *not* performed automatically and can thus result in NANs + info = torch.finfo(orig_dtype) + z = z.clamp(min=info.min, max=info.max) + return z.to(orig_dtype) + + def forward(self, W): + if any(getattr(torch, dtype_name, None) == W.dtype for dtype_name in UPCAST_DTYPES): + return self._low_prec_add(W, self.delta_weight) + return W + self.delta_weight + + +# copied from: +# https://github.com/pytorch/pytorch/blob/5e386eec9426f174eea130c0c012d9f65ebe65fb/torch/nn/utils/parametrize.py#L75-L79 +def _register_parameter_or_buffer(module, name, X): + if isinstance(X, nn.Parameter): + module.register_parameter(name, X) + else: + module.register_buffer(name, X) + + +class ParamWrapper(nn.Module, LoraLayer): + """A LoRA wrapper for `nn.Parameter`. This layer is dispatched if users target a parameter directly with + `lora_config.target_parameters` + Note: + - When accessing the wrapped nn.Parameter directly, e.g. via `module.weight`, the LoRA weights are *not* + applied. + - It is currently not implemented to target multiple parameters on the same module. To achieve this, it is + currently required to create a separate LoRA adapter (with another adapter name) and activate both at the + same time. + """ + + def __init__( + self, + base_layer, + adapter_name: str, + parameter_name: str, + config: LoraConfig, + r: int = 0, + lora_alpha: int = 1, + is_target_conv_1d_layer: bool = False, + **kwargs, + ) -> None: + self.parameter_name = parameter_name + super().__init__() + LoraLayer.__init__(self, base_layer, **kwargs) + + if config.lora_dropout: + # It's not possible to factor out x from lora_B(lora_A(dropout(x))), so dropout can't be correctly + # implemented + raise ValueError(f"lora.{self.__class__.__name__} does not work with lora_dropout != 0.") + if config.fan_in_fan_out: + raise ValueError(f"lora.{self.__class__.__name__} does not work with fan_in_fan_out.") + if config.lora_bias: + raise ValueError(f"lora.{self.__class__.__name__} does not work with lora_bias=True.") + if config.use_dora: + raise ValueError(f"lora.{self.__class__.__name__} does not work with use_dora=True.") + if config.velora_config is not None: + raise ValueError(f"lora.{self.__class__.__name__} does not work when `velora_config` is set.") + if is_target_conv_1d_layer: + raise ValueError(f"lora.{self.__class__.__name__} does not work with is_target_conv_1d_layer=True.") + + self.fan_in_fan_out = config.fan_in_fan_out + self._did_swap_in_out_features = False # ensure we swap only once + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + r, + lora_alpha=lora_alpha, + config=config, + ) + + def _get_in_out_features(self, module: nn.Module) -> tuple[int, int] | tuple[None, None]: + # For ParamWrapper, we don't derive the in_features and out_features based on the base layer type, but directly + # from the targeted parameter. + param = self.get_param() + if param.ndim == 3: + num_experts, in_features, out_features = param.shape + else: + num_experts, in_features, out_features = 1, param.shape[1], param.shape[0] + if param.ndim not in (2, 3): + raise ValueError( + f"lora.{self.__class__.__name__} was initialized with {param.ndim} dimensional Parameter, but only 2d " + "and 3d are supported." + ) + # we have to store the num_experts attribute here, as the parent class only stores in_features and out_features. + self.num_experts = num_experts + return in_features, out_features + + def update_layer( + self, + adapter_name: str, + r: int, + lora_alpha: int, + config: LoraConfig, + **kwargs, + ) -> None: + # same method as in lora.Linear but taking into account that there can be multiple experts (3d parameter) + lora_dropout = config.lora_dropout + init_lora_weights = config.init_lora_weights + use_rslora = config.use_rslora + lora_bias = config.lora_bias + inference_mode = config.inference_mode + # This code works for linear layers, override for other layer types + if r <= 0: + raise ValueError(f"`r` should be a positive integer value but the value passed is {r}") + + lora_variant = self.resolve_lora_variant(config=config) + if lora_variant is not None: + raise ValueError(f"lora.{self.__class__.__name__} does not work with LoRA variants like DoRA.") + + # for some MoE layers, the order is (experts, out_features, in_features) + is_transposed = getattr(self.get_base_layer(), "is_transposed", False) + swap_in_out_features = (self.get_param().ndim == 3) and not is_transposed + if swap_in_out_features and not self._did_swap_in_out_features: + self.in_features, self.out_features = self.out_features, self.in_features + self._did_swap_in_out_features = True + + self.r[adapter_name] = r + self.lora_alpha[adapter_name] = lora_alpha + if lora_dropout > 0.0: + # It's not possible to factor out x from lora_B(lora_A(dropout(x))), so dropout can't be correctly + # implemented + raise ValueError(f"lora.{self.__class__.__name__} does not work with lora_dropout != 0.") + else: + lora_dropout_layer = nn.Identity() + + self.lora_dropout.update(nn.ModuleDict({adapter_name: lora_dropout_layer})) + # Actual trainable parameters + # Difference to normal update_layer: consider experts. LoRA layers still use nn.Linear for consistency with + # lora.Linear. + self.lora_A[adapter_name] = nn.Linear(self.in_features, r * self.num_experts, bias=False) + self.lora_B[adapter_name] = nn.Linear(r * self.num_experts, self.out_features, bias=lora_bias) + self.lora_bias[adapter_name] = lora_bias + + if use_rslora: + self.scaling[adapter_name] = lora_alpha / math.sqrt(r) + else: + self.scaling[adapter_name] = lora_alpha / r + + self.use_rslora[adapter_name] = use_rslora + + self.use_dora[adapter_name] = config.use_dora + + # for inits that require access to the base weight, use gather_param_ctx so that the weight is gathered when using DeepSpeed + if isinstance(init_lora_weights, str) and init_lora_weights.startswith("pissa"): + with gather_params_ctx(self.get_base_layer().weight): + self.pissa_init(adapter_name, init_lora_weights) + elif isinstance(init_lora_weights, str) and init_lora_weights.startswith("corda"): + with gather_params_ctx(self.get_base_layer().weight): + self.corda_init(adapter_name, init_lora_weights) + elif isinstance(init_lora_weights, str) and init_lora_weights.lower() == "olora": + with gather_params_ctx(self.get_base_layer().weight): + self.olora_init(adapter_name) + elif init_lora_weights == "loftq": + with gather_params_ctx(self.get_base_layer().weight): + self.loftq_init(adapter_name) + elif init_lora_weights == "eva": + nn.init.zeros_(self.lora_B[adapter_name].weight) + elif init_lora_weights == "orthogonal": + with gather_params_ctx(self.get_base_layer().weight): + self.orthogonal_init(adapter_name) + elif init_lora_weights == "lora_ga": + with gather_params_ctx(self.get_base_layer().weight): + self.lora_ga_init(adapter_name, config.lora_ga_config) + elif init_lora_weights: + self.reset_lora_parameters(adapter_name, init_lora_weights) + # call this before init of the lora variants + self._move_adapter_to_device_of_base_layer(adapter_name) + + if adapter_name in self.lora_variant: + self.lora_variant[adapter_name].init(self, config=config, **kwargs) + + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def _move_adapter_to_device_of_base_layer(self, adapter_name: str, device: Optional[torch.device] = None) -> None: + """ + Move the adapter of the given name to the device of the base layer. Needs special handling for nn.Parameter + """ + device = self.get_param().device + meta = torch.device("meta") + param = self.get_param() + + for adapter_layer_name in self.adapter_layer_names + self.other_param_names: + adapter_layer = getattr(self, adapter_layer_name, None) + if not isinstance(adapter_layer, (nn.ModuleDict, nn.ParameterDict, BufferDict)): + continue + if adapter_name not in adapter_layer: + continue + if any(p.device == meta for p in adapter_layer.parameters()): + continue + + if param.dtype.is_floating_point or param.dtype.is_complex: + adapter_layer[adapter_name] = adapter_layer[adapter_name].to(device, dtype=param.dtype) + else: + adapter_layer[adapter_name] = adapter_layer[adapter_name].to(device) + + def get_param(self): + param = getattr(self.get_base_layer(), self.parameter_name) + return param + + def get_delta_weight(self, adapter_name, *args, **kwargs): + if self.num_experts == 1: + # could actually be a normal layer or experts stacked block-diagonally, acting like a single layer + delta_weight = Linear.get_delta_weight(self, adapter_name, *args, **kwargs) + else: + weight_A = self.lora_A[adapter_name].weight + weight_B = self.lora_B[adapter_name].weight + # shape: experts x rank x in_features + weight_A = weight_A.reshape(self.num_experts, -1, weight_A.shape[-1]) + # shape: out_features x rank x experts + weight_B = weight_B.reshape(weight_B.shape[0], -1, self.num_experts) + # fan_in_fan_out must be False, so no transpose call here + if not self._did_swap_in_out_features: + delta_weight = torch.einsum("o r e, e r i -> e i o", weight_B, weight_A) * self.scaling[adapter_name] + else: + # for some MoE layers, the order is (experts, out_features, in_features) + delta_weight = torch.einsum("o r e, e r i -> e o i", weight_B, weight_A) * self.scaling[adapter_name] + + param = self.get_param() + if param.dtype in ALLOWED_COMPUTE_DTYPES: + delta_weight = delta_weight.to(param.device, param.dtype) + else: + # don't cast dW to weight dtype if it is in torch.float8_e4m3fn etc. as these low precision dtypes because + # we want to perform the W+dW addition in high precision before downcasting, see _low_prec_add. + delta_weight = delta_weight.to(param.device) + return delta_weight + + @contextmanager + def _activate_lora(self, active_adapters: list[str]): + if not active_adapters or not any(adapter in self.lora_A for adapter in active_adapters): + # no active adapters for this layer + yield + return + + delta_weight = None + for active_adapter in active_adapters: + if active_adapter not in self.lora_A: + continue + if delta_weight is None: + delta_weight = self.get_delta_weight(active_adapter) + else: + delta_weight = delta_weight + self.get_delta_weight(active_adapter) + + base_layer = self.get_base_layer() + requires_grad_before = self.get_param().requires_grad + nn.utils.parametrize.register_parametrization( + base_layer, self.parameter_name, _LoraParameterProxy(delta_weight) + ) + # set requires_grad, as it defaults to False + base_layer.parametrizations[self.parameter_name].original.requires_grad_(requires_grad_before) + try: + with nn.utils.parametrize.cached(): + yield + finally: + self._remove_parametrizations() + + def _remove_parametrizations(self): + # Remove the parametrization of this specific parameter + base_layer = self.get_base_layer() + parameter_name = self.parameter_name + if parameter_name not in base_layer.parametrizations: + raise ValueError( + "Something went wrong, please report this issue on PEFT: https://github.com/huggingface/peft/issues" + ) + + param_list = base_layer.parametrizations[parameter_name] + if len(param_list) == 1: + # last parametrization, we can safely remove it completely + nn.utils.parametrize.remove_parametrizations(base_layer, parameter_name, leave_parametrized=False) + return + + # If there are multiple parametrizations for the same parameter_name, we only want to remove the LoRA proxy. + # Unfortunately, PyTorch does not support this directly, so we need to take care of it manually. To achieve + # this, we check the ParameterList from the back until we find the _LoraParameterProxy instance and then remove + # it. + reversed_indices = reversed(range(len(param_list))) + for i in reversed_indices: + module = param_list[i] + if isinstance(module, _LoraParameterProxy): + del param_list[i] + break + else: # no break encountered + # this should not happen, but raising an error is probably not necessary + warnings.warn( + f"Could not find any LoRA parametrization on {self}, please open an issue on " + "https://github.com/huggingface/peft/issues and report this warning." + ) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + # same as lora.Linear.merge but not hard-coding base_layer.weight and without special cases like variants removed + 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.lora_A.keys(): + base_layer = self.get_base_layer() + param = getattr(base_layer, self.parameter_name) + if safe_merge: + # Note that safe_merge will be slower than the normal merge + # because of the copy operation. + orig_weight = param.data.clone() + orig_dtype = orig_weight.dtype + delta_weight = self.get_delta_weight(active_adapter) + orig_weight += delta_weight.to(orig_dtype) + + if not torch.isfinite(orig_weight).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + param.data = orig_weight + + else: + delta_weight = self.get_delta_weight(active_adapter) + param.data += delta_weight + + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + # same as lora.Linear.unmerge but not hard-coding base_layer.weight and without special cases like variants removed + 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.lora_A.keys(): + param = getattr(self.get_base_layer(), self.parameter_name) + orig_dtype = param.dtype + delta_weight = self.get_delta_weight(active_adapter) + param.data -= delta_weight.to(orig_dtype) + + def _check_forward_args(self, x, *args, **kwargs): + """Check if the arguments are compatible with the configs and state of the model""" + if kwargs.get("adapter_names", None): + raise ValueError(f"lora.{self.__class__.__name__} does not support mixed adapter batches yet.") + super()._check_forward_args(x, *args, **kwargs) + + def unload_and_optionally_merge_module(self, merge: bool, safe_merge: bool, adapter_names: Optional[list[str]]): + base_layer = self.base_layer + # ParamWrappers can be nested, so merge and retrieve base layer recursively + if merge: + self.merge(safe_merge=safe_merge, adapter_names=adapter_names) + while isinstance(base_layer, ParamWrapper): + base_layer.merge(safe_merge=safe_merge, adapter_names=adapter_names) + base_layer = base_layer.base_layer + else: + base_layer = self.get_base_layer() + return base_layer + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> 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: + raise ValueError(f"lora.{self.__class__.__name__} does not support mixed batch inference") + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + with self._activate_lora(self.active_adapters): + result = self.base_layer(x, *args, **kwargs) + return result + + def __repr__(self) -> str: + rep = super().__repr__() + idx = rep.find("(") + 1 + # insert the name of the parameter to allow the repr to be disambiguous when multiple parameters on the same + # module are being targeted + rep = f"{rep[:idx]}\n parameter_name='{self.parameter_name}',{rep[idx:]}" + return "lora." + rep + + +def dispatch_default( + target: torch.nn.Module, + adapter_name: str, + config: LoraConfig, + parameter_name: Optional[str] = None, + **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 parameter_name is not None: + new_module = ParamWrapper(target, adapter_name, parameter_name=parameter_name, config=config, **kwargs) + elif isinstance(target_base_layer, torch.nn.Embedding): + new_module = Embedding(target, adapter_name, config=config, **kwargs) + elif isinstance(target_base_layer, torch.nn.Conv2d): + new_module = Conv2d(target, adapter_name, config=config, **kwargs) + elif isinstance(target_base_layer, torch.nn.Conv3d): + new_module = Conv3d(target, adapter_name, config=config, **kwargs) + elif isinstance(target_base_layer, nn.Conv1d): + new_module = Conv1d(target, adapter_name, config=config, **kwargs) + elif isinstance(target_base_layer, torch.nn.MultiheadAttention): + new_module = MultiheadAttention(target, adapter_name, config=config, **kwargs) + elif isinstance(target_base_layer, torch.nn.Linear): + if config.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." + ) + config.fan_in_fan_out = False + new_module = Linear(target, adapter_name, config=config, **kwargs) + elif isinstance(target_base_layer, Conv1D): + if not config.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." + ) + config.fan_in_fan_out = True + new_module = Linear(target, adapter_name, is_target_conv_1d_layer=True, config=config, **kwargs) + + return new_module diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/loraga.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/loraga.py new file mode 100644 index 0000000000000000000000000000000000000000..bb0926e3a67c189d4ffbd38b5b079a0e0ca9ece7 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/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 +from torch import 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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/model.py new file mode 100644 index 0000000000000000000000000000000000000000..8be27902684e6c5678191e5f4868682239115288 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/model.py @@ -0,0 +1,1076 @@ +# 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 math +import operator +import re +import warnings +from contextlib import contextmanager +from dataclasses import replace +from functools import partial, reduce +from typing import Literal, Optional, Union + +import packaging.version +import torch +import transformers +from torch import nn + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available, is_transformers_ge_v5_4_0 +from peft.tuners.tuners_utils import ( + BaseTuner, + BaseTunerLayer, + find_parameter_name_by_module, + get_device_map, + replicate_layers, +) +from peft.utils import ( + TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING, + AuxiliaryTrainingWrapper, + ModulesToSaveWrapper, + _freeze_adapter, + _get_submodules, + get_peft_model_state_dict, + get_quantization_config, +) +from peft.utils.integrations import TpInfo +from peft.utils.merge_utils import dare_linear, dare_ties, magnitude_prune, task_arithmetic, ties +from peft.utils.other import get_pattern_key + +from .aqlm import dispatch_aqlm +from .awq import dispatch_awq +from .config import LoraConfig +from .eetq import dispatch_eetq +from .gptq import dispatch_gptq +from .hqq import dispatch_hqq +from .inc import dispatch_inc +from .layer import Conv2d, LoraLayer, ParamWrapper, dispatch_default +from .te import dispatch_transformer_engine +from .torchao import dispatch_torchao +from .tp_layer import dispatch_megatron + + +def _adapter_names_pre_forward_hook(target, args, kwargs, adapter_names): + # pre-forward hook to inject the adapter_names argument when using mixed adapter batches inference + kwargs["adapter_names"] = adapter_names + return args, kwargs + + +def _alora_offsets_pre_forward_hook(target, args, kwargs, alora_offsets): + kwargs["alora_offsets"] = alora_offsets + return args, kwargs + + +def _get_encoder(model: nn.Module) -> nn.Module | None: + """Check if the model has an encoder and if it has, returns it; otherwise returns None""" + if not hasattr(model, "get_encoder"): + return None + + encoder = model.get_encoder() + # https://github.com/huggingface/transformers/pull/42156 + # new logic in transformers v5: all PretrainedModels return a model here, but it is self if there is no encoder + if encoder is model: + return None + return encoder + + +class LoraModel(BaseTuner): + """ + Creates Low Rank Adapter (LoRA) model from a pretrained transformers model. + + The method is described in detail in https://huggingface.co/papers/2106.09685. + + Args: + model ([`torch.nn.Module`]): The model to be adapted. + config ([`LoraConfig`]): The configuration of the Lora 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 Lora model. + + Example: + + ```py + >>> from transformers import AutoModelForSeq2SeqLM + >>> from peft import LoraModel, LoraConfig + + >>> config = LoraConfig( + ... task_type="SEQ_2_SEQ_LM", + ... r=8, + ... lora_alpha=32, + ... target_modules=["q", "v"], + ... lora_dropout=0.01, + ... ) + + >>> model = AutoModelForSeq2SeqLM.from_pretrained("t5-base") + >>> lora_model = LoraModel(model, config, "default") + ``` + + ```py + >>> import torch + >>> import transformers + >>> from peft import LoraConfig, PeftModel, get_peft_model, prepare_model_for_kbit_training + + >>> rank = ... + >>> target_modules = ["q_proj", "k_proj", "v_proj", "out_proj", "fc_in", "fc_out", "wte"] + >>> config = LoraConfig( + ... r=4, lora_alpha=16, target_modules=target_modules, lora_dropout=0.1, bias="none", task_type="CAUSAL_LM" + ... ) + >>> quantization_config = transformers.BitsAndBytesConfig(load_in_8bit=True) + + >>> tokenizer = transformers.AutoTokenizer.from_pretrained( + ... "kakaobrain/kogpt", + ... revision="KoGPT6B-ryan1.5b-float16", # or float32 version: revision=KoGPT6B-ryan1.5b + ... bos_token="[BOS]", + ... eos_token="[EOS]", + ... unk_token="[UNK]", + ... pad_token="[PAD]", + ... mask_token="[MASK]", + ... ) + >>> model = transformers.GPTJForCausalLM.from_pretrained( + ... "kakaobrain/kogpt", + ... revision="KoGPT6B-ryan1.5b-float16", # or float32 version: revision=KoGPT6B-ryan1.5b + ... pad_token_id=tokenizer.eos_token_id, + ... use_cache=False, + ... device_map={"": rank}, + ... torch_dtype=torch.float16, + ... quantization_config=quantization_config, + ... ) + >>> model = prepare_model_for_kbit_training(model) + >>> lora_model = get_peft_model(model, config) + ``` + + **Attributes**: + - **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted. + - **peft_config** ([`LoraConfig`]): The configuration of the Lora model. + """ + + prefix: str = "lora_" + tuner_layer_cls = LoraLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING + + def _prepare_model(self, peft_config: LoraConfig, model: nn.Module): + r""" + A private method to modify the model structure before adapter is applied. + + Args: + peft_config (`PeftConfig`): + The prepared adapter config. + model (`nn.Module`): + The model that is going to be adapted. + """ + if peft_config.layer_replication: + replicate_layers(model, peft_config.layer_replication) + + def _create_and_replace( + self, + lora_config, + adapter_name, + target, + target_name, + parent, + current_key, + *, + parameter_name: Optional[str] = None, + ) -> None: + if current_key is None: + raise ValueError("Current Key shouldn't be `None`") + + if lora_config.target_parameters: + # Right now, unfortunately, we don't support multiple adapters with target_parameters on the same model. + other_configs_use_target_params = any( + conf.target_parameters for key, conf in self.peft_config.items() if key != adapter_name + ) + if other_configs_use_target_params: + raise ValueError( + f"Adding a LoRA config with `target_parameters={lora_config.target_parameters}` but there are " + "already other LoRA adapters on this model that use `target_parameters`. At the moment, only " + "one LoRA adapter per model with `target_parameters` is allowed." + ) + + # Regexp matching - Find key which matches current target_name in patterns provided + r_key = get_pattern_key(lora_config.rank_pattern.keys(), current_key) + alpha_key = get_pattern_key(lora_config.alpha_pattern.keys(), current_key) + r = lora_config.rank_pattern.get(r_key, lora_config.r) + alpha = lora_config.alpha_pattern.get(alpha_key, lora_config.lora_alpha) + + # Checks if the target is marked as a tied layer + # If true, we add the reference to lora adapters of embedding layer in `tied_adapter` + is_tied = target_name in (getattr(lora_config, "target_modules_to_tie", []) or []) + tied_adapter = {} + if is_tied: + tied_module = self.model.get_input_embeddings() + emb_A = tied_module.lora_embedding_A[adapter_name] + emb_B = tied_module.lora_embedding_B[adapter_name] + + tied_adapter = {"lora_A": emb_B.t(), "lora_B": emb_A.t()} + + kwargs = { + "r": r, + "lora_alpha": alpha, + "target_name": current_key, + "loaded_in_8bit": getattr(self.model, "is_loaded_in_8bit", False), + "loaded_in_4bit": getattr(self.model, "is_loaded_in_4bit", False), + "ephemeral_gpu_offload": lora_config.runtime_config.ephemeral_gpu_offload, + "parameter_name": parameter_name, + "tied_adapter": tied_adapter, + } + + # for torchao merging, we need the get_apply_tensor_subclass from the quantization config + try: + kwargs["get_apply_tensor_subclass"] = operator.attrgetter( + "hf_quantizer.quantization_config.get_apply_tensor_subclass" + )(self.model) + except AttributeError: + pass + + 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 + + # note: AdaLoraLayer is a subclass of LoraLayer, we need to exclude it + from peft.tuners.adalora import AdaLoraLayer + + # if the target is a ParamWrapper, we nest it to allow targeting multiple nn.Parameter on the same module + wrap_target_param = isinstance(target, ParamWrapper) and (adapter_name in target.lora_A) + if isinstance(target, LoraLayer) and not isinstance(target, AdaLoraLayer) and not wrap_target_param: + target.update_layer( + adapter_name, + r, + lora_alpha=alpha, + target_name=current_key, + config=lora_config, + ) + + base_layer = target.get_base_layer() + lora_module = target + else: + if isinstance(target, ParamWrapper) and (parameter_name == target.parameter_name): + raise ValueError( + "Trying to target the same nn.Parameter twice, this should not happen. Please open an issue on the " + "PEFT repo: https://github.com/huggingface/peft/issues" + ) + device_map = get_device_map(self.model) + new_module = self._create_new_module(lora_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) + + base_layer = target + lora_module = new_module + + tp_plan = getattr(base_layer, "_hf_tp_plan", None) + device_mesh = getattr(base_layer, "_hf_device_mesh", None) + + # If the module has a tp_plan, we add hooks to the LoRA layers to make sure they respect the plan + if tp_plan is not None: + if not is_transformers_ge_v5_4_0: + raise RuntimeError( + "The base model is tensor-parallel sharded but the installed version of Transformers does not " + "support LoRA with Tensor Parallelism. Please upgrade to transformers >= 5.4.0." + ) + from transformers.integrations.tensor_parallel import ( + add_tensor_parallel_hooks_to_module, + ) + + _SUPPORTED_TP_PLANS = ("colwise", "rowwise", "embedding_rowwise") + + if tp_plan not in _SUPPORTED_TP_PLANS: + warnings.warn( + f'TP plan "{tp_plan}" on the base layer is not supported for LoRA. ' + "LoRA adapters will be created without tensor parallel hooks." + ) + else: + tp_plan_keys = [] + tp_plans = [] + generic_key = re.sub(r"\d+", "*", current_key) + if tp_plan in ["colwise", "rowwise"]: + if tp_plan == "colwise": + tp_plan_keys.append(f"{generic_key}.lora_B.{adapter_name}.weight") + tp_module = lora_module.lora_B[adapter_name] + tp_layer_name = (f"{current_key}.lora_B.{adapter_name}",) + else: # rowwise + tp_plan_keys.append(f"{generic_key}.lora_A.{adapter_name}.weight") + tp_module = lora_module.lora_A[adapter_name] + tp_layer_name = (f"{current_key}.lora_A.{adapter_name}",) + tp_plans.append(tp_plan) + add_tensor_parallel_hooks_to_module( + self.model, + tp_module, + tp_plan, + tp_layer_name, + device_mesh, + ) + else: # embedding_rowwise + # TP hooks are handled in the `_embed` method in lora/layer.py where they are explicitely called. + # Here we simply register the TP plans. + tp_plan_keys.append(f"{generic_key}.base_layer.weight") + tp_plan_keys.append(f"{generic_key}.lora_embedding_A.{adapter_name}") + tp_plans.append(tp_plan) + # Because lora_embedding_A is transposed compared to nn.Embedding, we set the TP plan + # to embedding_colwise so that the gathering happens on the correct dimension at save time. + tp_plans.append("embedding_colwise") + + lora_module._tp_info = TpInfo( + tp_plan=dict(zip(tp_plan_keys, tp_plans)), + device_mesh=device_mesh, + tp_size=self.model._tp_size, + ) + + def _replace_module(self, parent, child_name, new_module, child): + # override in LoraModel to handle quantized weights properly + + setattr(parent, child_name, new_module) + # It's not necessary to set requires_grad here, as that is handled by + # _mark_only_adapters_as_trainable + + # child layer wraps the original module, unpack it + if hasattr(child, "base_layer"): + child = child.base_layer + + meta = torch.device("meta") + # dispatch to correct device + for name, module in new_module.named_modules(): + if (self.prefix in name) or ("ranknum" in name): + if hasattr(child, "qweight"): + weight = child.qweight + elif hasattr(child, "W_q"): + weight = child.W_q + elif hasattr(child, "weight"): + weight = child.weight + elif getattr(child, "in_proj_weight", None) is not None: # MHA + weight = child.in_proj_weight + else: + weight = next(child.parameters()) + if not any(p.device == meta for p in module.parameters()): + module.to(weight.device) + + @staticmethod + def _create_new_module(lora_config, adapter_name, target, **kwargs): + # Collect dispatcher functions to decide what backend to use for the replaced LoRA layer. The order matters, + # because the first match is always used. Therefore, the default layers should be checked last. + dispatchers = [] + + if lora_config._custom_modules: + # Experimental custom LoRA module support. Allows users to pass a custom mapping for unsupported layer + # types by impelementing their own LoRA layers. + def dynamic_dispatch_func(target, adapter_name, config, **kwargs): + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + for key, custom_cls in config._custom_modules.items(): + if isinstance(target_base_layer, key): + new_module = custom_cls(target, adapter_name, config=config, **kwargs) + break + + return new_module + + dispatchers.append(dynamic_dispatch_func) + + # 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_torchao, + dispatch_megatron, + dispatch_transformer_engine, + dispatch_default, + ] + ) + + new_module = None + for dispatcher in dispatchers: + new_module = dispatcher(target, adapter_name, config=lora_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.Embedding`, `torch.nn.Conv1d`, `torch.nn.Conv2d`, `torch.nn.Conv3d`, " + "`transformers.pytorch_utils.Conv1D`, `torch.nn.MultiheadAttention.`." + ) + + return new_module + + @contextmanager + def _enable_peft_forward_hooks(self, *args, **kwargs): + # If adapter_names is passed as an argument, we inject it into the forward arguments. + adapter_names = kwargs.pop("adapter_names", None) + alora_offsets = kwargs.pop("alora_offsets", None) + + if adapter_names is None and alora_offsets is None: + # nothing to do + yield + return + hook_handles = [] + + if alora_offsets is not None: + # TODO: remove once transformers 4.52 is no longer supported. Note that 4.52.0 is yanked, so 4.52.1 + # is the first 4.52 release. + transformers_lt_4_52 = packaging.version.parse(transformers.__version__) < packaging.version.parse( + "4.52.1" + ) + if transformers_lt_4_52: + raise ValueError("Using aLoRA requires transformers >= 4.52.1.") + + from transformers.modeling_layers import GradientCheckpointingLayer + + for n, layer in self.named_modules(): + # gradient checkpointing layer are executed concurrently to the 'normal' forward call + # (in the backward step the gradient checkpointing layer's forward will be executed again). + # this means that when the gradient checkpointing layer is called, the _enable_peft_forward_hooks + # context manager is long gone. to be consistent with the normal forward we need to register the pre + # hooks for this concurrent forward call as well. + # + # Note that this will lead to double application of whatever the callbacks do in normal forward. + # Make sure that whatever change is done, can be applied more than once without harm (idempotency). + if isinstance(layer, GradientCheckpointingLayer) and layer.gradient_checkpointing: + + def forward_pre_hook(name, module, inputs, **kwargs): + for submodule in module.modules(): + if isinstance(submodule, LoraLayer): + handle = submodule.register_forward_pre_hook( + partial(_alora_offsets_pre_forward_hook, alora_offsets=kwargs["alora_offsets"]), + with_kwargs=True, + ) + module._peft_gradient_checkpointing_forward_hooks.append(handle) + + def backward_hook(name, module, *grad_output, **kwargs): + while module._peft_gradient_checkpointing_forward_hooks: + module._peft_gradient_checkpointing_forward_hooks.pop().remove() + + if getattr(layer, "_peft_gradient_checkpointing_forward_hooks", []): + raise ValueError( + "Multiple invocations of PEFT forward hooks before .backward() with enabled gradient " + "checkpointing. Disable gradient checkpointing or only call forward once per backward." + ) + layer._peft_gradient_checkpointing_forward_hooks = [] + handle = layer.register_forward_pre_hook(partial(forward_pre_hook, n, alora_offsets=alora_offsets)) + layer._peft_gradient_checkpointing_forward_hooks.append(handle) + handle = layer.register_full_backward_hook(partial(backward_hook, n)) + layer._peft_gradient_checkpointing_forward_hooks.append(handle) + if isinstance(layer, LoraLayer): + pre_forward = partial(_alora_offsets_pre_forward_hook, alora_offsets=alora_offsets) + handle = layer.register_forward_pre_hook(pre_forward, with_kwargs=True) + hook_handles.append(handle) + num_beams = kwargs.get("num_beams", None) + uses_beam_search = isinstance(num_beams, int) and (num_beams > 1) + if uses_beam_search: + if alora_offsets is not None: + raise ValueError("Beam search not yet supported for aLoRA.") + if adapter_names is not None: + if self.training: + raise ValueError("Cannot pass `adapter_names` when the model is in training mode.") + + # Check that users only passed actually existing adapters. + # Note: We cannot do this on the layer level, as each individual layer may not have each adapter. Still, we want + # to check that there is at least one layer with the given name, or else something like typos can easily slip. + expected_adapters = set() + for layer in self.modules(): + if isinstance(layer, LoraLayer): + expected_adapters |= layer.lora_A.keys() + expected_adapters |= layer.lora_embedding_A.keys() + unique_adapters = {name for name in adapter_names if name != "__base__"} + unexpected_adapters = unique_adapters - expected_adapters + if unexpected_adapters: + raise ValueError( + f"Trying to infer with non-existing adapter(s): {', '.join(sorted(unexpected_adapters))}" + ) + + # deal with beam search + original_adapter_names = adapter_names[:] + if uses_beam_search: + if not isinstance(adapter_names, (list, tuple)): + raise TypeError(f"Got adapter names of type {type(adapter_names)}, expected a list of str.") + # When there is beam search, the inputs are repeated n times, thus we repeat each adapter name n times and + # then flatten the nested list. For encoder-decoder models, this extended list should not be applied to the + # encoder part. Further below, the original argument is thus restored for the encoder. + adapter_names = [n for n in adapter_names for _ in range(kwargs["num_beams"])] + + for module in self.modules(): + if isinstance(module, (LoraLayer, AuxiliaryTrainingWrapper)): + pre_forward = partial(_adapter_names_pre_forward_hook, adapter_names=adapter_names) + handle = module.register_forward_pre_hook(pre_forward, with_kwargs=True) + hook_handles.append(handle) + + encoder = _get_encoder(self.model) + if uses_beam_search and (encoder is not None): + # For encoder-decoder models, even when applying beam search, the encoder part of the model should not use + # the extended adapter_names. This is because the encoder still uses the original, non-extended samples. + for module in encoder.modules(): + if isinstance(module, (LoraLayer, AuxiliaryTrainingWrapper)): + # Add another hook to overwrite the kwargs with the original adapter names -- this is easier than + # trying to exclude the encoder. + pre_forward = partial(_adapter_names_pre_forward_hook, adapter_names=original_adapter_names) + handle = module.register_forward_pre_hook(pre_forward, with_kwargs=True) + hook_handles.append(handle) + + yield + + for handle in hook_handles: + handle.remove() + + 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 LORA layers when the model is gptq quantized") + if self.peft_config.get("layer_replication"): + raise ValueError("Cannot merge LORA layers when base model layers are replicated") + + def _prepare_adapter_config(self, peft_config, model_config): + if peft_config.target_modules is None: + target_modules = self.target_module_mapping.get(model_config["model_type"]) + if target_modules is not None: + if isinstance(target_modules, str): + peft_config.target_modules = target_modules + else: + peft_config.target_modules = set(target_modules) + elif not peft_config.target_parameters: + raise ValueError("Please specify `target_modules` or `target_parameters`in `peft_config`") + return peft_config + + def _check_add_weighted_adapter( + self, adapters: list[str], combination_type: str, svd_rank: int | None + ) -> tuple[str, int, str]: + """ + Helper function to check if the arguments to add_weighted_adapter are valid and compatible with the underlying + model. + """ + for adapter in adapters: + if adapter not in list(self.peft_config.keys()): + raise ValueError(f"Adapter {adapter} does not exist") + + for adapter in adapters: + if self.peft_config[adapter].target_parameters: + raise ValueError( + f"add_weighted_adapter does not support targeting nn.Parameter (problematic adapter '{adapter}')" + ) + + # If more than one of the adapters targets the same module with modules_to_save, raise an error, as these + # modules cannot be merged. First, find the ModulesToSaveWrapper instances in the model, then check if they + # have modules for the adapters to be merged. + modules_to_save_wrappers = [module for module in self.modules() if isinstance(module, ModulesToSaveWrapper)] + problematic_wrappers = [ + wrapper + for wrapper in modules_to_save_wrappers + if sum(adapter in wrapper.modules_to_save for adapter in adapters) > 1 + ] + if problematic_wrappers: + raise ValueError( + "Cannot add weighted adapters if they target the same module with modules_to_save, but found " + f"{len(problematic_wrappers)} such instance(s)." + ) + + # if there is only one adapter, we can only use linear merging + combination_type = "linear" if len(adapters) == 1 else combination_type + + adapters_ranks: list[int] = [ + # When allocating tensors for the new adapter, we need the maximum possible rank to not overflow + config.r if not config.rank_pattern else max(config.r, *config.rank_pattern.values()) + for config in (self.peft_config[adapter] for adapter in adapters) + ] + + if combination_type in ("linear", "ties", "dare_ties", "dare_linear", "magnitude_prune"): + # all adapters ranks should be same, new rank is just this value + if len(set(adapters_ranks)) != 1: + raise ValueError( + "All adapters must have the same r value when using combination_type linear, ties, dare_ties or " + "dare_linear." + ) + new_rank = adapters_ranks[0] + elif combination_type == "cat": + # adapters ranks may be different, new rank is sum of all ranks + # be careful, because output adapter rank may be really big if mixing a lot of adapters + new_rank = sum(adapters_ranks) + elif combination_type.endswith("svd"): + # new rank is the max of all ranks of the adapters if not provided + new_rank = svd_rank or max(adapters_ranks) + else: + raise ValueError(f"Invalid combination_type: {combination_type}") + + target_module_types = [type(self.peft_config[adapter].target_modules) for adapter in adapters] + if not target_module_types: + raise ValueError(f"Found no adapter matching the names in {adapters}") + if len(set(target_module_types)) > 1: + raise ValueError( + "all adapter configs should follow the same target modules type. " + "Combining adapters with `target_modules` type being a mix of list/set and string is not supported." + ) + + if target_module_types[0] is str: + new_target_modules = "|".join(f"({self.peft_config[adapter].target_modules})" for adapter in adapters) + elif target_module_types[0] is set: + new_target_modules = reduce( + operator.or_, (self.peft_config[adapter].target_modules for adapter in adapters) + ) + else: + raise TypeError(f"Invalid type {target_module_types[0]} found in target_modules") + + return combination_type, new_rank, new_target_modules + + def add_weighted_adapter( + self, + adapters: list[str], + weights: list[float], + adapter_name: str, + combination_type: str = "svd", + svd_rank: int | None = None, + svd_clamp: int | None = None, + svd_full_matrices: bool = True, + svd_driver: str | None = None, + density: float | None = None, + majority_sign_method: Literal["total", "frequency"] = "total", + ) -> None: + """ + This method adds a new adapter by merging the given adapters with the given weights. + + When using the `cat` combination_type you should be aware that rank of the resulting adapter will be equal to + the sum of all adapters ranks. So it's possible that the mixed adapter may become too big and result in OOM + errors. + + Args: + adapters (`list`): + List of adapter names to be merged. + weights (`list`): + List of weights for each adapter. Weights can be positive or negative, allowing for both addition and + subtraction of adapter effects. + adapter_name (`str`): + Name of the new adapter. + combination_type (`str`): + The merging type can be one of [`svd`, `linear`, `cat`, `ties`, `ties_svd`, `dare_ties`, `dare_linear`, + `dare_ties_svd`, `dare_linear_svd`, `magnitude_prune`, `magnitude_prune_svd`]. When using the `cat` + combination_type, the rank of the resulting adapter is equal to the sum of all adapters ranks (the + mixed adapter may be too big and result in OOM errors). + svd_rank (`int`, *optional*): + Rank of output adapter for svd. If None provided, will use max rank of merging adapters. + svd_clamp (`float`, *optional*): + A quantile threshold for clamping SVD decomposition output. If None is provided, do not perform + clamping. Defaults to None. + svd_full_matrices (`bool`, *optional*): + Controls whether to compute the full or reduced SVD, and consequently, the shape of the returned + tensors U and Vh. Defaults to True. + svd_driver (`str`, *optional*): + Name of the cuSOLVER method to be used. This keyword argument only works when merging on CUDA. Can be + one of [None, `gesvd`, `gesvdj`, `gesvda`]. For more info please refer to `torch.linalg.svd` + documentation. Defaults to None. + density (`float`, *optional*): + Value between 0 and 1. 0 means all values are pruned and 1 means no values are pruned. Should be used + with [`ties`, `ties_svd`, `dare_ties`, `dare_linear`, `dare_ties_svd`, `dare_linear_svd`, + `magnintude_prune`, `magnitude_prune_svd`] + majority_sign_method (`str`): + The method, should be one of ["total", "frequency"], to use to get the magnitude of the sign values. + Should be used with [`ties`, `ties_svd`, `dare_ties`, `dare_ties_svd`] + """ + + if adapter_name in list(self.peft_config.keys()): + return + + combination_type, new_rank, new_target_modules = self._check_add_weighted_adapter( + adapters=adapters, + combination_type=combination_type, + svd_rank=svd_rank, + ) + + self.peft_config[adapter_name] = replace( + self.peft_config[adapters[0]], + r=new_rank, + lora_alpha=new_rank, + target_modules=new_target_modules, + alpha_pattern={}, + rank_pattern={}, + ) + self.inject_adapter(self.model, adapter_name) + + # Do we really need that? + _freeze_adapter(self.model, adapter_name) + + key_list = [key for key, _ in self.model.named_modules() if self.prefix not in key] + for key in key_list: + _, target, _ = _get_submodules(self.model, key) + if isinstance(target, LoraLayer): + if adapter_name in target.lora_A: + target_lora_A = target.lora_A[adapter_name].weight + target_lora_B = target.lora_B[adapter_name].weight + elif adapter_name in target.lora_embedding_A: + target_lora_A = target.lora_embedding_A[adapter_name] + target_lora_B = target.lora_embedding_B[adapter_name] + else: + continue + + target_lora_A.data = target_lora_A.data * 0.0 + target_lora_B.data = target_lora_B.data * 0.0 + if combination_type == "cat": + loras_A, loras_B = [], [] + for adapter, weight in zip(adapters, weights): + if adapter in target.lora_A: + current_adapter_lora_A = target.lora_A[adapter].weight + current_adapter_lora_B = target.lora_B[adapter].weight + elif adapter in target.lora_embedding_A: + current_adapter_lora_A = target.lora_embedding_A[adapter] + current_adapter_lora_B = target.lora_embedding_B[adapter] + else: + continue + loras_A.append(current_adapter_lora_A.data * weight * target.scaling[adapter]) + loras_B.append(current_adapter_lora_B.data) + + if len(loras_A) == 0: + raise ValueError("No matching LoRAs found. Please raise an issue on GitHub.") + loras_A = torch.cat(loras_A, dim=0) + loras_B = torch.cat(loras_B, dim=1) + target_lora_A.data[: loras_A.shape[0], :] = loras_A + target_lora_B.data[:, : loras_B.shape[1]] = loras_B + elif combination_type in [ + "svd", + "ties_svd", + "dare_linear_svd", + "dare_ties_svd", + "magnitude_prune_svd", + ]: + target_lora_A.data, target_lora_B.data = self._svd_generalized_task_arithmetic_weighted_adapter( + combination_type, + adapters, + weights, + new_rank, + target, + target_lora_A, + target_lora_B, + density, + majority_sign_method, + svd_clamp, + full_matrices=svd_full_matrices, + driver=svd_driver, + ) + elif combination_type in ["linear", "ties", "dare_linear", "dare_ties", "magnitude_prune"]: + target_lora_A.data, target_lora_B.data = self._generalized_task_arithmetic_weighted_adapter( + combination_type, adapters, weights, target, density, majority_sign_method + ) + + def _svd_generalized_task_arithmetic_weighted_adapter( + self, + combination_type, + adapters, + weights, + new_rank, + target, + target_lora_A, + target_lora_B, + density, + majority_sign_method, + clamp=None, + full_matrices=True, + driver=None, + ): + valid_adapters = [] + valid_weights = [] + is_embedding = any(adapter in target.lora_embedding_A for adapter in adapters) + for adapter, weight in zip(adapters, weights): + if adapter in target.lora_A or adapter in target.lora_embedding_A: + valid_adapters.append(adapter) + valid_weights.append(weight * target.scaling[adapter]) + + # if no valid adapter, nothing to do + if len(valid_adapters) == 0: + raise ValueError("No matching LoRAs found. Please raise an issue on Github.") + delta_weight = [target.get_delta_weight(adapter) for adapter in valid_adapters] + valid_weights = torch.tensor(valid_weights).to(delta_weight[0].device) + if combination_type == "svd": + delta_weight = task_arithmetic(delta_weight, valid_weights) + elif combination_type == "ties_svd": + delta_weight = ties(delta_weight, valid_weights, density, majority_sign_method) + elif combination_type == "dare_linear_svd": + delta_weight = dare_linear(delta_weight, valid_weights, density) + elif combination_type == "dare_ties_svd": + delta_weight = dare_ties(delta_weight, valid_weights, density, majority_sign_method) + elif combination_type == "magnitude_prune_svd": + delta_weight = magnitude_prune(delta_weight, valid_weights, density) + else: + raise ValueError(f"Invalid value passed to combination type: {combination_type}") + + conv2d = isinstance(target, Conv2d) + if conv2d: + conv2d_1x1 = target.weight.size()[2:4] == (1, 1) + if not conv2d_1x1: + delta_weight = delta_weight.flatten(start_dim=1) + else: + delta_weight = delta_weight.squeeze() + if (hasattr(target, "fan_in_fan_out") and target.fan_in_fan_out) or is_embedding: + delta_weight = delta_weight.T + + # based on https://github.com/kohya-ss/sd-scripts/blob/main/networks/svd_merge_lora.py#L114-L131 + U, S, Vh = torch.linalg.svd(delta_weight, full_matrices=full_matrices, driver=driver) + U = U[:, :new_rank] + S = S[:new_rank] + U = U @ torch.diag(S) + Vh = Vh[:new_rank, :] + if clamp is not None: + dist = torch.cat([U.flatten(), Vh.flatten()]) + hi_val = torch.quantile(dist, clamp) + low_val = -hi_val + U = U.clamp(low_val, hi_val) + Vh = Vh.clamp(low_val, hi_val) + if conv2d: + U = U.reshape(target_lora_B.data.shape) + Vh = Vh.reshape(target_lora_A.data.shape) + return Vh, U + + def _generalized_task_arithmetic_weighted_adapter( + self, + combination_type, + adapters, + weights, + target, + density, + majority_sign_method, + ): + # account weights for LoRA A and B layers. + valid_weights_A = [] + valid_weights_B = [] + lora_A_deltas = [] + lora_B_deltas = [] + for adapter, weight in zip(adapters, weights): + if adapter in target.lora_A: + current_adapter_lora_A = target.lora_A[adapter].weight + current_adapter_lora_B = target.lora_B[adapter].weight + elif adapter in target.lora_embedding_A: + current_adapter_lora_A = target.lora_embedding_A[adapter] + current_adapter_lora_B = target.lora_embedding_B[adapter] + else: + continue + # Support negative weights: take absolute value for sqrt, then apply sign + weight_with_scaling = weight * target.scaling[adapter] + sign = 1 if weight_with_scaling >= 0 else -1 + # apply sign only on one side of the weights, otherwise negative signs negate + valid_weights_A.append(math.sqrt(abs(weight_with_scaling)) * sign) + valid_weights_B.append(math.sqrt(abs(weight_with_scaling))) + lora_A_deltas.append(current_adapter_lora_A.data) + lora_B_deltas.append(current_adapter_lora_B.data) + valid_weights_A = torch.tensor(valid_weights_A).to(lora_A_deltas[0].device) + valid_weights_B = torch.tensor(valid_weights_B).to(lora_B_deltas[0].device) + valid_weights = [valid_weights_A, valid_weights_B] + lora_deltas = [lora_A_deltas, lora_B_deltas] + dtype = lora_A_deltas[0].dtype + for i, task_tensors in enumerate(lora_deltas): + if combination_type == "linear": + lora_deltas[i] = task_arithmetic(task_tensors, valid_weights[i]) + elif combination_type == "ties": + lora_deltas[i] = ties(task_tensors, valid_weights[i], density, majority_sign_method) + elif combination_type == "dare_linear": + lora_deltas[i] = dare_linear(task_tensors, valid_weights[i], density) + elif combination_type == "dare_ties": + lora_deltas[i] = dare_ties(task_tensors, valid_weights[i], density, majority_sign_method) + elif combination_type == "magnitude_prune": + lora_deltas[i] = magnitude_prune(task_tensors, valid_weights[i], density) + else: + raise ValueError("Invalid combination type") + lora_deltas = [delta.to(dtype) for delta in lora_deltas] + return lora_deltas + + def subtract_mutated_init(self, output_state_dict: dict[str, torch.Tensor], adapter_name: str, kwargs=None): + """ + This function can calculate the updates of the PiSSA/CorDA/OLoRA by comparing the parameters of the + PiSSA/CorDA/OLoRA adapter in `output_state_dict` with the initial values of PiSSA/CorDA/OLoRA in + `adapter_name`, thus converting PiSSA/CorDA/OLoRA to LoRA. + """ + for name, param in self.model.named_parameters(): + if ( + param.data.dtype != torch.float32 + and param.data.dtype != torch.float16 + and param.data.dtype != torch.bfloat16 + ) and adapter_name.startswith("pissa"): + warnings.warn( + r"Note that Quant(W_res) + AB != Quant(W) + \Delta(AB); " + "the converted LoRA, when combined with W or Quant(W), may introduce a certain gap in the fine-tuned model. " + "Therefore, we recommend directly using the Quant(W_res) in conjunction with the PiSSA adapter. " + ) + mutated_init_state_dict = get_peft_model_state_dict( + self, + state_dict=kwargs.get("state_dict", None), + adapter_name=adapter_name, + ) + tensors_lora = {} + for name in output_state_dict.keys(): + ## W = W^{res} + A_0 \times B_0, + ## W + \Delta W = W^{res} + A \times B, + ## \Delta W = A \times B - A_0 \times B_0 = [A | A_0] \times [B | -B_0]^T = A'B'. + if "lora_A" in name: + tensors_lora[name] = torch.cat( + [output_state_dict[name], mutated_init_state_dict[".".join(name.split(".")[1:])]], dim=0 + ) + elif "lora_B" in name: + tensors_lora[name] = torch.cat( + [output_state_dict[name], -mutated_init_state_dict[".".join(name.split(".")[1:])]], dim=1 + ) + + return tensors_lora + + def _get_monteclora_loss(self, adapter_names: Optional[Union[str, list[str]]] = None) -> torch.Tensor | float: + """ + Compute the MonteCLoRA variational regularization loss. + + Iterates over all `LoraLayer` modules in the model and, for each layer, collects the KL-divergence and entropy + components from the `MontecloraSampler`s that correspond to the requested adapters. The aggregated loss is + normalized by the number of contributing samplers. Returns `0.0` if no matching MonteCLoRA samplers are present + (e.g. MonteCLoRA is not used, or none of the requested adapters use MonteCLoRA). + + Only samplers belonging to `adapter_names` are considered. This matters when multiple LoRA adapters are + attached to the model but only a subset is active: the regularization loss is then computed only for those + adapters. By default (`adapter_names=None`) the model's currently active adapters are used. + + Typical usage during training (after computing the task loss): + + ```py + task_loss = ... # standard loss from the model + monteclora_loss = model._get_monteclora_loss() + total_loss = task_loss + monteclora_loss + ``` + + Args: + adapter_names (`str` or `list[str]`, *optional*): + Name(s) of the adapter(s) to include in the loss computation. If `None` (the default), the model's + currently active adapters (`self.active_adapters`) are used. + + Returns: + The normalized variational loss as a tensor (or `0.0` if no matching MonteCLoRA samplers are present). + """ + if adapter_names is None: + adapter_names = self.active_adapters + elif isinstance(adapter_names, str): + adapter_names = [adapter_names] + + var_loss_sum: torch.Tensor | float = 0.0 + num_monte_layers = 0 + for module in self.modules(): + if not isinstance(module, LoraLayer): + continue + samplers = getattr(module, "lora_monteclora_sampler", None) + if samplers is None: + continue + for adapter_name in adapter_names: + if adapter_name not in samplers: + continue + kl_loss, entropy_loss = samplers[adapter_name].get_variational_loss() + var_loss_sum = var_loss_sum + kl_loss + entropy_loss + num_monte_layers += 1 + + if num_monte_layers == 0: + return 0.0 + return var_loss_sum / num_monte_layers + + def _add_modules_to_save_to_tie(self, peft_config: LoraConfig, tied_weight_keys: list[str]): + """ + Add embedding layer to `modules_to_save` and remove rest of the tied layers from `module_to_save`. Maintain a + separate set for layers to be tied in `peft_config.tied_weights_keys`. + + Args: + peft_config (LoraConfig) -- The configuration of the Lora model. + tied_weight_keys (list[str]) -- Contains the layers tied to the embedding layer. + """ + tied_weight_keys = set(tied_weight_keys) + peft_config.modules_to_tie = tied_weight_keys + + modules_to_save = getattr(peft_config, "modules_to_save", []) or [] + embed_layer_name = find_parameter_name_by_module(self.model, self.model.get_input_embeddings()) + + # the layer may already be included but we assume that adding the same module twice is not a problem + if embed_layer_name not in modules_to_save: + modules_to_save.append(embed_layer_name) + + # Iterate over `tied_weight_keys` which are + # fully qualified keys and remove matching keys from + # `modules_to_save`. It will only remove first encounter + # in `module_to_save`, which should be safe, because `tied_weight_keys` + # is a unique set of keys. These keys are removed because all the + # tied keys are handled in a separate flow + # outside of the usual `modules_to_save` flow + # See: peft.utils.other.set_additional_trainable_modules for details + for key in tied_weight_keys: + for m in modules_to_save: + if re.match(rf"(^|.*\.){m}($|\..*)", key): + modules_to_save.remove(m) + break + + peft_config.modules_to_save = modules_to_save + + def _add_targets_to_tie(self, peft_config: LoraConfig, tied_weight_keys: list[str]): + """ + Add embedding layer to `target_modules` and remove rest of the tied layers from `target_modules`. Maintain a + separate set for layers to be tied in `peft_config.target_modules_to_tie` + + Args: + peft_config (LoraConfig) -- The configuration of the Lora model. + tied_weight_keys (list[str]) -- Contains the layers tied to the embedding layer. + """ + tied_weight_keys = set(tied_weight_keys) + peft_config.target_modules_to_tie = tied_weight_keys + + raw_target_modules = getattr(peft_config, "target_modules", None) + + embed_layer_name = find_parameter_name_by_module(self.model, self.model.get_input_embeddings()) + + if isinstance(raw_target_modules, str): + # The way weight tying is handled for adapters, we always want to add + # lora adapters to the input embedding layer (embed_tokens) + # instead of output embedding layer. + raw_target_modules = rf"(?:{raw_target_modules}|^{re.escape(embed_layer_name)}$)" + peft_config.target_modules = raw_target_modules + return + + target_modules = set(raw_target_modules or []) + target_modules.add(embed_layer_name) + + # Iterate over `tied_weight_keys` which are + # fully qualified keys and remove matching keys from + # `target_modules`. It will only remove first encounter + # in `target_modules`, which should be safe, because `tied_weight_keys` + # is a unique set of keys. These keys are removed because all the + # tied keys are handled in a separate flow + # outside of the usual `target_modules` flow + # See: peft.tuners.tuners_utils.BaseTuner.inject_adapter for details + for key in tied_weight_keys: + for m in target_modules: + if re.match(rf"(^|.*\.){m}($|\..*)", key): + target_modules.remove(m) + break + + peft_config.target_modules = target_modules diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/monteclora.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/monteclora.py new file mode 100644 index 0000000000000000000000000000000000000000..a0562ddbd83a64d84ad4e51552565c11e6f77f85 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/monteclora.py @@ -0,0 +1,238 @@ +# 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 typing import Optional + +import torch +from torch import nn +from torch.distributions.wishart import Wishart + +from peft.utils import infer_device + + +class BufferedMontecloraSampler: + """ + A buffered sampler for Monteclora that pre-generates samples to improve training efficiency. + """ + + def __init__(self, model: MontecloraSampler, buffer_size: int = 150, device: Optional[str] = None) -> None: + self.model = model + self.device = device if device is not None else infer_device() + self.buffer_size = buffer_size + self.buffer: list[dict[str, torch.Tensor]] = [] + self.index = 0 + + # Pre-create Wishart sampler. + # scale_tril must be a lower triangular matrix. + self.wish_sampler = Wishart( + df=self.model.out_features, scale_tril=torch.eye(self.model.out_features, device=self.device) + ) + + self._refill_buffer() + + def _refill_buffer(self) -> None: + """Generates a batch of samples to refill the internal buffer.""" + # Note: We generate on self.device (which might be CPU initially). + # We will cast to the correct accelerator in the forward pass of the main module. + sample_dtype = self.model.dtype + with torch.no_grad(): + z_mvn_bulk = torch.randn( + (self.buffer_size, self.model.num_samples, self.model.in_features, self.model.out_features), + device=self.device, + dtype=sample_dtype, + ) + + z_dirichlet_bulk = torch.randn( + (self.buffer_size, self.model.num_samples), device=self.device, dtype=sample_dtype + ) + + self.buffer = [] + for i in range(self.buffer_size): + # Wishart sampling is numerically unstable in low precision; sample in fp32 then cast. + z_wishart = self.wish_sampler._bartlett_sampling(torch.Size()).to(self.device) + if sample_dtype is not None: + z_wishart = z_wishart.to(sample_dtype) + + sample = {"z_mvn": z_mvn_bulk[i], "z_wishart": z_wishart, "z_dirichlet": z_dirichlet_bulk[i]} + self.buffer.append(sample) + + self.index = 0 + + def get(self) -> dict[str, torch.Tensor]: + """ + Retrieves a single sample set from the buffer. Refills buffer if empty. + """ + if self.index >= self.buffer_size: + self._refill_buffer() + + sample = self.buffer[self.index] + self.index += 1 + return sample + + +class MontecloraSampler(nn.Module): + """ + The main module responsible for maintaining the variational parameters. + """ + + def __init__( + self, + in_features: int, + out_features: int, + num_samples: int, + use_entropy: bool = True, + dirichlet_prior: float = 1.0, + sample_scaler: float = 3e-4, + kl_loss_weight: float = 1e-5, + buffer_size: int = 10, + device: Optional[str] = None, + dtype: Optional[torch.dtype] = None, + **kwargs, + ) -> None: + super().__init__() + self.in_features = in_features + self.out_features = out_features + self.num_samples = num_samples + self.use_entropy = use_entropy + # Initial device, might change if model.to() is called. + self.device = device if device is not None else infer_device() + self.dtype = dtype + self.sample_scaler = sample_scaler + self.kl_loss_weight = kl_loss_weight + self.dirichlet_prior = dirichlet_prior + + # Variational Parameters. The dtype is matched to the parent LoRA layer dtype so that PEFT's + # adapter dtype handling (e.g. `autocast_adapter_dtype`) treats these parameters consistently + # with the rest of the LoRA adapter. + self.std_prior = nn.Parameter(torch.rand(out_features, dtype=dtype)) + self.expert_weights_prior = nn.Parameter(torch.rand(num_samples, dtype=dtype)) + + # Buffers for state tracking + self.register_buffer("gaussian_var_prior", torch.eye(out_features, dtype=dtype)) + self.register_buffer("expert_weights", torch.ones(num_samples, dtype=dtype) / num_samples) + + self.sampler = BufferedMontecloraSampler(self, buffer_size=buffer_size, device=self.device) + + # Move to initial device + self.to(self.device) + + def wishart_reparameterization(self, std: torch.Tensor, z_wishart: torch.Tensor) -> torch.Tensor: + eps = 1e-3 + # z_wishart and std must be on the same device + updated_var = std @ z_wishart @ std.T + updated_var = torch.diag(torch.clip(updated_var.diag(), min=eps)) + return updated_var + + def multivariate_reparameterization(self, z_mvn: torch.Tensor, cov_matrix: torch.Tensor) -> torch.Tensor: + eps = 1e-3 + # Cholesky decomposition is numerically unstable in low precision (fp16/bf16) and can produce NaNs or + # negative-definite errors when autocast downcasts the inputs. We force the decomposition to run in fp32 + # and cast back to the original dtype afterwards. + with torch.amp.autocast("cuda", enabled=False): + L = torch.linalg.cholesky(cov_matrix.float()) + L = L.to(cov_matrix.dtype) + + varsum = torch.einsum("eio,op->eip", z_mvn, L) + varsum = torch.nan_to_num(varsum, nan=eps) + return self.sample_scaler * varsum + + def dirichlet_reparameterization(self, alpha: torch.Tensor, z_dirichlet: torch.Tensor) -> torch.Tensor: + eps = 1e-6 + alpha = torch.clamp(alpha, min=eps) + + mu = torch.log(alpha) - torch.log(alpha).mean() + # Dirichlet approximation via Normal distribution in log-space + diag_term = 1 / alpha * (1 - 2 / self.num_samples) + 1 / (self.num_samples**2) * (1 / alpha).sum() + diag_term = torch.clamp(diag_term, min=eps) + sigma = torch.diag(diag_term) + sigma = sigma + eps * torch.eye(len(alpha), device=self.expert_weights_prior.device) + + # As above, force Cholesky to run in fp32 to avoid NaNs / "matrix is not positive-definite" errors caused + # by autocast downcasting `sigma` to fp16/bf16. + with torch.amp.autocast("cuda", enabled=False): + try: + L = torch.linalg.cholesky(sigma.float()) + except torch.linalg.LinAlgError: + # Fallback for numerical stability + sigma = sigma + 1e-4 * torch.eye(len(alpha), device=self.expert_weights_prior.device) + L = torch.linalg.cholesky(sigma.float()) + + L = L.to(sigma.dtype) + return L @ z_dirichlet + mu + + def dirichlet_kl(self, alpha2: torch.Tensor) -> torch.Tensor: + current_device = self.expert_weights_prior.device + alpha1 = torch.tensor([self.dirichlet_prior] * self.num_samples, device=current_device) + + def custom_gamma(x: torch.Tensor) -> torch.Tensor: + return torch.lgamma(x).exp() + + return ( + torch.log(custom_gamma(alpha2.sum()) / custom_gamma(alpha1.sum())) + + (torch.log(custom_gamma(alpha2) / custom_gamma(alpha1))).sum() + + ((alpha2 - alpha1) * (torch.digamma(alpha2) - torch.digamma(alpha2.sum()))).sum() + ) + + def wishart_kl(self, std: torch.Tensor) -> torch.Tensor: + var = std @ std.T + var = torch.diag(var.diag()) + return 0.5 * ( + -torch.log(var).trace() * self.out_features + var.trace() * self.out_features - self.out_features**2 + ) + + def multivariate_kl(self, var: torch.Tensor) -> torch.Tensor: + var = torch.clamp(var, min=1e-6) + return self.num_samples * 0.5 * (var.trace() - torch.log(var).trace() - self.out_features) + + def get_variational_loss(self) -> tuple[torch.Tensor | float, torch.Tensor | float]: + """Calculates the KL divergence and entropy loss components.""" + if self.training: + kl1 = self.dirichlet_kl(torch.exp(self.expert_weights_prior)) + kl2 = self.wishart_kl(torch.diag(torch.exp(self.std_prior))) + kl3 = self.multivariate_kl(self.gaussian_var_prior) + entropy = (self.expert_weights**2).sum() if self.use_entropy else 0 + + return self.kl_loss_weight * (kl1 + kl2 + kl3), entropy + return 0.0, 0.0 + + def forward(self) -> tuple[torch.Tensor, torch.Tensor]: + """ + Returns: + tuple: (variational_noise, expert_weights) + """ + # Use std_prior (nn.Parameter) as the source of truth for the current device/dtype. + current_device = self.std_prior.device + current_dtype = self.std_prior.dtype + + sample = self.sampler.get() + z_mvn = sample["z_mvn"].to(device=current_device, dtype=current_dtype) + z_wishart = sample["z_wishart"].to(device=current_device, dtype=current_dtype) + z_dirichlet = sample["z_dirichlet"].to(device=current_device, dtype=current_dtype) + + std = torch.diag(torch.exp(self.std_prior)) + + gaussian_var = self.wishart_reparameterization(std, z_wishart) + + self.gaussian_var_prior = gaussian_var + + var = self.multivariate_reparameterization(z_mvn, gaussian_var) + + # Calculate Weights + expert_weights_logits = self.dirichlet_reparameterization(torch.exp(self.expert_weights_prior), z_dirichlet) + expert_weights = torch.softmax(expert_weights_logits, dim=-1) + self.expert_weights = expert_weights + + return var, self.expert_weights diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/te.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/te.py new file mode 100644 index 0000000000000000000000000000000000000000..22323ea9cdeca980e16986423b16fbef6eb6bf01 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/te.py @@ -0,0 +1,134 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: LicenseRef-Apache2 +# +# 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_te_pytorch_available +from peft.tuners.lora.layer import LoraLayer +from peft.tuners.tuners_utils import BaseTunerLayer + +from .config import LoraConfig + + +if is_te_pytorch_available(): + import transformer_engine as te + + +class TeLinear(torch.nn.Module, LoraLayer): + """LoRA layer for TransformerEngine linear modules. + + Supports ``te.pytorch.Linear``, ``te.pytorch.LayerNormLinear``, and ``te.pytorch.LayerNormMLP`` as base layers. + + Note: + Adapter weight merging (``merge`` / ``unmerge``) is **not supported** yet. + """ + + 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") + if config.velora_config is not None: + raise ValueError( + f"{self.__class__.__name__} does not support VeLoRA yet, please set `velora_config=None`." + ) + + super().__init__() + LoraLayer.__init__(self, base_layer=base_layer, **kwargs) + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + r, + lora_alpha=lora_alpha, + config=config, + ) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """Not supported yet for TransformerEngine layers. + + Raises: + NotImplementedError: Always. + """ + raise NotImplementedError(f"{self.__class__.__name__} does not support merge yet.") + + def unmerge(self) -> None: + """Not supported yet for TransformerEngine layers. + + Raises: + NotImplementedError: Always. + """ + raise NotImplementedError(f"{self.__class__.__name__} does not support unmerge yet.") + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + self._check_forward_args(x, *args, **kwargs) + adapter_names = kwargs.pop("adapter_names", None) + + if self.disable_adapters: + result = self.base_layer(x, *args, **kwargs) + elif adapter_names is not None: + raise ValueError(f"{self.__class__.__name__} does not support mixed_batch_forward yet.") + else: + result = self.base_layer(x, *args, **kwargs) + torch_result_dtype = result.dtype + + lora_A_keys = self.lora_A.keys() + for active_adapter in self.active_adapters: + if active_adapter not in 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] + x = self._cast_input_dtype(x, lora_A.weight.dtype) + result = result + lora_B(lora_A(dropout(x))) * scaling + + result = result.to(torch_result_dtype) + + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "lora." + rep + + +def dispatch_transformer_engine( + 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_te_pytorch_available() and isinstance( + target_base_layer, (te.pytorch.LayerNormLinear, te.pytorch.LayerNormMLP, te.pytorch.Linear) + ): + new_module = TeLinear(target, adapter_name, config=config, **kwargs) + + return new_module diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/torchao.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/torchao.py new file mode 100644 index 0000000000000000000000000000000000000000..9d09bffc03b25bb75f2730f85f4cabcbe3c52eea --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/torchao.py @@ -0,0 +1,168 @@ +# 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 warnings +from typing import Any, Optional + +import torch + +# from torch import nn +from peft.import_utils import is_torchao_available +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge + +from .config import LoraConfig +from .layer import Linear + + +class TorchaoLoraLinear(Linear): + """LoRA layer implementation for Linear layers using torchao data""" + + def __init__(self, *args, get_apply_tensor_subclass=None, **kwargs): + if kwargs["config"].lora_bias: + raise ValueError(f"{self.__class__.__name__} does not support lora_bias yet, set it to False") + + super().__init__(*args, **kwargs) + self.get_apply_tensor_subclass = get_apply_tensor_subclass + if get_apply_tensor_subclass is None: + warnings.warn( + f"{type(self).__name__} was instantiated without `get_apply_tensor_subclass`. " + "Forward and training will work, but `merge()` / `unmerge()` will raise an error. " + "To enable merging, load the base model via Transformers with a `TorchAoConfig` " + "(e.g. `AutoModelForCausalLM.from_pretrained(..., quantization_config=TorchAoConfig(quant_type=Int8WeightOnlyConfig()))`) " + "so PEFT can recover the requantization subclass automatically." + ) + self._check_dtype_supported() + + def _check_dtype_supported(self): + # TODO: Not required once int4_weight_only is properly supported by torchao + from torchao.quantization import Int4Tensor + + base_layer = self.get_base_layer() + weight = base_layer.weight + if isinstance(weight, Int4Tensor): + raise TypeError(f"{type(self).__name__} only supports int8 weights for now.") + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + from torchao import quantize_ + + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + if self.get_apply_tensor_subclass is None: + raise ValueError( + f"{type(self).__name__} was instantiated without `get_apply_tensor_subclass`, which is " + "required to re-quantize the base layer after merging." + ) + + self._check_dtype_supported() + + base_layer = self.get_base_layer() + weight = base_layer.weight + + for active_adapter in adapter_names: + try: + weight = weight.dequantize() + except NotImplementedError as exc: + msg = ( + f"Weights of type {type(weight).__name__} do not support dequantization (yet), which is needed to " + "support merging." + ) + raise NotImplementedError(msg) from exc + + if safe_merge and not torch.isfinite(weight).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + weight += self.get_delta_weight(active_adapter) + # TODO: once (if) torchao supports directly mutating the data, use that instead. + del base_layer.weight + base_layer.weight = weight + quantize_(base_layer, self.get_apply_tensor_subclass()) + del weight + + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + from torchao import quantize_ + + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + if self.get_apply_tensor_subclass is None: + raise ValueError( + f"{type(self).__name__} was instantiated without `get_apply_tensor_subclass`, which is " + "required to re-quantize the base layer after unmerging." + ) + + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter not in self.lora_A.keys(): + continue + + base_layer = self.get_base_layer() + weight = base_layer.weight + try: + weight = weight.dequantize() + except NotImplementedError as exc: + msg = ( + f"Weights of type {type(weight).__name__} do not support dequantization (yet), which is needed to " + "support unmerging." + ) + raise NotImplementedError(msg) from exc + + weight -= self.get_delta_weight(active_adapter) + # We go through a dummy module because overriding the weight.data does not work, the tensor retains the old + # data. Therefore, we need to go through quantize_, which takes a module as input, and we need to delete and + # re-assign the weight. + # TODO: once (if) torchao supports directly mutating the data, use that instead. + del base_layer.weight + base_layer.weight = weight + quantize_(base_layer, self.get_apply_tensor_subclass()) + del weight + + def __repr__(self) -> str: + rep = super().__repr__() + return rep.replace("lora.Linear", f"lora.{self.__class__.__name__}") + + +def dispatch_torchao( + 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 not hasattr(target_base_layer, "weight"): + return new_module + + if not is_torchao_available(): + return new_module + + from torchao.utils import TorchAOBaseTensor + + if isinstance(target_base_layer.weight, TorchAOBaseTensor): + new_module = TorchaoLoraLinear(target, adapter_name, config=config, **kwargs) + + return new_module diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/tp_layer.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/tp_layer.py new file mode 100644 index 0000000000000000000000000000000000000000..c68988c7185798e6c9ac8f337ba77fc7a1495b1f --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/tp_layer.py @@ -0,0 +1,362 @@ +# 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 importlib +import math +import warnings +from typing import Any, Optional + +import torch +from torch import nn +from torch.nn import init + +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge +from peft.utils import transpose +from peft.utils.integrations import gather_params_ctx + +from .config import LoraConfig +from .layer import LoraLayer + + +def get_default_module_allowlist(): + """Allowed module names that config.megatron_core can reference for import""" + return [ + "megatron", + ] + + +class LoraParallelLinear(nn.Module, LoraLayer): + """ + When the target layer parallel_linear is RowParallelLinear, in order to keep the input and output shapes + consistent, we need to split the lora matrix A into rows, and the lora_B at this time should be a complete linear + layer; In the same way, when the target layer is ColumnParallelLinear, we perform column segmentation on lora_B, + while lora_A is still a complete linear layer. + """ + + def __init__( + self, + base_layer, + adapter_name: str, + config: LoraConfig, + backend, + r: int = 0, + lora_alpha: int = 1, + is_target_conv_1d_layer: bool = False, + **kwargs, + ): + 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=base_layer, **kwargs) + + if config.use_dora: + raise ValueError(f"{self.__class__.__name__} does not support DoRA yet, please set it to False") + if config.velora_config is not None: + raise ValueError( + f"{self.__class__.__name__} does not support VeLoRA yet, please set `velora_config=None`." + ) + + self.backend = backend + self.is_parallel_a = isinstance(base_layer, backend.RowParallelLinear) + self.fan_in_fan_out = config.fan_in_fan_out + self._active_adapter = adapter_name + + megatron_config = kwargs["megatron_config"] + parallel_linear_kwargs = {"megatron_config": megatron_config} + init_method = init.xavier_normal_ + if hasattr(megatron_config, "init_method"): + init_method = megatron_config.init_method + input_is_parallel = True + gather_output = False + if self.is_parallel_a: + input_is_parallel = base_layer.input_is_parallel + else: + gather_output = base_layer.gather_output + self.update_layer( + adapter_name, + r, + lora_alpha=lora_alpha, + config=config, + init_method=init_method, + input_is_parallel=input_is_parallel, + gather_output=gather_output, + **parallel_linear_kwargs, + ) + + if is_target_conv_1d_layer: + raise ValueError( + f"{self.__class__.__name__} does not support target_conv_1d_layer yet, please set it to False" + ) + self.is_target_conv_1d_layer = False + + def update_layer( + self, + adapter_name: str, + r: int, + lora_alpha: int, + config: LoraConfig, + init_method=init.xavier_normal_, + input_is_parallel: bool = True, + gather_output: bool = False, + inference_mode: bool = False, + **parallel_linear_kwargs, + ) -> None: + lora_dropout = config.lora_dropout + init_lora_weights = config.init_lora_weights + use_rslora = config.use_rslora + use_dora = config.use_dora + + 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.lora_alpha[adapter_name] = lora_alpha + if lora_dropout > 0.0: + lora_dropout_layer = nn.Dropout(p=lora_dropout) + else: + lora_dropout_layer = nn.Identity() + + self.lora_dropout[adapter_name] = lora_dropout_layer + + megatron_config = parallel_linear_kwargs["megatron_config"] + # lora needs to be forced to upgrade to 32-bit precision, otherwise it will overflow + megatron_config.params_dtype = torch.float32 + if self.is_parallel_a: + lora_a = self.backend.RowParallelLinear( + input_size=self.in_features, + output_size=r, + bias=False, + input_is_parallel=input_is_parallel, + skip_bias_add=True, + init_method=init_method, + config=megatron_config, + ) + lora_b = nn.Linear(in_features=r, out_features=self.out_features, bias=False, dtype=torch.float32) + else: + lora_a = nn.Linear(in_features=self.in_features, out_features=r, bias=False, dtype=torch.float32) + lora_b = self.backend.ColumnParallelLinear( + input_size=r, + output_size=self.out_features, + bias=False, + gather_output=gather_output, + init_method=init_method, + config=megatron_config, + ) + self.lora_A[adapter_name] = lora_a + self.lora_B[adapter_name] = lora_b + if use_rslora: + self.scaling[adapter_name] = lora_alpha / math.sqrt(r) + else: + self.scaling[adapter_name] = lora_alpha / r + + self.use_dora[adapter_name] = use_dora + + # for inits that require access to the base weight, use gather_param_ctx so that the weight is gathered when using DeepSpeed + if isinstance(init_lora_weights, str) and init_lora_weights.startswith("pissa"): + with gather_params_ctx(self.get_base_layer().weight): + self.pissa_init(adapter_name, init_lora_weights) + elif isinstance(init_lora_weights, str) and init_lora_weights.startswith("corda"): + with gather_params_ctx(self.get_base_layer().weight): + self.corda_init(adapter_name, init_lora_weights) + elif isinstance(init_lora_weights, str) and init_lora_weights.lower() == "olora": + with gather_params_ctx(self.get_base_layer().weight): + self.olora_init(adapter_name) + elif init_lora_weights == "loftq": + with gather_params_ctx(self.get_base_layer().weight): + self.loftq_init(adapter_name) + elif init_lora_weights: + self.reset_lora_parameters(adapter_name, init_lora_weights) + + # call this before dora_init + self._move_adapter_to_device_of_base_layer(adapter_name) + + if adapter_name in self.lora_variant: + self.lora_variant[adapter_name].init(self, adapter_name=adapter_name, config=config) + + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any): + self._check_forward_args(x, *args, **kwargs) + adapter_names = kwargs.pop("adapter_names", None) + # If weight is used for matrix multiplication here, the final aggregation operation of the original + # parallel_linear layer will be missing, so we need to directly call its forward function to obtain the + # output of the original parallel_linear layer. + if self.disable_adapters: + if self.merged: + self.unmerge() + result, bias = self.base_layer(x, *args, **kwargs) + elif adapter_names is not None: + raise ValueError(f"{self.__class__.__name__} does not support mixed_batch_forward yet.") + elif self.merged: + result, bias = self.base_layer(x, *args, **kwargs) + else: + result, bias = self.base_layer(x, *args, **kwargs) + torch_result_dtype = result.dtype + 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] + x = self._cast_input_dtype(x, lora_A.weight.dtype) + result = result + lora_B(lora_A(dropout(x))) * scaling + + result = result.to(torch_result_dtype) + return result, bias + + 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.lora_A.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() + delta_weight = self.get_delta_weight(active_adapter) + orig_weights = orig_weights + delta_weight + + 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: + delta_weight = self.get_delta_weight(active_adapter) + base_layer.weight.data = base_layer.weight.data + delta_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 + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter in self.lora_A.keys(): + weight = self.get_base_layer().weight + delta_weight = self.get_delta_weight(active_adapter) + weight.data -= delta_weight + + 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.lora_B[adapter].weight.device + dtype = self.lora_B[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) + + weight_A = self.lora_A[adapter].weight + weight_B = self.lora_B[adapter].weight + + if cast_to_fp32: + weight_A = weight_A.float() + weight_B = weight_B.float() + + output_tensor = transpose(weight_B @ weight_A, self.fan_in_fan_out) * self.scaling[adapter] + + if cast_to_fp32: + output_tensor = output_tensor.to(dtype=dtype) + + # cast back the weights + self.lora_A[adapter].weight.data = weight_A.to(dtype) + self.lora_B[adapter].weight.data = weight_B.to(dtype) + + return output_tensor + + def __repr__(self) -> str: + rep = super().__repr__() + return "lora." + rep + + +def dispatch_megatron( + 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 config.megatron_config: + if not any(config.megatron_core.startswith(f"{prefix}.") for prefix in get_default_module_allowlist()): + raise ValueError( + f"{config.megatron_core=} does not start with a valid prefix ({get_default_module_allowlist()}) " + "which is unsupported due to being a potential security risk. If you think it should be supported, " + "please raise an issue in PEFT." + ) + megatron_core = importlib.import_module(config.megatron_core) + else: + megatron_core = None + + if megatron_core and isinstance( + target_base_layer, + (megatron_core.tensor_parallel.ColumnParallelLinear, megatron_core.tensor_parallel.RowParallelLinear), + ): + megatron_kwargs = kwargs.copy() + megatron_config = config.megatron_config + if isinstance(megatron_config, dict): + transformer_config_class = megatron_core.transformer.transformer_config.TransformerConfig + megatron_config = transformer_config_class(**config.megatron_config) + megatron_kwargs["megatron_config"] = megatron_config + if megatron_kwargs["fan_in_fan_out"]: + warnings.warn( + "fan_in_fan_out is set to True but the target module is `ColumnParallelLinear` " + "or `RowParallelLinear`. " + "Setting fan_in_fan_out to False." + ) + megatron_kwargs["fan_in_fan_out"] = config.fan_in_fan_out = False + new_module = LoraParallelLinear( + base_layer=target, + adapter_name=adapter_name, + config=config, + backend=megatron_core.tensor_parallel, + **megatron_kwargs, + ) + + return new_module diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/variants.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/variants.py new file mode 100644 index 0000000000000000000000000000000000000000..43e465e64267cec0c59884605e95ed8bf6958267 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/variants.py @@ -0,0 +1,1218 @@ +# 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 collections +import warnings +from typing import Any, Optional + +import torch +import torch.nn.functional as F +from accelerate.utils.imports import is_xpu_available +from torch import nn + +from peft.tuners._buffer_dict import BufferDict +from peft.tuners.lora.config import BdLoraConfig, MontecloraConfig +from peft.utils.other import transpose + +from .arrow import ArrowLoraLinearLayer +from .config import LoraConfig, PeftConfig +from .dora import DoraConv1dLayer, DoraConv2dLayer, DoraConv3dLayer, DoraEmbeddingLayer, DoraLinearLayer +from .layer import Conv1d, Conv2d, Conv3d, Embedding, Linear, LoraVariant, _ConvNd +from .monteclora import MontecloraSampler +from .velora import VeloraFunction, _get_group_dim, _normalize_projection, _reshape_to_grouped_subtokens + + +class ArrowLinearVariant(LoraVariant): + @staticmethod + def init(module: Linear, adapter_name: str, config: LoraConfig, **kwargs): + """ + Initialise the ArrowLoraLinearLayer() inside lora_arrow. lora_arrow is nn.ModuleDict(), serving as a container + for ArrowLoraLinearLayer(). A layer of the base model with LoRA adapter loaded on it will be like: + ---------------------------------------------------- + (qkv_proj): lora.Linear4bit or lora.Linear( + (base_layer): Linear4bit or Linear (lora_dropout): ModuleDict( ... ) (lora_A): ModuleDict( ... ) + (lora_B): ModuleDict( ... ) (lora_embedding_A): ParameterDict( ... ) (lora_embedding_B): ParameterDict( + ... ) (lora_magnitude_vector): ModuleDict( ... ) (lora_arrow): ModuleDict( + (arrow_router): ArrowLoraLinearLayer() ) + ) + ---------------------------------------------------- + + Args: + module (Linear): LoRA Layer of the model, containing base_layer, lora_A, lora_B, etc. + adapter_name (str): name of the adapter that will be put in lora_arrow. + The adapter_name is "arrow_router" by default, set in create_arrow_model() in ./arrow.py + """ + # Checking for arrow necessary config + arrow_config = config.arrow_config + if arrow_config is None: + raise ValueError("ArrowLinearVariant.init() did not receive an arrow_config") + + # 1-a) build the ArrowLoRALayer + arrow_layer = ArrowLoraLinearLayer( + in_features=module.in_features, + arrow_config=arrow_config, + ).to(module.weight.device) + + # 1-b) register a container if it doesn’t exist yet + if not hasattr(module, "lora_arrow"): + module.lora_arrow = nn.ModuleDict() + + module.lora_arrow[adapter_name] = arrow_layer + + @staticmethod + def forward( + module: Linear, + *, + active_adapter: str, + x: torch.Tensor, + result: torch.Tensor, + **kwargs, + ) -> torch.Tensor: + """ + Parameters mirror those in PEFT’s `LoraVariant.forward`. Called every time the host Linear does a fwd pass. + + build_prototypes() and gen_know_sub() should run only once before routing. Both are implemented in + ArrowLoraLinearLayer (see ./arrow.py). They are lazily invoked in the forward pass below. Attributes of + ArrowLoraLinearLayer() class ensure they execute only a single time. + + Args: + module (Linear): LoRA Layer of the model + active_adapter (str): name of the arrow route, which should be active to perform arrow. + x (torch.Tensor): input to the layer + result (torch.Tensor): output of the base layer. + + Return value: + output of the base model + delta weight computed by arrow layer. + """ + arrow = module.lora_arrow[active_adapter] # ArrowLoraLinearLayer + # Apply GenKnowSub the 1st time if applcable. By calling arrow/on_adapter_change(), + # gen_know_sub() is redone for newly added adapters after arrow.create_arrow_model(). + arrow.gen_know_sub(module.lora_A, module.lora_B) + # lazily build prototypes the 1st time after GenKnowSub. By calling arrow/on_adapter_change(), + # build_prototypes() is redone for newly added adapters after arrow.create_arrow_model(). + arrow.build_prototypes(module.lora_A, module.lora_B) + + # A forward path of ArrowLoraLinearLayer is called so routing performs. + # Accept and ignore extra variant kwargs (e.g., 'alora_offsets') for compatibility + delta = arrow( + x, + lora_A=module.lora_A, + lora_B=module.lora_B, + dropout=module.lora_dropout[active_adapter], + scaling=module.scaling, + ) + return result + delta + + """ + Since Arrow is a Mixture-of-Experts (MoE) approach, merging adapters is not meaningful or even possible: for each + token, the top-k LoRA experts are dynamically selected and routed. Because of this per-token routing, there is no + single set of weights that can represent a merged adapter. + """ + + @staticmethod + def merge_safe(module: Linear, active_adapter: str, orig_weight: torch.Tensor) -> torch.Tensor: + raise RuntimeError("Cannot merge an active Arrow router adapter. Remove it first.") + + @staticmethod + def merge_unsafe(module: Linear, active_adapter: str, orig_weight: torch.Tensor) -> None: + raise RuntimeError("Cannot merge an active Arrow router adapter. Remove it first.") + + @staticmethod + def unmerge(module: Linear, active_adapter: str, orig_weight: torch.Tensor) -> torch.Tensor: + raise RuntimeError("Cannot unmerge an active Arrow router adapter. Remove it first.") + + +class DoraLinearVariant(LoraVariant): + @staticmethod + def init(module: Linear, adapter_name: str, **kwargs: Any) -> None: + if not module.lora_magnitude_vector: + # first dora layer being added, add lora_magnitude_vector to the list of learnable parameters + module.adapter_layer_names = module.adapter_layer_names[:] + ("lora_magnitude_vector",) + + dora_layer = DoraLinearLayer(fan_in_fan_out=getattr(module, "fan_in_fan_out", False)) + lora_A = module.lora_A[adapter_name].weight + lora_B = module.lora_B[adapter_name].weight + place_on_cpu = module.ephemeral_gpu_offload and (lora_A.device.type == "cpu" or lora_B.device.type == "cpu") + if module.ephemeral_gpu_offload: + if lora_A.device.type in ["cuda", "xpu"]: + lora_B = lora_B.to(lora_A.device) + else: + if lora_B.device.type not in ["cuda", "xpu"]: + if is_xpu_available(): + lora_B = lora_B.to("xpu") + else: + lora_B = lora_B.to("cuda") + lora_A = lora_A.to(lora_B.device) + scaling = module.scaling[adapter_name] + dora_layer.update_layer( + base_layer=module.get_base_layer(), + lora_A=lora_A, + lora_B=lora_B, + scaling=scaling, + place_on_cpu=place_on_cpu, + ) + module.lora_magnitude_vector[adapter_name] = dora_layer + + @staticmethod + def merge_safe(module: Linear, active_adapter: str, orig_weight: torch.Tensor) -> torch.Tensor: + orig_dtype = orig_weight.dtype + delta_weight = module.get_delta_weight(active_adapter) + + # since delta_weight already includes scaling, set it to 1 here + weight_norm = ( + module.lora_magnitude_vector[active_adapter] + .get_weight_norm(orig_weight, transpose(delta_weight, module.fan_in_fan_out), scaling=1) + .detach() + ) + # We need to cache weight_norm because it has to be based on the original weights. We + # cannot calculate it on the fly based on the merged weights when unmerging because its a + # different value + module._cache_store(f"{active_adapter}-weight_norm", weight_norm) + dora_factor = module.lora_magnitude_vector[active_adapter].weight / weight_norm + dora_factor = transpose(dora_factor.view(-1, 1), module.fan_in_fan_out) + new_weight = dora_factor * (orig_weight + delta_weight) + new_weight = new_weight.to(orig_dtype) + return new_weight + + @staticmethod + def merge_unsafe(module: Linear, active_adapter: str, orig_weight: torch.Tensor) -> None: + orig_dtype = orig_weight.dtype + delta_weight = module.get_delta_weight(active_adapter) + weight_norm = ( + module.lora_magnitude_vector[active_adapter] + .get_weight_norm(orig_weight, transpose(delta_weight, module.fan_in_fan_out), scaling=1) + .detach() + ) + # We need to cache weight_norm because it has to be based on the original weights. We + # cannot calculate it on the fly based on the merged weights when unmerging because its a + # different value + module._cache_store(f"{active_adapter}-weight_norm", weight_norm) + dora_factor = module.lora_magnitude_vector[active_adapter].weight / weight_norm + dora_factor = transpose(dora_factor.view(-1, 1), module.fan_in_fan_out) + new_weight = dora_factor * (orig_weight.data + delta_weight) + new_weight = new_weight.to(orig_dtype) + orig_weight.data = new_weight + + @staticmethod + def unmerge(module: Linear, active_adapter: str, orig_weight: torch.Tensor) -> torch.Tensor: + orig_dtype = orig_weight.dtype + delta_weight = module.get_delta_weight(active_adapter) + weight_norm = module._cache_pop(f"{active_adapter}-weight_norm") + dora_factor = module.lora_magnitude_vector[active_adapter].weight / weight_norm + new_weight = orig_weight.data / dora_factor.view(-1, 1) - delta_weight + new_weight = new_weight.to(orig_dtype) + return new_weight + + @staticmethod + def forward( + module: Linear, + active_adapter: str, + x: torch.Tensor, + result: torch.Tensor, + **kwargs, + ) -> torch.Tensor: + lora_A = module.lora_A[active_adapter] + lora_B = module.lora_B[active_adapter] + dropout = module.lora_dropout[active_adapter] + scaling = module.scaling[active_adapter] + + if isinstance(dropout, nn.Identity) or not module.training: + base_result = result + else: + x = dropout(x) + base_result = None + + result = result + module.lora_magnitude_vector[active_adapter]( + x, + lora_A=lora_A, + lora_B=lora_B, + scaling=scaling, + base_layer=module.get_base_layer(), + base_result=base_result, + adapter_name=active_adapter, + ) + return result + + +class DoraEmbeddingVariant(DoraLinearVariant): + @staticmethod + def init(module: Embedding, adapter_name: str, **kwargs: Any) -> None: + if module.lora_magnitude_vector is None: + # first dora layer being added, add lora_magnitude_vector to the list of learnable parameters + module.adapter_layer_names = module.adapter_layer_names[:] + ("lora_magnitude_vector",) + + dora_layer = DoraEmbeddingLayer(fan_in_fan_out=True) + lora_embedding_A = module.lora_embedding_A[adapter_name] + lora_embedding_B = module.lora_embedding_B[adapter_name] + scaling = module.scaling[adapter_name] + dora_layer.update_layer( + base_layer=module.get_base_layer(), lora_A=lora_embedding_A, lora_B=lora_embedding_B, scaling=scaling + ) + module.lora_magnitude_vector[adapter_name] = dora_layer + + @staticmethod + def merge_safe(module: Embedding, active_adapter: str, orig_weight: torch.Tensor) -> torch.Tensor: + orig_dtype = orig_weight.dtype + delta_weight = module.get_delta_weight(active_adapter) + + # since delta_weight already includes scaling, set it to 1 here + weight_norm = ( + module.lora_magnitude_vector[active_adapter] + .get_weight_norm(orig_weight, delta_weight.T, scaling=1) + .detach() + ) + # We need to cache weight_norm because it has to be based on the original weights. We + # cannot calculate it on the fly based on the merged weights when unmerging because its a + # different value + module._cache_store(f"{active_adapter}-weight_norm", weight_norm) + dora_factor = module.lora_magnitude_vector[active_adapter].weight / weight_norm + dora_factor = dora_factor.view(1, -1) + new_weight = dora_factor * (orig_weight + delta_weight) + new_weight = new_weight.to(orig_dtype) + return new_weight + + @staticmethod + def merge_unsafe(module: Embedding, active_adapter: str, orig_weight: torch.Tensor) -> None: + orig_dtype = orig_weight.dtype + delta_weight = module.get_delta_weight(active_adapter) + weight_norm = ( + module.lora_magnitude_vector[active_adapter] + .get_weight_norm(orig_weight, delta_weight.T, scaling=1) + .detach() + ) + # We need to cache weight_norm because it has to be based on the original weights. We + # cannot calculate it on the fly based on the merged weights when unmerging because its a + # different value + module._cache_store(f"{active_adapter}-weight_norm", weight_norm) + dora_factor = module.lora_magnitude_vector[active_adapter].weight / weight_norm + dora_factor = dora_factor.view(1, -1) + new_weight = dora_factor * (orig_weight.data + delta_weight) + new_weight = new_weight.to(orig_dtype) + orig_weight.data = new_weight + + @staticmethod + def unmerge(module: Embedding, active_adapter: str, orig_weight: torch.Tensor) -> torch.Tensor: + orig_dtype = orig_weight.dtype + delta_weight = module.get_delta_weight(active_adapter) + weight_norm = module._cache_pop(f"{active_adapter}-weight_norm") + dora_factor = module.lora_magnitude_vector[active_adapter].weight / weight_norm + new_weight = orig_weight.data / dora_factor.view(1, -1) - delta_weight + new_weight = new_weight.to(orig_dtype) + return new_weight + + @staticmethod + def forward( + module: Embedding, + active_adapter: str, + x: torch.Tensor, + result: torch.Tensor, + **kwargs, + ) -> torch.Tensor: + embedding_A = module.lora_embedding_A[active_adapter].T + embedding_B = module.lora_embedding_B[active_adapter].T + scaling = module.scaling[active_adapter] + + mag_norm_scale, dora_result = module.lora_magnitude_vector[active_adapter]( + x, + lora_A=embedding_A, + lora_B=embedding_B, + scaling=scaling, + base_layer=module.get_base_layer(), + embed_fn=module._embed, + adapter_name=active_adapter, + ) + + # Some embedding layers (e.g., Gemma3TextScaledWordEmbedding) apply scaling in their forward method. + # Since base_layer(x) already includes this scaling, we need to apply it to DoRA contributions too. + # Note: embed_scale is applied AFTER weight norm calculation to preserve DoRA's weight geometry semantics. + embed_scale = module._get_embed_scale() + if embed_scale is not None: + dora_result = dora_result * embed_scale.to(dora_result.dtype) + + result = mag_norm_scale * result + dora_result + return result + + +class _DoraConvNdVariant(LoraVariant): + @staticmethod + def init_convd_variant(module: _ConvNd, adapter_name: str, dora_layer: nn.Module) -> None: + if module.lora_magnitude_vector is None: + # first dora layer being added, add lora_magnitude_vector to the list of learnable parameters + module.adapter_layer_names = module.adapter_layer_names[:] + ("lora_magnitude_vector",) + + lora_A = module.lora_A[adapter_name].weight + lora_B = module.lora_B[adapter_name].weight + scaling = module.scaling[adapter_name] + dora_layer.update_layer(base_layer=module.get_base_layer(), lora_A=lora_A, lora_B=lora_B, scaling=scaling) + module.lora_magnitude_vector[adapter_name] = dora_layer + + @staticmethod + def merge_safe(module: _ConvNd, active_adapter: str, orig_weight: torch.Tensor) -> torch.Tensor: + orig_dtype = orig_weight.dtype + delta_weight = module.get_delta_weight(active_adapter) + + # since delta_weight already includes scaling, set it to 1 here + weight_norm = ( + module.lora_magnitude_vector[active_adapter].get_weight_norm(orig_weight, delta_weight, scaling=1).detach() + ) + # We need to cache weight_norm because it has to be based on the original weights. We + # cannot calculate it on the fly based on the merged weights when unmerging because its a + # different value + module._cache_store(f"{active_adapter}-weight_norm", weight_norm) + dora_factor = module.lora_magnitude_vector[active_adapter].weight / weight_norm + new_weight = dora_factor.view(*module._get_dora_factor_view()) * (orig_weight + delta_weight) + new_weight = new_weight.to(orig_dtype) + return new_weight + + @staticmethod + def merge_unsafe(module: _ConvNd, active_adapter: str, orig_weight: torch.Tensor) -> None: + orig_dtype = orig_weight.dtype + delta_weight = module.get_delta_weight(active_adapter) + # since delta_weight already includes scaling, set it to 1 here + weight_norm = ( + module.lora_magnitude_vector[active_adapter].get_weight_norm(orig_weight, delta_weight, scaling=1).detach() + ) + # We need to cache weight_norm because it has to be based on the original weights. We + # cannot calculate it on the fly based on the merged weights when unmerging because its a + # different value + module._cache_store(f"{active_adapter}-weight_norm", weight_norm) + dora_factor = module.lora_magnitude_vector[active_adapter].weight / weight_norm + new_weight = dora_factor.view(*module._get_dora_factor_view()) * (orig_weight.data + delta_weight) + new_weight = new_weight.to(orig_dtype) + orig_weight.data = new_weight + + @staticmethod + def unmerge(module: _ConvNd, active_adapter: str, orig_weight: torch.Tensor) -> torch.Tensor: + orig_dtype = orig_weight.dtype + delta_weight = module.get_delta_weight(active_adapter) + weight_norm = module._cache_pop(f"{active_adapter}-weight_norm") + dora_factor = module.lora_magnitude_vector[active_adapter].weight / weight_norm + new_weight = orig_weight.data / dora_factor.view(*module._get_dora_factor_view()) - delta_weight + new_weight = new_weight.to(orig_dtype) + return new_weight + + @staticmethod + def forward( + module: _ConvNd, + active_adapter: str, + x: torch.Tensor, + result: torch.Tensor, + **kwargs, + ) -> torch.Tensor: + lora_A = module.lora_A[active_adapter] + lora_B = module.lora_B[active_adapter] + dropout = module.lora_dropout[active_adapter] + scaling = module.scaling[active_adapter] + + if isinstance(dropout, nn.Identity) or not module.training: + base_result = result + else: + x = dropout(x) + base_result = None + + result = result + module.lora_magnitude_vector[active_adapter]( + x, + lora_A=lora_A, + lora_B=lora_B, + scaling=scaling, + base_layer=module.get_base_layer(), + base_result=base_result, + adapter_name=active_adapter, + ) + return result + + +class DoraConv1dVariant(_DoraConvNdVariant): + @staticmethod + def init(module: Conv1d, adapter_name: str, config: LoraConfig, **kwargs: Any) -> None: + dora_layer = DoraConv1dLayer(fan_in_fan_out=False) + _DoraConvNdVariant.init_convd_variant(module, adapter_name, dora_layer=dora_layer) + + +class DoraConv2dVariant(_DoraConvNdVariant): + @staticmethod + def init(module: Conv2d, adapter_name: str, config: LoraConfig, **kwargs: Any) -> None: + dora_layer = DoraConv2dLayer(fan_in_fan_out=False) + _DoraConvNdVariant.init_convd_variant(module, adapter_name, dora_layer=dora_layer) + + +class DoraConv3dVariant(_DoraConvNdVariant): + @staticmethod + def init(module: Conv3d, adapter_name: str, config: LoraConfig, **kwargs: Any) -> None: + dora_layer = DoraConv3dLayer(fan_in_fan_out=False) + _DoraConvNdVariant.init_convd_variant(module, adapter_name, dora_layer=dora_layer) + + +class QALoraLinearVariant(LoraVariant): + @staticmethod + def init(module: Linear, adapter_name: str, config: LoraConfig, **kwargs: Any) -> None: + """ + Initializes QALoRA specific parameters for a given adapter. + + Args: + module (Linear): The linear module to be adapted. + adapter_name (str): The name of the adapter. + config (LoraConfig): The config of the LoRA adapter. + **kwargs: Additional keyword arguments. + """ + qalora_group_size = config.qalora_group_size + if module.in_features is not None and module.in_features % qalora_group_size != 0: + raise ValueError( + f"`use_qalora=True` requires `module.in_features` ({module.in_features}) to be" + f"divisible by 'qalora_group_size' ({qalora_group_size})" + ) + + if "qalora_group_size" not in module.other_param_names: + module.other_param_names = module.other_param_names + ("qalora_group_size",) + + if not hasattr(module, "qalora_group_size"): + module.qalora_group_size = {} + module.qalora_group_size[adapter_name] = qalora_group_size + + old_lora_A_layer = module.lora_A[adapter_name] + r = old_lora_A_layer.out_features + device = old_lora_A_layer.weight.device + dtype = old_lora_A_layer.weight.dtype + + new_lora_A_layer = nn.Linear( + old_lora_A_layer.in_features // module.qalora_group_size[adapter_name], + r, + bias=False, + device=device, + dtype=dtype, + ) + module.lora_A[adapter_name] = new_lora_A_layer + + @staticmethod + def get_delta_weight(module: Linear, active_adapter: str) -> torch.Tensor: + raise NotImplementedError("QALoRA for GPTQ layers does not support 'get_delta_weight'.") + + @staticmethod + def merge_safe(module: Linear, active_adapter: str, orig_weight: torch.Tensor) -> torch.Tensor: + raise NotImplementedError("QALoRA for GPTQ layers does not support 'safe_merge'.") + + @staticmethod + def merge_unsafe(module: Linear, active_adapter: str, orig_weight: torch.Tensor) -> None: + raise NotImplementedError("QALoRA for GPTQ layers does not support 'merge_unsafe'.") + + @staticmethod + def unmerge(module: Linear, active_adapter: str, orig_weight: torch.Tensor) -> torch.Tensor: + raise NotImplementedError("QALoRA for GPTQ layers does not support 'unmerge'.") + + @staticmethod + def forward( + module: Linear, + active_adapter: str, + x: torch.Tensor, + result: torch.Tensor, + **kwargs, + ) -> torch.Tensor: + lora_A_weight = module.lora_A[active_adapter].weight + lora_B_weight = module.lora_B[active_adapter].weight + dropout = module.lora_dropout[active_adapter] + scaling = module.scaling[active_adapter] + group_size = module.qalora_group_size[active_adapter] + + x_dropped = dropout(x) if module.training and not isinstance(dropout, nn.Identity) else x + orig_shape = x_dropped.shape + + # Reshape to 2D + if len(orig_shape) > 2: + x_flat = x_dropped.view(-1, module.in_features) + else: + x_flat = x_dropped + + batch_size, in_features = x_flat.shape + pooled_features = in_features // group_size + + x_pooled = x_flat.view(batch_size, pooled_features, group_size).mean(dim=2) + + x_pooled_scaled = x_pooled * pooled_features + + # LoRA computation + delta = x_pooled_scaled @ lora_A_weight.t() @ lora_B_weight.t() * scaling + + # Reshape back + if len(orig_shape) > 2: + delta = delta.view(orig_shape[:-1] + (delta.size(-1),)) + + return result + delta + + +class ALoraLinearVariant(LoraVariant): + @staticmethod + def init(module: Linear, adapter_name: str, config: LoraConfig, **kwargs: Any) -> None: + pass + + @staticmethod + def merge_safe(module: Linear, active_adapter: str, orig_weight: torch.Tensor) -> torch.Tensor: + raise NotImplementedError("aLoRA does not support safe merging.") + + @staticmethod + def merge_unsafe(module: Linear, active_adapter: str, orig_weight: torch.Tensor) -> None: + raise NotImplementedError("aLoRA does not support merging.") + + @staticmethod + def unmerge(module: Linear, active_adapter: str, orig_weight: torch.Tensor) -> torch.Tensor: + raise NotImplementedError("aLoRA does not support unmerging.") + + @staticmethod + def forward( + module: Linear, + active_adapter: str, + x: torch.Tensor, + result: torch.Tensor, + **kwargs, + ) -> torch.Tensor: + alora_offsets = kwargs.get("alora_offsets", None) + lora_A = module.lora_A[active_adapter] + lora_B = module.lora_B[active_adapter] + dropout = module.lora_dropout[active_adapter] + scaling = module.scaling[active_adapter] + x = x.to(lora_A.weight.dtype) + result_shape = result.shape + B = result_shape[0] # batch + if len(result_shape) == 3: + T = result_shape[1] # tokens + else: + T = 1 + D = result_shape[-1] # dimensions + Dx = x.shape[-1] + device = result.device + if alora_offsets is None: # use base model only, but ensure 0 gradient + mask = torch.zeros((B, T), dtype=torch.bool) + else: + # If alora_offsets[i] is None, this means that the invocation sequence was not found in the + # input. As a result, the weights should not be activated anywhere (equivalent to base model). + # Convert None -> 0 and clip to T + offsets = torch.tensor( + [0 if o is None else min(int(o), T) for o in alora_offsets], + device=device, + dtype=torch.long, + ) + # Mask True on the last `offsets[i]` positions for each row i + pos = torch.arange(T, device=device).unsqueeze(0) # [1, T] + mask = pos >= (T - offsets).unsqueeze(1) + + # Flatten for vectorization + x_flat = x.view(-1, Dx) + res_flat = result.view(-1, D) + mask_flat = mask.view(-1) + + # Compute adapter on the selected tokens only + res_flat[mask_flat] += lora_B(lora_A(dropout(x_flat[mask_flat]))) * scaling + return result + + +def calculate_alora_offsets( + peft_config: PeftConfig, active_adapter: str, input_ids: torch.Tensor, adapter_names: Optional[list[str]] = None +) -> list[int]: + """ + This is a helper function for Activated LoRA (aLoRA) that searches each input token sequence for the last + occurrence of the appropriate "alora_invocation_tokens" invocation sequence. The calculated alora_offset is the + location of the *start* of the invocation tokens, counting backward from the end (will therefore always be >= + len(alora_invocation_tokens). If adapter_names is passed, then each input uses the appropriate invocation sequence + for the specified adapter for that row. Logic is provided to handle mixed collections of adapters for which not all + are aLoRAs (e.g. some base model, some LoRA). + """ + if input_ids is None: + return [] + + batch_size = input_ids.shape[0] + alora_offsets = [None] * batch_size + + cached_invocation_tensors = {} + adapters_to_process_indices = collections.defaultdict(list) + + for i in range(batch_size): + current_adapter_name = adapter_names[i] if adapter_names and i < len(adapter_names) else active_adapter + + if current_adapter_name == "__base__": + alora_offsets[i] = None + continue + + if current_adapter_name not in peft_config: + warnings.warn(f"Adapter '{current_adapter_name}' not found in peft_config. Using base model for row {i}.") + alora_offsets[i] = None + continue + + current_peft_config = peft_config[current_adapter_name] + + invocation_tokens = getattr(current_peft_config, "alora_invocation_tokens", None) + if invocation_tokens is None: + alora_offsets[i] = None # Not an aLoRA adapter or wrong type + continue + + if current_adapter_name not in cached_invocation_tensors: + cached_invocation_tensors[current_adapter_name] = torch.tensor( + invocation_tokens, dtype=torch.long, device=input_ids.device + ) + + adapters_to_process_indices[current_adapter_name].append(i) + + for adapter_name_to_process, indices in adapters_to_process_indices.items(): + current_invocation_ids_tensor = cached_invocation_tensors[adapter_name_to_process] + invocation_len = len(current_invocation_ids_tensor) + + for i in indices: + sequence = input_ids[i] + seq_len = len(sequence) + best_match_start_idx = -1 + + possible_starts = (sequence == current_invocation_ids_tensor[0]).nonzero(as_tuple=True)[0] + + for start_idx_tensor in possible_starts: + idx = start_idx_tensor.item() + if idx + invocation_len <= seq_len: + if torch.equal(sequence[idx : idx + invocation_len], current_invocation_ids_tensor): + best_match_start_idx = max(best_match_start_idx, idx) + + if best_match_start_idx != -1: + offset_val = seq_len - best_match_start_idx + alora_offsets[i] = offset_val if offset_val > 0 else None + else: # Invocation sequence not found in input + alora_offsets[i] = None + return alora_offsets + + +def is_alora_relevant_in_batch(model: nn.Module, adapter_names: Optional[list[str]] = None): + """ + Helper function to determine if the current batch has any aLoRA adapters. + """ + is_alora_relevant = False + if getattr(model.active_peft_config, "alora_invocation_tokens", None): + is_alora_relevant = True + elif adapter_names: + for name in adapter_names: + if name == "__base__": + continue + config_ = model.peft_config.get(name) + if config_ and getattr(config_, "alora_invocation_tokens", None): + is_alora_relevant = True + break + + return is_alora_relevant + + +def get_alora_offsets_for_forward( + model: nn.Module, input_ids: torch.Tensor = None, inputs_embeds: torch.Tensor = None, **kwargs +): + """ + Wrapper around calculate_alora_offsets, for the .forward of the model. It only calculates alora_offsets if the + batch contains aLoRA adapters. + """ + adapter_names_for_offset_calc = kwargs.get("adapter_names", None) + if not is_alora_relevant_in_batch(model, adapter_names_for_offset_calc): + # Nothing to compute + return kwargs + alora_offsets = kwargs.get("alora_offsets") + if alora_offsets is None: + if input_ids is None and inputs_embeds is not None: + warnings.warn( + "Cannot calculate aLoRA offsets when only inputs_embeds are provided. Disabling aLoRA for this forward pass." + ) + kwargs["alora_offsets"] = None + elif input_ids is not None: + kwargs["alora_offsets"] = calculate_alora_offsets( + model.peft_config, + model.active_adapter, + input_ids, + adapter_names=adapter_names_for_offset_calc, + ) + else: + kwargs["alora_offsets"] = None + return kwargs + + +def get_alora_offsets_for_generate(model: nn.module, *args, **kwargs): + """ + Wrapper around calculate_alora_offsets, for the .generate of the model. It only calculates alora_offsets if the + batch contains aLoRA adapters. + """ + adapter_names_for_offset_calc = kwargs.get("adapter_names") + if not is_alora_relevant_in_batch(model, adapter_names_for_offset_calc): + # Nothing to compute + return kwargs + alora_offsets_from_kwargs = kwargs.get("alora_offsets") + if alora_offsets_from_kwargs is None: + current_input_ids = kwargs.get("input_ids") + if current_input_ids is None: # args[0] is usually input_ids + if args and isinstance(args[0], torch.Tensor): + current_input_ids = args[0] + else: + current_input_ids = None + + if current_input_ids is not None: + if current_input_ids.ndim == 1: + current_input_ids = current_input_ids.unsqueeze(0) + calculated_offsets = calculate_alora_offsets( + model.peft_config, + model.active_adapter, + current_input_ids, + adapter_names=adapter_names_for_offset_calc, + ) + kwargs["alora_offsets"] = calculated_offsets + + else: + warnings.warn( + "Cannot calculate aLoRA offsets during generate as input_ids are not available. Disabling aLoRA." + ) + + kwargs["alora_offsets"] = None + return kwargs + + +class VeloraLinearVariant(LoraVariant): + @staticmethod + def init(module: Linear, adapter_name: str, config: LoraConfig, **kwargs: Any) -> None: + if not hasattr(module, "lora_velora_embed"): + module.lora_velora_embed = BufferDict({}, persistent=True) + if not hasattr(module, "lora_velora_initialized"): + module.lora_velora_initialized = {} + if not hasattr(module, "lora_velora_num_groups"): + module.lora_velora_num_groups = {} + if not hasattr(module, "lora_velora_init_type"): + module.lora_velora_init_type = {} + if not hasattr(module, "lora_velora_scale"): + module.lora_velora_scale = {} + + velora_param_names = ( + "lora_velora_embed", + "lora_velora_initialized", + "lora_velora_num_groups", + "lora_velora_init_type", + "lora_velora_scale", + ) + for param_name in velora_param_names: + if param_name not in module.other_param_names: + module.other_param_names = module.other_param_names + (param_name,) + + module.lora_velora_num_groups[adapter_name] = config.velora_config.num_groups + module.lora_velora_init_type[adapter_name] = config.velora_config.init_type + module.lora_velora_scale[adapter_name] = config.velora_config.scale + + group_dim = _get_group_dim(module.in_features, config.velora_config.num_groups) + base_layer = module.get_base_layer() + dtype = base_layer.weight.dtype + device = base_layer.weight.device + + if config.velora_config.init_type == "random": + embed = _normalize_projection(torch.randn(group_dim, device=device, dtype=dtype)).to(dtype=dtype) + initialized = True + else: + embed = torch.zeros(group_dim, device=device, dtype=dtype) + initialized = False + + module.lora_velora_embed[adapter_name] = embed + module.lora_velora_initialized[adapter_name] = initialized + module._move_adapter_to_device_of_base_layer(adapter_name) + + @staticmethod + def merge_safe(module: Linear, active_adapter: str, orig_weight: torch.Tensor) -> torch.Tensor: + orig_dtype = orig_weight.dtype + delta_weight = module.get_delta_weight(active_adapter) + return orig_weight + delta_weight.to(orig_dtype) + + @staticmethod + def merge_unsafe(module: Linear, active_adapter: str, orig_weight: torch.Tensor) -> None: + orig_weight.data += module.get_delta_weight(active_adapter) + + @staticmethod + def unmerge(module: Linear, active_adapter: str, orig_weight: torch.Tensor) -> torch.Tensor: + orig_dtype = orig_weight.dtype + delta_weight = module.get_delta_weight(active_adapter) + return orig_weight - delta_weight.to(orig_dtype) + + @staticmethod + def _maybe_update_embed(module: Linear, adapter_name: str, x: torch.Tensor) -> None: + if adapter_name not in module.lora_velora_initialized: + return + + init_type = module.lora_velora_init_type[adapter_name] + if init_type == "random": + return + if init_type == "batch_average_once": + initialized = module.lora_velora_initialized[adapter_name] + if initialized: + return + + num_groups = module.lora_velora_num_groups[adapter_name] + with torch.no_grad(): + subtokens = _reshape_to_grouped_subtokens(x.detach(), num_groups) + subtokens = subtokens.reshape(-1, subtokens.shape[-1]) + embed = _normalize_projection(subtokens.mean(dim=0)) + target = module.lora_velora_embed[adapter_name] + module.lora_velora_embed[adapter_name] = embed.to(device=target.device, dtype=target.dtype) + module.lora_velora_initialized[adapter_name] = True + + @staticmethod + def forward( + module: Linear, + active_adapter: str, + x: torch.Tensor, + result: torch.Tensor, + **kwargs, + ) -> torch.Tensor: + lora_A = module.lora_A[active_adapter] + lora_B = module.lora_B[active_adapter] + dropout = module.lora_dropout[active_adapter] + scaling = module.scaling[active_adapter] + + x = dropout(x) + + if module.training and torch.is_grad_enabled(): + VeloraLinearVariant._maybe_update_embed(module, active_adapter, x) + after_A = VeloraFunction.apply( + x, + lora_A.weight, + lora_A.bias, + module.lora_velora_embed[active_adapter], + module.lora_velora_num_groups[active_adapter], + module.lora_velora_scale[active_adapter], + ) + else: + after_A = lora_A(x) + + result = result + lora_B(after_A) * scaling + return result + + +class BlockDiagonalLinear(nn.Module): + def __init__( + self, + in_features: int, + out_features: int, + nblocks: int, + init_zero: bool = False, + dtype: torch.dtype = torch.float32, + device: torch.device | None = None, + ): + super().__init__() + self.in_features = in_features + self.out_features = out_features + self.nblocks = nblocks + device = device or torch.device("cpu") + if self.in_features % nblocks != 0 or self.out_features % nblocks != 0: + raise ValueError( + f"self.in_features={self.in_features} or self.out_features={self.out_features} not divisible by {self.nblocks}" + ) + # Create weight with specified dtype and device + self.weight = nn.Parameter(torch.empty(out_features, in_features // nblocks, dtype=dtype, device=device)) + + if init_zero: + torch.nn.init.zeros_(self.weight) + else: + torch.nn.init.kaiming_uniform_(self.weight) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + first_dims = x.shape[:-1] + if x.dim() != 2: + x = x.reshape(-1, x.shape[-1]) + B = x.shape[0] + nb = self.nblocks + m = x.shape[-1] // nb + n = self.out_features // nb + x = x.reshape(B, nb, m) + w = self.weight.view(nb, n, m) + out = torch.einsum("bim,inm->bin", x, w) + return out.reshape(*first_dims, -1) + + def weight_as_blockdiagonal_matrix(self): + """Returns weight in a format similar to a vanilla LoRA adapter. For this, we stack the blocks on the diagonal, + leaving the off-diagonals padded with zero.""" + return torch.block_diag(*torch.chunk(self.weight, self.nblocks, dim=0)) + + +class BdLoraLinearVariant(LoraVariant): + @staticmethod + def init(module: Linear, adapter_name: str, config: LoraConfig, **kwargs) -> None: + use_bdlora = config.use_bdlora + target_name = kwargs.get("target_name", "") + + # Handle case where use_bdlora is a dict (from saved config) instead of BdLoraConfig object + if isinstance(use_bdlora, dict): + use_bdlora = BdLoraConfig(**use_bdlora) + + lora_a_blockdiagonal_pattern = use_bdlora.target_modules_bd_a or [] + lora_b_blockdiagonal_pattern = use_bdlora.target_modules_bd_b or [] + nblocks = use_bdlora.nblocks + + has_lora_a_blockdiagonal = any(pattern in target_name for pattern in lora_a_blockdiagonal_pattern) + has_lora_b_blockdiagonal = any(pattern in target_name for pattern in lora_b_blockdiagonal_pattern) + + if has_lora_a_blockdiagonal and has_lora_b_blockdiagonal: + raise ValueError(f"Target {target_name} matches both A and B block-diagonal patterns") + if use_bdlora.match_strict and not (has_lora_a_blockdiagonal or has_lora_b_blockdiagonal): + raise ValueError( + f"Target {target_name} matches neither A nor B block-diagonal patterns." + "If this is intentional, set match_strict=False in BdLoraConfig during initialization. " + ) + + if has_lora_a_blockdiagonal: + r = module.lora_A[adapter_name].out_features + base_layer = module.get_base_layer() + layer = BlockDiagonalLinear( + base_layer.in_features, + r, + nblocks=nblocks, + init_zero=False, + dtype=base_layer.weight.dtype, + device=base_layer.weight.device, + ) + module.lora_A[adapter_name] = layer + elif has_lora_b_blockdiagonal: + r = module.lora_B[adapter_name].in_features + base_layer = module.get_base_layer() + layer = BlockDiagonalLinear( + r, + base_layer.out_features, + nblocks=nblocks, + init_zero=True, + dtype=base_layer.weight.dtype, + device=base_layer.weight.device, + ) + module.lora_B[adapter_name] = layer + + @staticmethod + def forward(module: Linear, active_adapter: str, x: torch.Tensor, result: torch.Tensor, **kwargs) -> torch.Tensor: + lora_A = module.lora_A[active_adapter] + lora_B = module.lora_B[active_adapter] + dropout = module.lora_dropout[active_adapter] + scaling = module.scaling[active_adapter] + x = dropout(x) + # Cast input dtype to match lora_A weight dtype + x = module._cast_input_dtype(x, lora_A.weight.dtype) + result += lora_B(lora_A(x)) * scaling + return result + + @staticmethod + def _get_weight_from_module_maybe_blockdiagonal(module: nn.Module) -> torch.Tensor: + if isinstance(module, BlockDiagonalLinear): + return module.weight_as_blockdiagonal_matrix() + else: + return module.weight # type: ignore + + @staticmethod + def _get_bdlora_delta_weight(module: Linear, adapter: str) -> torch.Tensor: + """Similar to get_delta_weight for a linear module, but we have to eventually reshape the blocks + of the weights.""" + device = module.lora_B[adapter].weight.device + # Use base layer dtype to ensure compatibility with merge/unmerge operations + base_layer = module.get_base_layer() + dtype = base_layer.weight.dtype + cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16) + + weight_A = BdLoraLinearVariant._get_weight_from_module_maybe_blockdiagonal(module.lora_A[adapter]) + weight_B = BdLoraLinearVariant._get_weight_from_module_maybe_blockdiagonal(module.lora_B[adapter]) + + if cast_to_fp32: + weight_A = weight_A.float() + weight_B = weight_B.float() + + output_tensor = transpose(weight_B @ weight_A, module.fan_in_fan_out) * module.scaling[adapter] + + if cast_to_fp32: + output_tensor = output_tensor.to(dtype=dtype) + + # Ensure output tensor matches base layer dtype + return output_tensor.to(dtype=dtype) + + @staticmethod + def merge_safe(module: Linear, active_adapter: str, orig_weight: torch.Tensor) -> torch.Tensor: + return orig_weight + BdLoraLinearVariant._get_bdlora_delta_weight(module, active_adapter) + + @staticmethod + def merge_unsafe(module: Linear, active_adapter: str, orig_weight: torch.Tensor) -> None: + orig_weight.data += BdLoraLinearVariant._get_bdlora_delta_weight(module, active_adapter) + + @staticmethod + def unmerge(module: Linear, active_adapter: str, orig_weight: torch.Tensor) -> torch.Tensor: + return orig_weight - BdLoraLinearVariant._get_bdlora_delta_weight(module, active_adapter) + + +class MontecloraLinearVariant(LoraVariant): + """ + Monteclora (Monte Carlo Low-Rank Adaptation) variant implementation. + + This variant adds variational inference to LoRA by introducing Monte Carlo sampling to the adapter weights during + training. The sampling is controlled by a MontecloraSampler that maintains variational parameters and produces + perturbations to the LoRA weights. + """ + + @staticmethod + def init(module: Linear, adapter_name: str, config: LoraConfig, **kwargs: Any) -> None: + """ + Initialize Monteclora for a LoRA layer. + + This adds a MontecloraSampler to the layer that will be used during forward passes to sample variational + perturbations for the LoRA A matrix. + + Args: + module: The Linear LoRA layer to add Monteclora to + adapter_name: Name of the adapter + config: The `LoraConfig` which carries the `monteclora_config`. + """ + monteclora_config = config.monteclora_config + + if not hasattr(module, "lora_monteclora_sampler"): + module.adapter_layer_names = module.adapter_layer_names[:] + ("lora_monteclora_sampler",) + module.lora_monteclora_sampler = nn.ModuleDict() + if not hasattr(module, "_lora_monteclora_config"): + module._lora_monteclora_config = {} + module._lora_monteclora_config[adapter_name] = monteclora_config + + lora_A = module.lora_A[adapter_name] + # When low_cpu_mem_usage=True, adapters can be initialized on meta device. + # Defer sampler creation until first forward on a concrete device. + if lora_A.weight.device.type != "meta": + module.lora_monteclora_sampler[adapter_name] = MontecloraLinearVariant._create_sampler( + module, adapter_name, monteclora_config + ) + + @staticmethod + def _create_sampler(module: Linear, adapter_name: str, monteclora_config: MontecloraConfig) -> MontecloraSampler: + lora_A = module.lora_A[adapter_name] + return MontecloraSampler( + in_features=module.in_features, + out_features=lora_A.out_features, + num_samples=monteclora_config.num_samples, + use_entropy=monteclora_config.use_entropy, + dirichlet_prior=monteclora_config.dirichlet_prior, + sample_scaler=monteclora_config.sample_scaler, + kl_loss_weight=monteclora_config.kl_loss_weight, + buffer_size=monteclora_config.buffer_size, + device=lora_A.weight.device, + dtype=lora_A.weight.dtype, + ) + + @staticmethod + def merge_safe(module: Linear, active_adapter: str, orig_weight: torch.Tensor) -> torch.Tensor: + """ + Safely merge Monteclora adapter weights into base weights. + + For merging, we ignore the MC sampling and just use the base LoRA weights (lora_A and lora_B). This is + equivalent to merging a standard LoRA adapter. + + Args: + module: The Linear LoRA layer + active_adapter: Name of the adapter to merge + orig_weight: Original base layer weight + + Returns: + New weight with adapter merged + """ + orig_dtype = orig_weight.dtype + delta_weight = module.get_delta_weight(active_adapter) + new_weight = orig_weight + delta_weight.to(orig_dtype) + return new_weight + + @staticmethod + def merge_unsafe(module: Linear, active_adapter: str, orig_weight: torch.Tensor) -> None: + """ + Merge Monteclora adapter weights into base weights (in-place). + + For merging, we ignore the MC sampling and just use the base LoRA weights (lora_A and lora_B). This is + equivalent to merging a standard LoRA adapter. + + Args: + module: The Linear LoRA layer + active_adapter: Name of the adapter to merge + orig_weight: Original base layer weight (modified in-place) + """ + delta_weight = module.get_delta_weight(active_adapter) + orig_weight.data += delta_weight + + @staticmethod + def unmerge(module: Linear, active_adapter: str, orig_weight: torch.Tensor) -> torch.Tensor: + """ + Unmerge Monteclora adapter weights from base weights. + + For unmerging, we ignore the MC sampling and just use the base LoRA weights (lora_A and lora_B). This is + equivalent to unmerging a standard LoRA adapter. + + Args: + module: The Linear LoRA layer + active_adapter: Name of the adapter to unmerge + orig_weight: Current weight with adapter merged + + Returns: + Weight with adapter unmerged + """ + orig_dtype = orig_weight.dtype + delta_weight = module.get_delta_weight(active_adapter) + new_weight = orig_weight - delta_weight.to(orig_dtype) + return new_weight + + @staticmethod + def forward( + module: Linear, + active_adapter: str, + x: torch.Tensor, + result: torch.Tensor, + **kwargs, + ) -> torch.Tensor: + """ + Forward pass with Monteclora sampling. + + This samples variational perturbations from the MontecloraSampler and applies them to the LoRA A weights before + computing the LoRA update. + + Args: + module: The Linear LoRA layer + active_adapter: Name of the active adapter + x: Input tensor + result: Output from the base layer + **kwargs: Additional arguments (unused) + + Returns: + result + LoRA update with Monteclora sampling applied + """ + lora_A = module.lora_A[active_adapter] + lora_B = module.lora_B[ + active_adapter + ] # lora_B is zero in the beginning. test for stochasticity of outputs might fail because of this + dropout = module.lora_dropout[active_adapter] + scaling = module.scaling[active_adapter] + if active_adapter not in module.lora_monteclora_sampler: + # Sampler creation was deferred in `init` because the LoRA weights were on the meta device + # (e.g. when `low_cpu_mem_usage=True`). Now that we have a real tensor at forward time, we can + # finally create the sampler on the correct device. + monteclora_config = module._lora_monteclora_config[active_adapter] + module.lora_monteclora_sampler[active_adapter] = MontecloraLinearVariant._create_sampler( + module, active_adapter, monteclora_config + ) + sampler = module.lora_monteclora_sampler[active_adapter] + + x = x.to(lora_A.weight.dtype) + if isinstance(dropout, nn.Identity) or not module.training: + x_dropped = x + else: + x_dropped = dropout(x) + + current_weight_A = lora_A.weight + + if module.training: + lora_A_vars, lora_A_wts = sampler() + if torch.isnan(lora_A_vars).any() or torch.isnan(lora_A_wts).any(): + warnings.warn("Monteclora sampling produced NaNs, using base weights.") + else: + noise = torch.nan_to_num(lora_A_vars, nan=0.0) + base_w = lora_A.weight.T + perturbed_w = base_w + noise + averaged_w = torch.einsum("n,nij->ij", lora_A_wts, perturbed_w) + current_weight_A = averaged_w.T + out_A = F.linear(x_dropped, current_weight_A) + result = result + lora_B(out_A) * scaling + return result diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/velora.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/velora.py new file mode 100644 index 0000000000000000000000000000000000000000..f3f9f533fde9c341ba442d08126734969b8bc8a2 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lora/velora.py @@ -0,0 +1,112 @@ +# Copyright 2026-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 typing import Optional + +import torch +import torch.nn.functional as F + + +def _get_group_dim(in_features: int, num_groups: int) -> int: + return (in_features + num_groups - 1) // num_groups + + +def _reshape_to_grouped_subtokens(x: torch.Tensor, num_groups: int) -> torch.Tensor: + group_dim = _get_group_dim(x.shape[-1], num_groups) + padded_features = num_groups * group_dim + if x.shape[-1] != padded_features: + x = F.pad(x, (0, padded_features - x.shape[-1])) + return x.reshape(-1, num_groups, group_dim) + + +def _compress_activations(x: torch.Tensor, embed: torch.Tensor, num_groups: int) -> torch.Tensor: + grouped = _reshape_to_grouped_subtokens(x, num_groups) + return torch.einsum("tgd,d->tg", grouped, embed) + + +def _reconstruct_activations( + compressed: torch.Tensor, + embed: torch.Tensor, + in_features: int, + velora_scale: float, +) -> torch.Tensor: + grouped = compressed.unsqueeze(-1) * embed.view(1, 1, -1) + reconstructed = grouped.reshape(-1, compressed.shape[-1] * embed.numel()) + return reconstructed[:, :in_features] * velora_scale + + +def _normalize_projection(embed: torch.Tensor) -> torch.Tensor: + embed = embed.float() + norm = torch.linalg.vector_norm(embed) + if norm == 0: + embed = torch.ones_like(embed) + norm = torch.linalg.vector_norm(embed) + return embed / norm + + +class VeloraFunction(torch.autograd.Function): + @staticmethod + def forward( + ctx, + input: torch.Tensor, + weight: torch.Tensor, + bias: Optional[torch.Tensor], + embed: torch.Tensor, + num_groups: int, + velora_scale: float, + ) -> torch.Tensor: + output = F.linear(input, weight, bias) + + ctx.input_shape = tuple(input.shape) + ctx.input_dtype = input.dtype + ctx.in_features = input.shape[-1] + ctx.num_groups = num_groups + ctx.velora_scale = velora_scale + ctx.bias_dtype = None if bias is None else bias.dtype + + compressed = _compress_activations(input, embed.to(dtype=input.dtype), num_groups) + ctx.save_for_backward(compressed, weight, embed) + return output + + @staticmethod + def backward(ctx, grad_output: torch.Tensor): + compressed, weight, embed = ctx.saved_tensors + compute_dtype = grad_output.dtype + + grad_output_2d = grad_output.reshape(-1, grad_output.shape[-1]).to(compute_dtype) + weight_compute = weight.to(compute_dtype) + + grad_input = grad_weight = grad_bias = None + + if ctx.needs_input_grad[0]: + grad_input = grad_output_2d @ weight_compute + grad_input = grad_input.reshape(ctx.input_shape).to(dtype=ctx.input_dtype) + + if ctx.needs_input_grad[1]: + reconstructed = _reconstruct_activations( + compressed.to(compute_dtype), + embed.to(compute_dtype), + ctx.in_features, + ctx.velora_scale, + ) + grad_weight = grad_output_2d.transpose(0, 1) @ reconstructed + grad_weight = grad_weight.to(dtype=weight.dtype) + + if ctx.needs_input_grad[2]: + grad_bias = grad_output_2d.sum(dim=0) + grad_bias = grad_bias.to(dtype=ctx.bias_dtype) + + return grad_input, grad_weight, grad_bias, None, None, None diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lycoris_utils.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lycoris_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..883cbb91a3f835092a2dc2a81d289fab25b6c0d4 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/lycoris_utils.py @@ -0,0 +1,261 @@ +# 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 abc import abstractmethod +from dataclasses import dataclass, field +from typing import Any, Optional, Union + +import torch +from torch import nn + +from peft.config import PeftConfig + +from .tuners_utils import ( + BaseTuner, + BaseTunerLayer, + _get_in_out_features, + check_adapters_to_merge, +) + + +@dataclass +class LycorisConfig(PeftConfig): + r""" + A base config for LyCORIS like adapters + """ + + rank_pattern: Optional[dict] = field( + default_factory=dict, + metadata={ + "help": ( + "The mapping from layer names or regexp expression to ranks which are different from the default rank specified by `r`. " + "For example, `{'^model.decoder.layers.0.encoder_attn.k_proj': 16}`." + ) + }, + ) + alpha_pattern: Optional[dict] = field( + default_factory=dict, + metadata={ + "help": ( + "The mapping from layer names or regexp expression to alphas which are different from the default alpha specified by `alpha`. " + "For example, `{'^model.decoder.layers.0.encoder_attn.k_proj': 16}`." + ) + }, + ) + + +class LycorisLayer(BaseTunerLayer): + r""" + A base layer for LyCORIS like adapters + """ + + # adapter_layer_names needs to be defined on the child class + other_param_names = ("r", "alpha", "scaling", "rank_dropout", "module_dropout") + + def __init__(self, base_layer: nn.Module) -> None: + self.base_layer = base_layer + self.r = {} + self.alpha = {} + self.scaling = {} + self.rank_dropout = {} + self.rank_dropout_scale = {} + self.module_dropout = {} + + # Tuner info + 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 + + in_features, out_features = _get_in_out_features(self.get_base_layer()) + self.in_features = in_features + self.out_features = out_features + + @property + @abstractmethod + def _available_adapters(self) -> set[str]: ... + + def _init_empty_weights(self, cls, *args, **kwargs) -> None: + # A helper method that allows to initialize the layer of the given class without spending time to initialize the + # model weights. The implementation is inspired by + # https://pytorch.org/docs/stable/generated/torch.nn.utils.skip_init.html but this function cannot be used + # directly. + # Instead of this approach, it would be possible to bypass the __init__ of the class but that runs the risk of + # omitting important logic inside that __init__. + kwargs = kwargs.copy() + final_device = kwargs.pop("device", "cpu") + cls.__init__(self, *args, device="meta", **kwargs) + self.to_empty(device=final_device) + + @abstractmethod + def create_adapter_parameters(self, adapter_name: str, r: int, **kwargs): ... + + # TODO: refactor LoRA to use the same approach + @abstractmethod + def _get_delta_activations(self, adapter_name: str, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + """Activations added on top of the base layer output (i.e. after the base layer forward pass)""" + + @abstractmethod + def get_delta_weight(self, adapter_name: str) -> torch.Tensor: ... + + 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._available_adapters: + base_layer = self.get_base_layer() + if safe_merge: + 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) + + @abstractmethod + def reset_adapter_parameters(self, adapter_name: str): ... + + def set_scale(self, adapter, scale): + if adapter not in self._available_adapters: + # Ignore the case where the adapter is not in the layer + return + self.scaling[adapter] = scale * self.alpha[adapter] / self.r[adapter] + + def scale_layer(self, scale: float) -> None: + if scale == 1: + return + + for active_adapter in self.active_adapters: + if active_adapter not in self._available_adapters: + continue + + self.scaling[active_adapter] *= scale + + 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 in self._available_adapters: + self.get_base_layer().weight.data -= self.get_delta_weight(active_adapter) + + def unscale_layer(self, scale=None) -> None: + for active_adapter in self.active_adapters: + if active_adapter not in self._available_adapters: + continue + + if scale is None: + self.scaling[active_adapter] = self.alpha[active_adapter] / self.r[active_adapter] + else: + self.scaling[active_adapter] /= scale + + @abstractmethod + def update_layer(self, adapter_name: str, r: int, alpha: float, **kwargs): ... + + +class LycorisTuner(BaseTuner): + r""" + A base tuner for LyCORIS like adapters + + Args: + model ([`torch.nn.Module`]): The model to be adapted. + config ([`LoraConfig`]): The configuration of the Lora 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. + + """ + + prefix: str + tuner_layer_cls = LycorisLayer + layers_mapping: dict[type[torch.nn.Module], type[LycorisLayer]] + + @abstractmethod + def _create_and_replace( + self, + config: LycorisConfig, + adapter_name: str, + target: Union[LycorisLayer, nn.Module], + target_name, + parent, + current_key, + ): ... + + @classmethod + def _create_new_module(cls, config: LycorisConfig, adapter_name: str, target: nn.Module, **kwargs) -> LycorisLayer: + # Find corresponding subtype of provided target module + new_module_cls = None + for subtype, target_cls in cls.layers_mapping.items(): + if ( + hasattr(target, "base_layer") + and isinstance(target.get_base_layer(), subtype) + and isinstance(target, BaseTunerLayer) + ): + # nested tuner layers are allowed + new_module_cls = target_cls + break + elif isinstance(target, subtype): + new_module_cls = target_cls + break + + # We didn't find corresponding type, so adapter for this layer is not supported + if new_module_cls is None: + supported_modules = ", ".join(layer.__name__ for layer in cls.layers_mapping.keys()) + raise TypeError( + f"Target module of type {type(target)} not supported, " + f"currently only adapters for {supported_modules} are supported" + ) + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if isinstance(target_base_layer, (torch.nn.Conv2d, torch.nn.Conv1d, torch.nn.Linear)): + new_module = new_module_cls(target, adapter_name=adapter_name, config=config, **kwargs) + else: + supported_modules = ", ".join(layer.__name__ for layer in cls.layers_mapping.keys()) + raise TypeError( + f"Target module of type {type(target)} not supported, " + f"currently only adapters for {supported_modules} are supported" + ) + + return new_module diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/miss/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/miss/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ca8aceeb0dc772c6db6157834de40ab2c43fe291 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/miss/__init__.py @@ -0,0 +1,24 @@ +# 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 MissConfig +from .layer import MissLayer, MissLinear +from .model import MissModel + + +__all__ = ["MissConfig", "MissLayer", "MissLinear", "MissModel"] + +register_peft_method(name="miss", config_cls=MissConfig, model_cls=MissModel) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/miss/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/miss/config.py new file mode 100644 index 0000000000000000000000000000000000000000..85287e5f21cbe25faf3d340b6ec1494308b62682 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/miss/config.py @@ -0,0 +1,140 @@ +# 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 Literal, Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class MissConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`MissModel`]. + + Args: + r (`int`): + The rank of MiSS across different layers. It is best to set 'r' to an even number; otherwise, the default + initialization method will not work. The rank of MiSS corresponds to a low-rank decomposition along the + in_features dimension. + miss_dropout (`float`): + The dropout probability for MiSS layers. + mini_r (`int`): + The rank of MiSS corresponds to a low-rank decomposition along the out_features dimension. When you set + `init_weights=mini`, you need to set `mini_r`. Please make sure that `out_features` is divisible by + `mini_r`. + 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. + 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 | Literal["bat", "mini"]): + Different initializations correspond to different MiSS variants. By default(balance), the most efficient + and general method in MiSS will be used. 'bat': In this mode, you can enable nonlinear updates across + different shards. 'mini': In this mode, you can set a smaller rank to use fewer trainable parameters, but + it is recommended to keep `out_features % mini_r == 0`. + 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 (`str`): + The layer pattern name, used only if `layers_to_transform` is different from `None`. + modules_to_save (`List[str]`): + List of modules apart from adapter layers to be set as trainable and saved in the final checkpoint. + """ + + r: int = field( + default=64, + metadata={ + "help": "The rank of MiSS corresponds to a low-rank decomposition along the in_features dimension.", + "note": "It is best to set 'r' to an even number; otherwise, the default initialization method will not work.", + }, + ) + miss_dropout: float = field(default=0.0, metadata={"help": "MiSS dropout"}) + mini_r: int = field( + default=1, + metadata={ + "help": "The rank of MiSS corresponds to a low-rank decomposition along the out_features dimension.", + "note": "It is recommended that mini_r be divisible by out_features. When mini_r == out_features, the mini method is equivalent to the default efficient MiSS.", + }, + ) + 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 MiSS.", + "example": "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 MiSS."}, + ) + init_weights: bool | Literal["bat", "mini"] = field( + default=True, + metadata={ + "help": ( + "True -> MiSS balance; `bat` -> Bat; `mini` -> smaller rank and efficiency" + "Whether to initialize the weights of the MiSS 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." + }, + ) + bias: str = field(default="none", metadata={"help": "Bias type for MiSS. Can be 'none', 'all' or 'MiSS_only'"}) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": "List of modules apart from MiSS 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.MISS + 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 + ) + # if target_modules is a regex expression, then layers_to_transform should be None + if isinstance(self.target_modules, str) and self.layers_to_transform is not None: + raise ValueError("`layers_to_transform` cannot be used when `target_modules` is a str.") + + # if target_modules is a regex expression, then layers_pattern should be None + if isinstance(self.target_modules, str) and self.layers_pattern is not None: + raise ValueError("`layers_pattern` cannot be used when `target_modules` is a str.") diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/miss/layer.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/miss/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..3bfa61abd916c394249b7b0099c50f96e2318a48 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/miss/layer.py @@ -0,0 +1,377 @@ +# 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 math +import warnings +from typing import Any, Optional + +import torch +import torch.nn.functional as F +from torch import nn + +from peft.tuners.tuners_utils import BaseTunerLayer, _get_in_out_features, check_adapters_to_merge +from peft.utils import quantization_extra_repr, resolve_quantization_backend + +from .config import MissConfig + + +class MissLayer(BaseTunerLayer): + # All names of layers that may contain (trainable) adapter weights + adapter_layer_names = ("miss_block",) + # All names of other parameters that may contain adapter-related parameters + other_param_names = ("miss_r", "miss_dropout", "miss_mini_r") + + def __init__(self, base_layer: nn.Module, **kwargs) -> None: + self.base_layer = base_layer + self.quantization_backend = resolve_quantization_backend( + self.get_base_layer(), get_apply_tensor_subclass=kwargs.get("get_apply_tensor_subclass") + ) + self.miss_r = {} + self.miss_dropout = nn.ModuleDict({}) + self.miss_mini_r = {} + self.miss_block = nn.ParameterDict({}) + # 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() + in_features, out_features = _get_in_out_features(base_layer) + if (in_features is None) or (out_features is None): + raise TypeError(f"Unsupported layer type {type(base_layer)}") + self.in_features, self.out_features = in_features, out_features + + def update_layer( + self, + adapter_name: str, + r: int, + config: MissConfig, + inference_mode: bool = False, + **kwargs, + ) -> None: + """Internal function to create miss adapter + + Args: + adapter_name (`str`): Name for the adapter to add. + r (`int`): Rank for the added adapter. + init_weights (`bool`): Whether to initialize weights. + """ + mini_r = config.mini_r + miss_dropout = config.miss_dropout + init_weights = config.init_weights + + if r <= 0: + raise ValueError(f"`r` should be a positive integer value but the value passed is {r}") + + self.miss_r[adapter_name] = r + self.miss_mini_r[adapter_name] = mini_r + if miss_dropout > 0.0: + miss_dropout_layer = nn.Dropout(p=miss_dropout) + else: + miss_dropout_layer = nn.Identity() + + self.miss_dropout[adapter_name] = miss_dropout_layer + + # Determine shape of MiSS weights; supportedness was already validated in __init__ and the model dispatcher. + self.miss_block[adapter_name] = nn.Parameter(torch.zeros(r, self.out_features), requires_grad=True) + + # Initialize weights + if init_weights == "bat": + if self.in_features % r != 0 or self.out_features % r != 0: + raise ValueError("The weight matrix must be fully divisible into [r, r] blocks.") + self.reset_bat_parameters(adapter_name, r) + elif init_weights == "mini": + if self.out_features % mini_r != 0: + raise ValueError( + "mini_r is divided along the out_features dimension. For optimal performance and implementation simplicity," + "it is recommended that out_features be divisible by mini_r." + "Error: {self.out_features} % mini_r != 0" + ) + self.reset_mini_parameters(adapter_name, r, mini_r) + elif init_weights: + self.reset_miss_parameters(adapter_name, r) + else: + self.reset_miss_parameters_random(adapter_name) + # 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_miss_parameters(self, adapter_name: str, r): + self.miss_block[adapter_name] = nn.Parameter(torch.zeros(r, self.out_features), requires_grad=True) + + def reset_bat_parameters(self, adapter_name: str, r): + self.miss_block[adapter_name] = nn.Parameter(torch.zeros(self.out_features // r, r, r), requires_grad=True) + + def reset_mini_parameters(self, adapter_name: str, r, mini_r): + self.miss_block[adapter_name] = nn.Parameter(torch.zeros(r, mini_r), requires_grad=True) + + def reset_miss_parameters_random(self, adapter_name: str): + nn.init.kaiming_uniform_(self.miss_block[adapter_name], a=math.sqrt(5)) + + def scale_layer(self, scale: float) -> None: + if scale == 1: + return + + for active_adapter in self.active_adapters: + if active_adapter not in self.miss_block.keys(): + continue + + warnings.warn("Scaling operation for MiSS 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.miss_block.keys(): + continue + + warnings.warn("Unscaling operation for MiSS not supported! Keeping scale at 1.") + + +class MissLinear(nn.Module, MissLayer): + """ + MiSS implemented in a dense layer. + """ + + def __init__( + self, + base_layer, + adapter_name: str, + config: MissConfig, + r: int = 0, + **kwargs, + ) -> None: + super().__init__() + MissLayer.__init__(self, base_layer, **kwargs) + self._active_adapter = adapter_name + self.update_layer(adapter_name, r, config=config, **kwargs) + self.miss_fn = config.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.miss_block.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. + weight = self.get_base_weight().clone() + orig_dtype = weight.dtype + if self.miss_fn == "bat": + weight += self.get_delta_weight(active_adapter, weight) + else: + weight = self.get_delta_weight_miss(active_adapter, weight) + + if not torch.isfinite(weight).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + self.set_base_weight(weight.to(orig_dtype)) + else: + weight = self.get_base_weight() + orig_dtype = weight.dtype + if self.miss_fn == "bat": + weight += self.get_delta_weight(active_adapter, weight) + else: + weight = self.get_delta_weight_miss(active_adapter, weight) + self.set_base_weight(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: + active_adapter = self.merged_adapters.pop() + base_layer = self.get_base_layer() + if active_adapter in self.miss_block.keys(): + weight = self.get_base_weight() + orig_dtype = weight.dtype + if self.miss_fn == "bat": + weight = self.get_delta_weight(active_adapter, weight, reverse=True) + elif self.miss_fn == "mini": + weight = self.get_delta_weight_miss(active_adapter, weight, reverse=True) + else: + weight = self.get_delta_weight_miss(active_adapter, weight, reverse=True) + + self.set_base_weight(weight.to(orig_dtype)) + + def get_delta_weight(self, adapter, orig_weight, reverse: bool = False) -> 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. + reverse (bool): + If True, reverse the merge (unmerge). If False, apply the merge (forward). + """ + device = self.miss_block[adapter].device + dtype = self.miss_block[adapter].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) + + miss_B = self.miss_block[adapter] + + if cast_to_fp32: + miss_B = miss_B.float() + orig_weight = orig_weight.to(miss_B.dtype) + + r = miss_B.size(-1) + W = orig_weight.reshape(orig_weight.size(0) // r, r, orig_weight.size(1) // r, r).permute(2, 0, 1, 3) + + if reverse: + eye = torch.eye(r, device=miss_B.device, dtype=torch.float32) + inv_I_plus_miss_B = torch.inverse(eye + miss_B.float()).to(miss_B.dtype) + result = (W - miss_B) @ inv_I_plus_miss_B + else: + result = W @ miss_B + miss_B + + output_tensor = result.permute(1, 2, 0, 3).reshape(*orig_weight.shape) + + if cast_to_fp32: + output_tensor = output_tensor.to(dtype=dtype) + self.miss_block[adapter].data = miss_B.to(dtype) + + return output_tensor + + def get_delta_weight_miss(self, adapter, orig_weight, reverse: bool = False) -> torch.Tensor: + """ + Compute the *full* weight for the given adapter (not the weight delta!) + + Args: + adapter (str): + The name of the adapter for which the delta weight should be computed. + reverse (bool): + If True, reverse the merge (unmerge). If False, apply the merge (forward). + """ + device = self.miss_block[adapter].device + dtype = self.miss_block[adapter].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) + + miss_B = self.miss_block[adapter] + + if cast_to_fp32: + miss_B = miss_B.float() + + in_features = orig_weight.size(-1) + out_features = orig_weight.size(0) + r = miss_B.size(0) + if self.miss_fn == "mini": + miss_B = miss_B.repeat(1, out_features // self.miss_mini_r[adapter]) + + sign = -1 if reverse else 1 + + if in_features % r != 0: + remainder = in_features % r + n_blocks = in_features // r + aligned_size = n_blocks * r + + W_aligned = orig_weight[:, :aligned_size].reshape(-1, n_blocks, r).permute(1, 2, 0) + orig_weight[:, :aligned_size] = ( + (W_aligned + sign * miss_B).permute(2, 0, 1).reshape(*orig_weight[:, :aligned_size].shape) + ) + orig_weight[:, aligned_size:] = ( + orig_weight[:, aligned_size:] + sign * miss_B.transpose(0, 1)[:, :remainder] + ) + output_tensor = orig_weight + else: + W_blocks = orig_weight.reshape(-1, orig_weight.size(1) // r, r).permute(1, 2, 0) + output_tensor = (W_blocks + sign * miss_B).permute(2, 0, 1).reshape(*orig_weight.shape) + + if cast_to_fp32: + output_tensor = output_tensor.to(dtype=dtype) + self.miss_block[adapter].data = miss_B.to(dtype) + + return output_tensor + + 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: + if self.miss_fn == "bat": + orig_weight = self.get_base_weight().clone() + for active_adapter in self.active_adapters: + if active_adapter not in self.miss_block.keys(): + continue + delta_weight = self.get_delta_weight(active_adapter, orig_weight) + orig_weight = orig_weight + delta_weight + + x = self._cast_input_dtype(x, orig_weight.dtype) + bias = self._cast_input_dtype(self.base_layer.bias, orig_weight.dtype) + result = F.linear(input=x, weight=orig_weight, bias=bias) + else: + result = self.base_layer(x, *args, **kwargs) + if self.quantization_backend is not None: + result = self.quantization_backend.maybe_clone_base_result(result) + for active_adapter in self.active_adapters: + if active_adapter not in self.miss_block.keys(): + continue + miss = self.miss_block[active_adapter] + if self.miss_fn == "mini": + miss = miss.repeat(1, self.base_layer.out_features // self.miss_mini_r[active_adapter]) + + dropout = self.miss_dropout[active_adapter] + r = miss.size(0) + if x.size(-1) % r != 0: + padding_size = (r - x.size(-1) % r) % r + x = F.pad(x, (0, padding_size)) + x = self._cast_input_dtype(x, miss.dtype) + result = result + torch.sum(dropout(x).reshape(*x.shape[:-1], x.size(-1) // r, r), dim=-2) @ miss + + 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 "miss." + rep + + def extra_repr(self) -> str: + return quantization_extra_repr(self) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/miss/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/miss/model.py new file mode 100644 index 0000000000000000000000000000000000000000..340101130eb725d8a53e3559541c31dd27a5b248 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/miss/model.py @@ -0,0 +1,141 @@ +# 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 torch + +from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer +from peft.utils import ( + TRANSFORMERS_MODELS_TO_MISS_TARGET_MODULES_MAPPING, + get_quantization_kwargs, + resolve_quantization_backend, +) + +from .layer import MissLayer, MissLinear + + +def _get_tuner_layer_class(target_base_layer: torch.nn.Module) -> type[MissLayer] | None: + layer_cls: type[MissLayer] | None = None + if isinstance(target_base_layer, torch.nn.Linear): + layer_cls = MissLinear + elif (quant_backend := resolve_quantization_backend(target_base_layer)) is not None: + layer_cls = {"linear": MissLinear}.get(quant_backend.layer_type) + + return layer_cls + + +class MissModel(BaseTuner): + """ + Creates Householder reflection adaptation (MiSS) model from a pretrained model. The method is described in + https://huggingface.co/papers/2409.15371 + + Args: + model (`torch.nn.Module`): The model to which the adapter tuner layers will be attached. + config ([`MissConfig`]): The configuration of the MiSS 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 MiSS model. + + Example: + ```py + >>> from diffusers import StableDiffusionPipeline + >>> from peft import MissModel, MissConfig + + >>> config_te = MissConfig( + ... r=8, + ... target_modules=["k_proj", "q_proj", "v_proj", "out_proj", "fc1", "fc2"], + ... init_weights=True, + ... ) + >>> config_unet = MissConfig( + ... r=8, + ... target_modules=[ + ... "proj_in", + ... "proj_out", + ... "to_k", + ... "to_q", + ... "to_v", + ... "to_out.0", + ... "ff.net.0.proj", + ... "ff.net.2", + ... ], + ... init_weights=True, + ... ) + + >>> model = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5") + >>> model.text_encoder = MissModel(model.text_encoder, config_te, "default") + >>> model.unet = MissModel(model.unet, config_unet, "default") + ``` + + **Attributes**: + - **model** ([`~torch.nn.Module`]) -- The model to be adapted. + - **peft_config** ([`MissConfig`]): The configuration of the MiSS model. + """ + + prefix: str = "miss_" + tuner_layer_cls = MissLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_MISS_TARGET_MODULES_MAPPING + + def _create_and_replace( + self, + miss_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 = { + "r": miss_config.r, + "bias": bias, + } + kwargs.update(get_quantization_kwargs(self)) + + # If it is not a MissLayer, create a new module, else update it with new adapters + if not isinstance(target, MissLayer): + new_module = self._create_new_module(miss_config, adapter_name, target, **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, + config=miss_config, + **kwargs, + ) + + @staticmethod + def _create_new_module(miss_config, adapter_name, target, **kwargs): + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + layer_cls = _get_tuner_layer_class(target_base_layer) + if layer_cls is None: + raise TypeError( + f"Target module {target} is not supported. Currently, only `torch.nn.Linear` (optionally quantized) " + "is supported." + ) + + new_module = layer_cls(target, adapter_name, config=miss_config, **kwargs) + return new_module diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/mixed/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/mixed/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2955d7258ddcf76b47b38fd6fd5ebeb3d1d6110c --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/mixed/__init__.py @@ -0,0 +1,18 @@ +# 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 .model import COMPATIBLE_TUNER_TYPES, MixedModel + + +__all__ = ["COMPATIBLE_TUNER_TYPES", "MixedModel"] diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/mixed/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/mixed/model.py new file mode 100644 index 0000000000000000000000000000000000000000..460a1f1f698292de3e4015e422d08c2996552bc5 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/mixed/model.py @@ -0,0 +1,314 @@ +# 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 itertools import pairwise +from typing import Any, Optional, Union + +import torch +from torch import nn +from tqdm import tqdm + +from peft.tuners import adalora, loha, lokr, lora, oft, shira +from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer, _delete_auxiliary_adapter +from peft.utils import ( + TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING, + ModulesToSaveWrapper, + PeftType, + _get_submodules, +) +from peft.utils.other import _set_adapter + + +# Collection of constants used for all tuners +COMPATIBLE_TUNER_TYPES = (PeftType.LORA, PeftType.LOHA, PeftType.LOKR, PeftType.ADALORA, PeftType.OFT, PeftType.SHIRA) +PREFIXES = [ + lora.LoraModel.prefix, + lokr.LoKrModel.prefix, + loha.LoHaModel.prefix, + oft.OFTModel.prefix, + shira.ShiraModel.prefix, +] +Configs = Union[ + lora.LoraConfig, loha.LoHaConfig, lokr.LoKrConfig, adalora.AdaLoraConfig, oft.OFTConfig, shira.ShiraConfig +] +Layers = ( + lora.layer.LoraLayer, + loha.layer.LoHaLayer, + lokr.layer.LoKrLayer, + adalora.layer.AdaLoraLayer, + oft.OFTLayer, + shira.ShiraLayer, +) + + +class MixedModel(BaseTuner): + """ + A class that allows to mix different types of adapters in a single model. + + Note: This class should usually not be initialized directly. Instead, use `get_peft_model` with the argument + `mixed=True`. + + Args: + model (:obj:`nn.Module`): + The model to be tuned. + config (:obj:`PeftConfig`): + The config of the model to be tuned. The adapter type must be compatible. + adapter_name (:obj:`str`): + The name of the first adapter. + """ + + def __init__(self, model: nn.Module, config: Configs, adapter_name: str) -> None: + super().__init__(model, config, adapter_name) + + def _check_new_adapter_config(self, config: Configs) -> 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. + + """ + if not isinstance(config, Configs.__args__): + raise TypeError( + f"{self.__class__.__name__} only supports {COMPATIBLE_TUNER_TYPES} configs, but got {type(config)}." + ) + + super()._check_new_adapter_config(config) + + def _create_and_replace( + self, + config: Configs, + *args: Any, + **kwargs: Any, + ) -> None: + if isinstance(config, adalora.AdaLoraConfig): + adalora.AdaLoraModel._create_and_replace(self, config, *args, **kwargs) + elif isinstance(config, lora.LoraConfig): + lora.LoraModel._create_and_replace(self, config, *args, **kwargs) + elif isinstance(config, loha.LoHaConfig): + loha.LoHaModel._create_and_replace(self, config, *args, **kwargs) + elif isinstance(config, lokr.LoKrConfig): + lokr.LoKrModel._create_and_replace(self, config, *args, **kwargs) + elif isinstance(config, oft.OFTConfig): + oft.OFTModel._create_and_replace(self, config, *args, **kwargs) + elif isinstance(config, shira.ShiraConfig): + shira.ShiraModel._create_and_replace(self, config, *args, **kwargs) + else: + raise TypeError(f"Unsupported config type {type(config)}, should be one of {COMPATIBLE_TUNER_TYPES}.") + + def _replace_module(self, parent, child_name, new_module, child) -> None: + setattr(parent, child_name, new_module) + # It's not necessary to set requires_grad here, as that is handled by + # _mark_only_adapters_as_trainable + + # child layer wraps the original module, unpack it + if hasattr(child, "base_layer"): + child = child.get_base_layer() + elif hasattr(child, "quant_linear_module"): + # TODO maybe not necessary to have special treatment? + child = child.quant_linear_module + + if not hasattr(new_module, "base_layer"): + new_module.weight = child.weight + if hasattr(child, "bias"): + new_module.bias = child.bias + + if getattr(child, "state", None) is not None: + if hasattr(new_module, "base_layer"): + new_module.base_layer.state = child.state + else: + new_module.state = child.state + new_module.to(child.weight.device) + + meta = torch.device("meta") + # dispatch to correct device + for name, module in new_module.named_modules(): + if any(prefix in name for prefix in PREFIXES): + if hasattr(child, "qweight"): + weight = child.qweight + elif hasattr(child, "W_q"): + weight = child.W_q + elif hasattr(child, "weight"): + weight = child.weight + elif getattr(child, "in_proj_weight", None) is not None: # MHA + weight = child.in_proj_weight + else: + weight = next(child.parameters()) + + if not any(p.device == meta for p in module.parameters()): + module.to(weight.device) + + def _mark_only_adapters_as_trainable(self, model: nn.Module) -> None: + for n, p in model.named_parameters(): + if not any(prefix in n for prefix in PREFIXES): + p.requires_grad = False + + for active_adapter in self.active_adapters: + bias = getattr(self.peft_config[active_adapter], "bias", "none") + if bias == "none": + continue + + if bias == "all": + for n, p in model.named_parameters(): + if "bias" in n: + p.requires_grad = True + elif bias == "lora_only": + # TODO: check if this is needed for other supported types + for m in model.modules(): + if isinstance(m, Layers) and hasattr(m, "bias") and m.bias is not None: + m.bias.requires_grad = True + else: + raise ValueError(f"Requested bias: {bias}, is not implemented.") + + @staticmethod + def _create_new_module(config, adapter_name, target, **kwargs): + gptq_quantization_config = kwargs.get("gptq_quantization_config", None) + if gptq_quantization_config is not None: + raise ValueError(f"GPTQ quantization not supported for {config.peft_type.value} (yet).") + + loaded_in_8bit = kwargs.pop("loaded_in_8bit", False) + loaded_in_4bit = kwargs.pop("loaded_in_4bit", False) + if loaded_in_8bit or loaded_in_4bit: + raise ValueError(f"8bit and 4bit quantization not supported for {config.peft_type.value} (yet).") + + if isinstance(config, adalora.AdaLoraConfig): + new_module = adalora.AdaLoraModel._create_new_module(config, adapter_name, target, **kwargs) + elif isinstance(config, lora.LoraConfig): + new_module = lora.LoraModel._create_new_module(config, adapter_name, target, **kwargs) + elif isinstance(config, loha.LoHaConfig): + new_module = loha.LoHaModel._create_new_module(config, adapter_name, target, **kwargs) + elif isinstance(config, lokr.LoKrConfig): + new_module = lokr.LoKrModel._create_new_module(config, adapter_name, target, **kwargs) + elif isinstance(config, oft.OFTConfig): + new_module = oft.OFTModel._create_new_module(config, adapter_name, target, **kwargs) + elif isinstance(config, shira.ShiraConfig): + new_module = shira.ShiraModel._create_new_module(config, adapter_name, target, **kwargs) + else: + raise TypeError(f"Unknown config type {type(config)}, should be one of {COMPATIBLE_TUNER_TYPES}.") + return new_module + + def set_adapter(self, adapter_name: Union[str, list[str]], inference_mode: bool = False) -> None: + _set_adapter(self, adapter_name, inference_mode=inference_mode) # handle auxiliary modules + for module in self.model.modules(): + if isinstance(module, Layers): + if module.merged: + warnings.warn("Adapter cannot be set when the model is merged. Unmerging the model first.") + module.unmerge() + module.set_adapter(adapter_name, inference_mode=inference_mode) + self.active_adapter = adapter_name + + @staticmethod + def _prepare_adapter_config(peft_config, model_config): + if peft_config.target_modules is None: + if model_config["model_type"] not in TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING: + raise ValueError("Please specify `target_modules` in `peft_config`") + + peft_config.target_modules = set( + TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING[model_config["model_type"]] + ) + return peft_config + + def _unload_and_optionally_merge( + self, + merge=True, + progressbar: bool = False, + safe_merge: bool = False, + adapter_names: Optional[list[str]] = None, + ): + if merge: + if getattr(self.model, "quantization_method", None) == "gptq": + raise ValueError("Cannot merge layers when the model is gptq quantized") + + def merge_recursively(module): + # helper function to recursively merge the base_layer of the target + path = [] + layer = module + while hasattr(layer, "base_layer"): + path.append(layer) + layer = layer.base_layer + for layer_before, layer_after in pairwise(path): + layer_after.merge(safe_merge=safe_merge, adapter_names=adapter_names) + layer_before.base_layer = layer_after.base_layer + module.merge(safe_merge=safe_merge, adapter_names=adapter_names) + + key_list = [key for key, _ in self.model.named_modules() if not any(prefix in key for prefix in PREFIXES)] + desc = "Unloading " + ("and merging " if merge else "") + "model" + + for key in tqdm(key_list, disable=not progressbar, desc=desc): + try: + parent, target, target_name = _get_submodules(self.model, key) + except AttributeError: + continue + + if hasattr(target, "base_layer"): + if merge: + merge_recursively(target) + self._replace_module(parent, target_name, target.get_base_layer(), target) + elif isinstance(target, ModulesToSaveWrapper): + # save any additional trainable modules part of `modules_to_save` + new_module = target.modules_to_save[target.active_adapter] + if hasattr(new_module, "base_layer"): + # check if the module is itself a tuner layer + if merge: + new_module.merge(safe_merge=safe_merge, adapter_names=adapter_names) + new_module = new_module.get_base_layer() + setattr(parent, target_name, new_module) + + # Clean up peft_config from the model since all PEFT modules have been removed. + # This prevents spurious warnings when re-wrapping the model with get_peft_model(). + if hasattr(self.model, "peft_config"): + del self.model.peft_config + + return self.model + + def add_weighted_adapter(self, *args: Any, **kwargs: Any) -> None: + raise NotImplementedError(f"Weighted adapters are not supported for {self.__class__.__name__} (yet).") + + def delete_adapter(self, adapter_name: Union[str, list[str]]) -> None: + """ + Deletes an existing adapter. + + Args: + adapter_name (Union[str, list[str]]): Name of the adapter(s) to delete. + """ + if isinstance(adapter_name, str): + adapter_names = [adapter_name] + else: + adapter_names = adapter_name + + mismatched = set(adapter_names) - set(self.peft_config.keys()) + if mismatched: + raise ValueError( + f"Adapter(s) {sorted(mismatched)} not found, available adapters: {sorted(self.peft_config.keys())}" + ) + + for adapter_to_delete in adapter_names: + del self.peft_config[adapter_to_delete] + + key_list = [key for key, _ in self.model.named_modules() if not any(prefix in key for prefix in PREFIXES)] + new_adapter = None + for key in key_list: + _, target, _ = _get_submodules(self.model, key) + if isinstance(target, BaseTunerLayer): + target.delete_adapter(adapter_to_delete) + if new_adapter is None: + new_adapter = target.active_adapters[:] + + self.active_adapter = new_adapter or [] + if adapter_to_delete in adapter_names: + _delete_auxiliary_adapter(self.model, adapter_to_delete, new_active_adapters=new_adapter) + + def generate(self, *args: Any, **kwargs: Any): + return self.model.generate(*args, **kwargs) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/multitask_prompt_tuning/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/multitask_prompt_tuning/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fe692a93378254601753cc9b17218fdd5a92b8de --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/multitask_prompt_tuning/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/multitask_prompt_tuning/config.py new file mode 100644 index 0000000000000000000000000000000000000000..6cb279573559e4fa33a973aa35e052647a6ab8f9 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/multitask_prompt_tuning/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/multitask_prompt_tuning/model.py new file mode 100644 index 0000000000000000000000000000000000000000..20d9d498f48c4f3bc7087c38b4f8072d8de66637 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/oft/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/oft/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..32e21e32f64b02315731642542cf0bf31227d7a4 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/oft/aqlm.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/oft/aqlm.py new file mode 100644 index 0000000000000000000000000000000000000000..42d967b59837cd684d560419e3dbd36da74194ef --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/oft/aqlm.py @@ -0,0 +1,92 @@ +# 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 + +from .config import OFTConfig + + +if is_aqlm_available(): + from aqlm import QuantizedLinear + + +class AqlmOFTLinear(torch.nn.Module, OFTLayer): + def __init__( + self, + base_layer, + adapter_name: str, + config: OFTConfig, + r: int = 0, + **kwargs, + ): + super().__init__() + OFTLayer.__init__(self, base_layer) + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + r, + config=config, + ) + + 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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/oft/awq.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/oft/awq.py new file mode 100644 index 0000000000000000000000000000000000000000..78f30f9f0e4dbc69fe902aa00599ae08a97de6e4 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/oft/awq.py @@ -0,0 +1,92 @@ +# 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 +from peft.utils.other import is_gptqmodel_awq_layer + +from .config import OFTConfig + + +class AwqOFTLinear(torch.nn.Module, OFTLayer): + def __init__( + self, + base_layer, + adapter_name: str, + config: OFTConfig, + r: int = 0, + **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, + config=config, + ) + + 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() and is_gptqmodel_awq_layer(target_base_layer): + new_module = AwqOFTLinear(target, adapter_name, **kwargs) + target.qweight = target_base_layer.qweight + + return new_module diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/oft/bnb.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/oft/bnb.py new file mode 100644 index 0000000000000000000000000000000000000000..7fdf3a8b9628d1d6919a3c2e35fb49b480c346b4 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/oft/bnb.py @@ -0,0 +1,361 @@ +# 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 .config import OFTConfig +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, + config: OFTConfig, + r: int = 8, + **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, + config=config, + ) + + 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, + config: OFTConfig, + r: int = 8, + **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, + config=config, + ) + + 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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/oft/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/oft/config.py new file mode 100644 index 0000000000000000000000000000000000000000..9c62e1becea23cd3ca0f0d568f8c176d96c70a78 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/oft/eetq.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/oft/eetq.py new file mode 100644 index 0000000000000000000000000000000000000000..f118166d5b0a6725c2a6f6e4e1a7565afec441fc --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/oft/eetq.py @@ -0,0 +1,102 @@ +# 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 + +from .config import OFTConfig + + +if is_eetq_available(): + from eetq import EetqLinear + + class EetqOFTLinear(torch.nn.Module, OFTLayer): + def __init__( + self, + base_layer, + adapter_name: str, + config: OFTConfig, + r: int = 0, + **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, + config=config, + ) + + 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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/oft/gptq.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/oft/gptq.py new file mode 100644 index 0000000000000000000000000000000000000000..530b8c07382e1cf67816c9da6388926553eeb81c --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/oft/gptq.py @@ -0,0 +1,94 @@ +# 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 + +from .config import OFTConfig + + +class GPTQOFTLinear(torch.nn.Module, OFTLayer): + def __init__( + self, + base_layer, + adapter_name: str, + config: OFTConfig, + r: int = 8, + **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, + config=config, + ) + + 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, + oft_config: OFTConfig, + **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, config=oft_config, **kwargs) + target.qweight = target_base_layer.qweight + + return new_module diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/oft/hqq.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/oft/hqq.py new file mode 100644 index 0000000000000000000000000000000000000000..140e48b05bc594be3e36b827a74335d99e0b5b32 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/oft/hqq.py @@ -0,0 +1,173 @@ +# 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 .config import OFTConfig +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, + config: OFTConfig, + r: int = 8, + **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, + config=config, + ) + + 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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/oft/inc.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/oft/inc.py new file mode 100644 index 0000000000000000000000000000000000000000..6ed855bc7dc65af10d77a2f486abb8fc27c12dd5 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/oft/layer.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/oft/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..a42476ad61d6169c24b6c0d45c166e08f237d1f6 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/oft/layer.py @@ -0,0 +1,1189 @@ +# 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 torch +import torch.nn.functional as F +from torch import nn + +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge +from peft.utils.other import is_gptqmodel_quant_linear + +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_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 is_gptqmodel_quant_linear(base_layer): + # GPT-QModel quantized linears + 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, + config: OFTConfig, + 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. + """ + oft_block_size = config.oft_block_size + module_dropout = config.module_dropout + coft = config.coft + eps = config.eps + block_share = config.block_share + init_weights = config.init_weights + use_cayley_neumann = config.use_cayley_neumann + num_cayley_neumann_terms = config.num_cayley_neumann_terms + + # 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, + config: OFTConfig, + r: int = 8, + 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, + **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, + config=config, + ) + 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, + config: OFTConfig, + r: int = 8, + fan_in_fan_out: bool = False, # Set this to True if the layer to replace stores weight like (fan_in, fan_out) + **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, + config=config, + ) + + def update_layer( + self, + adapter_name, + r, + config: OFTConfig, + inference_mode: bool = False, + **kwargs, + ): + """ + Update the conv2d layer with trainable OFT weights. + """ + oft_block_size = config.oft_block_size + module_dropout = config.module_dropout + coft = config.coft + eps = config.eps + block_share = config.block_share + init_weights = config.init_weights + use_cayley_neumann = config.use_cayley_neumann + num_cayley_neumann_terms = config.num_cayley_neumann_terms + + # 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, + config: OFTConfig, + r: int = 8, + fan_in_fan_out: bool = False, + **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, + config=config, + ) + + def update_layer( + self, + adapter_name: str, + r: int, + config: OFTConfig, + inference_mode: bool = False, + **kwargs, + ): + oft_block_size = config.oft_block_size + coft = config.coft + eps = config.eps + block_share = config.block_share + init_weights = config.init_weights + use_cayley_neumann = config.use_cayley_neumann + num_cayley_neumann_terms = config.num_cayley_neumann_terms + + 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, config=oft_config, **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, config=oft_config, **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, config=oft_config, **embedding_kwargs) + + return new_module diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/oft/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/oft/model.py new file mode 100644 index 0000000000000000000000000000000000000000..9ac738e3146873a9c57a977a0fc13b1430f5e177 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/oft/model.py @@ -0,0 +1,185 @@ +# 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, + "fan_in_fan_out": oft_config.fan_in_fan_out, + "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, + config=oft_config, + ) + + @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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/osf/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/osf/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..801e93fc5380e6fc2ae48798e6650a9a41cb2dcc --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/osf/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/osf/config.py new file mode 100644 index 0000000000000000000000000000000000000000..77a08964d4fce411870e088879f6a5a8b4d993c8 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/osf/layer.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/osf/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..8f74377db817192ce60a7dd7f95bea138bc1c958 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/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.functional as F +from torch import nn + +from peft.tuners._buffer_dict import BufferDict +from peft.tuners.tuners_utils import BaseTunerLayer + +from .config import OSFConfig +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, config: OSFConfig, **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, + config: OSFConfig, + effective_rank: Optional[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, config=config, **kwargs) + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + if self.disable_adapters or 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: OSFConfig, + **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, config=osf_config, **kwargs) + + return new_module diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/osf/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/osf/model.py new file mode 100644 index 0000000000000000000000000000000000000000..9a55351638e80d66f95d5c04b429d59993e69da2 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/osf/model.py @@ -0,0 +1,124 @@ +from __future__ import annotations + +import re + +import torch +from torch import 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 + + # 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, config=osf_config, **kwargs) + else: + new_module = dispatch_default(target, adapter_name, osf_config, **kwargs) + if new_module is None: + return + # 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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/osf/utils.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/osf/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0030e22b09da586e3327a646ad91541b8b69bcb1 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/p_tuning/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/p_tuning/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9195c0d75d3d11e752d0477b64edd79599bdaa01 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/p_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 PromptEncoderConfig, PromptEncoderReparameterizationType +from .model import PromptEncoder + + +__all__ = ["PromptEncoder", "PromptEncoderConfig", "PromptEncoderReparameterizationType"] + +register_peft_method(name="p_tuning", config_cls=PromptEncoderConfig, model_cls=PromptEncoder) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/p_tuning/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/p_tuning/config.py new file mode 100644 index 0000000000000000000000000000000000000000..a69c13db9c8a0f57a7daa7d312472625251fb6c8 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/p_tuning/config.py @@ -0,0 +1,60 @@ +# 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 Union + +from peft.config import PromptLearningConfig +from peft.utils import PeftType + + +class PromptEncoderReparameterizationType(str, enum.Enum): + MLP = "MLP" + LSTM = "LSTM" + + +@dataclass +class PromptEncoderConfig(PromptLearningConfig): + """ + This is the configuration class to store the configuration of a [`PromptEncoder`]. + + Args: + encoder_reparameterization_type (Union[[`PromptEncoderReparameterizationType`], `str`]): + The type of reparameterization to use. + encoder_hidden_size (`int`): The hidden size of the prompt encoder. + encoder_num_layers (`int`): The number of layers of the prompt encoder. + encoder_dropout (`float`): The dropout probability of the prompt encoder. + """ + + encoder_reparameterization_type: Union[str, PromptEncoderReparameterizationType] = field( + default=PromptEncoderReparameterizationType.MLP, + metadata={"help": "How to reparameterize the prompt encoder"}, + ) + encoder_hidden_size: int = field( + default=None, + metadata={"help": "The hidden size of the prompt encoder"}, + ) + encoder_num_layers: int = field( + default=2, + metadata={"help": "The number of layers of the prompt encoder"}, + ) + encoder_dropout: float = field( + default=0.0, + metadata={"help": "The dropout of the prompt encoder"}, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.P_TUNING diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/p_tuning/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/p_tuning/model.py new file mode 100644 index 0000000000000000000000000000000000000000..ade2b1128158376c134441687803b85d444cfb96 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/p_tuning/model.py @@ -0,0 +1,130 @@ +# 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/NVIDIA/NeMo/blob/main/nemo/collections/nlp/modules/common/prompt_encoder.py +# with some refactor +import warnings + +import torch + +from .config import PromptEncoderConfig, PromptEncoderReparameterizationType + + +class PromptEncoder(torch.nn.Module): + """ + The prompt encoder network that is used to generate the virtual token embeddings for p-tuning. + + Args: + config ([`PromptEncoderConfig`]): The configuration of the prompt encoder. + + Example: + + ```py + >>> from peft import PromptEncoder, PromptEncoderConfig + + >>> config = PromptEncoderConfig( + ... peft_type="P_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_reparameterization_type="MLP", + ... encoder_hidden_size=768, + ... ) + + >>> prompt_encoder = PromptEncoder(config) + ``` + + **Attributes**: + - **embedding** (`torch.nn.Embedding`) -- The embedding layer of the prompt encoder. + - **mlp_head** (`torch.nn.Sequential`) -- The MLP head of the prompt encoder if `inference_mode=False`. + - **lstm_head** (`torch.nn.LSTM`) -- The LSTM head of the prompt encoder if `inference_mode=False` and + `encoder_reparameterization_type="LSTM"`. + - **token_dim** (`int`) -- The hidden embedding dimension of the base transformer model. + - **input_size** (`int`) -- The input size of the prompt encoder. + - **output_size** (`int`) -- The output size of the prompt encoder. + - **hidden_size** (`int`) -- The hidden size of the prompt encoder. + - **total_virtual_tokens** (`int`): The total number of virtual tokens of the + prompt encoder. + - **encoder_type** (Union[[`PromptEncoderReparameterizationType`], `str`]): The encoder type of the prompt + encoder. + + + Input shape: (`batch_size`, `total_virtual_tokens`) + + Output shape: (`batch_size`, `total_virtual_tokens`, `token_dim`) + """ + + def __init__(self, config): + super().__init__() + self.token_dim = config.token_dim + self.input_size = self.token_dim + self.output_size = self.token_dim + self.hidden_size = config.encoder_hidden_size + self.total_virtual_tokens = config.num_virtual_tokens * config.num_transformer_submodules + self.encoder_type = config.encoder_reparameterization_type + + # embedding + self.embedding = torch.nn.Embedding(self.total_virtual_tokens, self.token_dim) + if not config.inference_mode: + if self.encoder_type == PromptEncoderReparameterizationType.LSTM: + lstm_dropout = config.encoder_dropout + num_layers = config.encoder_num_layers + # LSTM + self.lstm_head = torch.nn.LSTM( + input_size=self.input_size, + hidden_size=self.hidden_size, + num_layers=num_layers, + dropout=lstm_dropout, + bidirectional=True, + batch_first=True, + ) + + self.mlp_head = torch.nn.Sequential( + torch.nn.Linear(self.hidden_size * 2, self.hidden_size * 2), + torch.nn.ReLU(), + torch.nn.Linear(self.hidden_size * 2, self.output_size), + ) + + elif self.encoder_type == PromptEncoderReparameterizationType.MLP: + encoder_num_layers_default = PromptEncoderConfig.encoder_num_layers + if config.encoder_num_layers != encoder_num_layers_default: + warnings.warn( + f"for {self.encoder_type.value}, the argument `encoder_num_layers` is ignored. " + f"Exactly {encoder_num_layers_default} MLP layers are used." + ) + layers = [ + torch.nn.Linear(self.input_size, self.hidden_size), + torch.nn.ReLU(), + torch.nn.Linear(self.hidden_size, self.hidden_size), + torch.nn.ReLU(), + torch.nn.Linear(self.hidden_size, self.output_size), + ] + self.mlp_head = torch.nn.Sequential(*layers) + + else: + raise ValueError("Prompt encoder type not recognized. Please use one of MLP (recommended) or LSTM.") + + def forward(self, indices): + input_embeds = self.embedding(indices) + if self.encoder_type == PromptEncoderReparameterizationType.LSTM: + output_embeds = self.mlp_head(self.lstm_head(input_embeds)[0]) + elif self.encoder_type == PromptEncoderReparameterizationType.MLP: + output_embeds = self.mlp_head(input_embeds) + else: + raise ValueError("Prompt encoder type not recognized. Please use one of MLP (recommended) or LSTM.") + + return output_embeds diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/peanut/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/peanut/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cd278f2aaae94966c6388349453615f782a9b152 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/peanut/__init__.py @@ -0,0 +1,27 @@ +# Copyright 2026-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 PeftType, register_peft_method + +from .config import PeanutConfig +from .layer import Linear, PeanutLayer +from .model import PeanutModel + + +__all__ = ["Linear", "PeanutConfig", "PeanutLayer", "PeanutModel"] + +if "PEANUT" in PeftType.__members__: + register_peft_method( + name="peanut", config_cls=PeanutConfig, model_cls=PeanutModel, prefix="peanut_", is_mixed_compatible=False + ) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/peanut/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/peanut/config.py new file mode 100644 index 0000000000000000000000000000000000000000..c3d1697d7349947a9675f6470ca5458751a49b62 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/peanut/config.py @@ -0,0 +1,192 @@ +# Copyright 2026-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 transformers.activations import ACT2FN + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class PeanutConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`PeanutModel`]. + + Args: + r (`int`): + PEANuT rank. This is the hidden dimension used by the adapters. Similar to LoRA rank, larger `r` increases + adapter capacity and trainable parameters. + depth (`int`): + Number of hidden adapter layers per encoder/decoder side in PEANuT. The input projection `A` and output + projection `B` are always present in addition to these hidden layers. Therefore, `depth` must be a + non-negative integer. + + - `depth=0`: `A`, `B`. + - `depth=1`: `A`, one encoder, one decoder, `B`. + - `depth=2`: `A`, two encoders, two decoders, `B`. + - `depth=3`: `A`, three encoders, three decoders, `B`, etc. + act_fn (`str`): + Non-linear activation applied in the PEANuT network. This corresponds to `non_linear` in the vanilla + PyTorch implementation. Default is `"relu"`. Any activation key available in + `transformers.activations.ACT2FN` is supported and may perform better on different tasks. + scaling (`float`): + A scalar multiplier applied to the PEANuT output before adding it to the frozen base layer output. The + final adapter contribution is `scaling * (x @ delta_w)`. + target_modules (`Union[List[str], str]`, *optional*): + The names of the modules to apply PEANuT to. Can be a list of module name strings (e.g. `['q_proj', + 'v_proj']`) or a regex pattern. + modules_to_save (`List[str]`, *optional*): + List of modules apart from PEANuT layers to be set as trainable and saved in the final checkpoint. + exclude_modules (`Union[List[str], str]`, *optional*): + 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. + layers_to_transform (`Union[list[int], int]`, *optional*): + The layer indexes to transform. If this argument is specified, PEFT will transform only the layer indexes + that are specified in this list. If a single integer is passed, PEFT will transform only the layer at this + index. + layers_pattern (`Optional[Union[List[str], str]]`, *optional*): + The layer pattern name, used only if `layers_to_transform` is not None and if the layer pattern is not in + the common layers pattern. + init_weights (`bool`): + Whether to initialize PEANuT adapter weights using the default initialization scheme: + + - If `True`: all weights except `B` are initialized with Kaiming uniform, and `B` is initialized to zero. + - If `False`: all weights (including `B`) are initialized with Kaiming uniform. + + Initializing `B` to zero makes the adapter start as an exact no-op. + + Notes: + PEANuT uses a weight-aware pathway, where the delta weight is conditioned on the base weight. The `A` adapter + is applied over the base weight's output dimension, so `A` has shape `(out_dim -> r)` rather than the usual + `(in_dim -> r)` used by LoRA-like methods. + """ + + r: int = field( + default=32, + metadata={ + "help": ( + "PEANuT rank. This is the hidden dimension used by the adapter stack. Similar to LoRA rank, larger " + "`r` increases adapter capacity and trainable parameters." + ) + }, + ) + depth: int = field( + default=0, + metadata={ + "help": ( + "Number of hidden adapter layers per encoder/decoder side in PEANuT. The input projection `A` and " + "output projection `B` are added automatically, so `depth` must be a non-negative integer." + ) + }, + ) + act_fn: str = field( + default="relu", + metadata={ + "help": ( + "Non-linear activation applied in the PEANuT pathway. This corresponds to `non_linear` in the " + "vanilla implementation. Must be a key in `transformers.activations.ACT2FN`." + ) + }, + ) + scaling: float = field( + default=1.0, + metadata={ + "help": ( + "A scalar multiplier applied to the PEANuT output before adding it to the frozen base layer output. " + "The final adapter contribution is `scaling * (x @ delta_w)`." + ) + }, + ) + 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 PEANuT. " + "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'. " + "If not specified, PEANuT will use architecture-specific default target modules." + ) + }, + ) + 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 PEANuT. " + "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: Optional[list[str]] = field( + default=None, + metadata={ + "help": ( + "List of modules apart from PEANuT layers to be set as trainable and saved in the final checkpoint." + ) + }, + ) + layers_to_transform: Optional[Union[list[int], int]] = field( + default=None, + metadata={ + "help": ( + "The layer indexes to transform, if 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'`." + ) + }, + ) + init_weights: bool = field( + default=True, + metadata={ + "help": ( + "Whether to initialize PEANuT adapter weights using the default initialization scheme: if `True`, " + "all weights except `B` are initialized with Kaiming uniform and `B` is initialized to zero; if " + "`False`, all weights including `B` are initialized with Kaiming uniform." + ) + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.PEANUT + 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 + ) + 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: + raise ValueError("`r` must be a positive integer.") + if self.depth < 0: + raise ValueError("`depth` can only be a non-negative integer.") + if self.act_fn not in ACT2FN: + raise ValueError(f"Unsupported `act_fn`: {self.act_fn}. Must be one of {sorted(ACT2FN.keys())}.") diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/peanut/layer.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/peanut/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..ca61fcd675c9ab5bc0237115223df70023e74dc2 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/peanut/layer.py @@ -0,0 +1,242 @@ +# Copyright 2026-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 warnings +from typing import Any, Optional + +import torch +from torch import nn +from transformers.activations import ACT2FN + +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge + +from .config import PeanutConfig + + +class PeanutLayer(BaseTunerLayer): + # All names of layers that may contain (trainable) adapter weights + adapter_layer_names: tuple[str, ...] = ("peanut_A", "peanut_B", "peanut_encoders", "peanut_decoders") + # All names of other parameters that may contain adapter-related parameters + other_param_names: tuple[str, ...] = ("r", "depth", "scaling", "act_fn", "res_num") + + def __init__(self, base_layer: nn.Module, **kwargs) -> None: + self.base_layer = base_layer + self.r = {} + self.depth = {} + self.res_num = {} + self.scaling = {} + self.act_fn = {} + self.peanut_A = nn.ModuleDict({}) + self.peanut_B = nn.ModuleDict({}) + self.peanut_encoders = nn.ModuleDict({}) + self.peanut_decoders = nn.ModuleDict({}) + self.kwargs = kwargs + + self._disable_adapters = False + self.merged_adapters = [] + self._cached_delta_weights = {} + + 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: + 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 update_layer( + self, + adapter_name: str, + r: int, + config: PeanutConfig, + ) -> None: + depth = config.depth + scaling = config.scaling + act_fn = config.act_fn + init_weights = config.init_weights + inference_mode = config.inference_mode + + self.r[adapter_name] = r + self.depth[adapter_name] = depth + self.res_num[adapter_name] = depth + self.scaling[adapter_name] = scaling + self.act_fn[adapter_name] = act_fn + + self.peanut_A[adapter_name] = nn.Linear(self.out_features, r, bias=False) + self.peanut_encoders[adapter_name] = nn.ModuleList([nn.Linear(r, r, bias=False) for _ in range(depth)]) + self.peanut_decoders[adapter_name] = nn.ModuleList([nn.Linear(r, r, bias=False) for _ in range(depth)]) + + self.peanut_B[adapter_name] = nn.Linear(r, self.out_features, bias=False) + + self.reset_peanut_parameters(adapter_name, init_weights=init_weights) + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def reset_peanut_parameters(self, adapter_name: str, init_weights: bool = True): + if adapter_name not in self.peanut_A: + return + + nn.init.kaiming_uniform_(self.peanut_A[adapter_name].weight, a=math.sqrt(5)) + for encoder in self.peanut_encoders[adapter_name]: + nn.init.kaiming_uniform_(encoder.weight, a=math.sqrt(5)) + for decoder in self.peanut_decoders[adapter_name]: + nn.init.kaiming_uniform_(decoder.weight, a=math.sqrt(5)) + + if init_weights: + nn.init.zeros_(self.peanut_B[adapter_name].weight) + else: + nn.init.kaiming_uniform_(self.peanut_B[adapter_name].weight, a=math.sqrt(5)) + + +class Linear(nn.Module, PeanutLayer): + # PEANuT implemented in a dense layer + def __init__( + self, + base_layer, + adapter_name: str, + r: int, + config: PeanutConfig, + **kwargs, + ) -> None: + super().__init__() + PeanutLayer.__init__(self, base_layer, **kwargs) + + self._active_adapter = adapter_name + + self.update_layer(adapter_name, r, config=config) + + def _compute_delta_weight(self, adapter: str, base_weight: torch.Tensor) -> torch.Tensor: + if adapter not in self.peanut_A: + raise ValueError(f"Adapter {adapter} not found.") + + peanut_A = self.peanut_A[adapter] + peanut_B = self.peanut_B[adapter] + non_linear = ACT2FN[self.act_fn[adapter]] + scaling = self.scaling[adapter] + res_num = self.res_num[adapter] + peanut_encoders = self.peanut_encoders[adapter] + peanut_decoders = self.peanut_decoders[adapter] + + base_weight_t = base_weight.transpose(0, 1).to(peanut_A.weight.dtype) + delta_w = non_linear(torch.matmul(base_weight_t, peanut_A.weight.t())) + + residuals = [] + for i in range(res_num): + residuals.append(delta_w) + encoder = peanut_encoders[i] + delta_w = non_linear(encoder(delta_w)) + + for i in range(res_num): + decoder = peanut_decoders[i] + delta_w = non_linear(decoder(delta_w)) + delta_w = delta_w + residuals[res_num - 1 - i] + + delta_w = peanut_B(delta_w) + return (delta_w * scaling).transpose(0, 1) + + def get_delta_weight(self, adapter) -> torch.Tensor: + base_weight = self.get_base_layer().weight + return self._compute_delta_weight(adapter, base_weight) + + 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: + return + + base_layer = self.get_base_layer() + merge_base_weight = base_layer.weight.data.detach().clone() + + for active_adapter in adapter_names: + if active_adapter not in self.peanut_A: + continue + + with torch.no_grad(): + delta_weight = self._compute_delta_weight(active_adapter, merge_base_weight) + delta_weight = delta_weight.to(dtype=base_layer.weight.dtype, device=base_layer.weight.device) + + if safe_merge: + orig_weights = base_layer.weight.data.clone() + orig_weights = orig_weights + delta_weight + + 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.add_(delta_weight) + + if delta_weight.device.type != "cpu": + cached_delta_weight = delta_weight.detach().to("cpu") + else: + cached_delta_weight = delta_weight.detach() + self._cached_delta_weights[active_adapter] = cached_delta_weight + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + base_layer = self.get_base_layer() + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter not in self.peanut_A: + continue + + delta_weight = self._cached_delta_weights.pop(active_adapter, None) + if delta_weight is None: + raise ValueError(f"Cached delta weight for adapter '{active_adapter}' is missing; cannot unmerge.") + + base_layer.weight.data.sub_( + delta_weight.to(dtype=base_layer.weight.dtype, device=base_layer.weight.device) + ) + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> 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) + + if self.active_adapters: + torch_result_dtype = result.dtype + + for active_adapter in self.active_adapters: + if active_adapter not in self.peanut_A: + continue + + delta_weight = self.get_delta_weight(active_adapter) + x_cast = self._cast_input_dtype(x, delta_weight.dtype) + delta = torch.matmul(x_cast, delta_weight.transpose(0, 1)) + result = result + delta.to(torch_result_dtype) + + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "peanut." + rep diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/peanut/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/peanut/model.py new file mode 100644 index 0000000000000000000000000000000000000000..5d24d9fd0627bccee6ad16cec16dc6df47fafd74 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/peanut/model.py @@ -0,0 +1,91 @@ +# Copyright 2026-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 + +from peft.tuners.tuners_utils import ( + BaseTuner, + BaseTunerLayer, +) +from peft.utils import TRANSFORMERS_MODELS_TO_PEANUT_TARGET_MODULES_MAPPING + +from .layer import Linear, PeanutLayer + + +class PeanutModel(BaseTuner): + """ + Creates a PEANuT model from a pretrained transformers model. + + The method is described in detail in https://arxiv.org/abs/2410.01870. + + Args: + model ([`torch.nn.Module`]): The model to be adapted. + config ([`PeanutConfig`]): The configuration of the PEANuT model. + adapter_name (`str`): The name of the adapter, defaults to `"default"`. + + Returns: + `torch.nn.Module`: The PEANuT PEFT model. + + **Attributes**: + - **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted. + - **peft_config** ([`PeanutConfig`]): The configuration of the PEANuT model. + """ + + prefix: str = "peanut_" + tuner_layer_cls = PeanutLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_PEANUT_TARGET_MODULES_MAPPING + + def _create_and_replace( + self, + peanut_config, + adapter_name, + target, + target_name, + parent, + current_key, + **optional_kwargs, + ): + if current_key is None: + raise ValueError("Current Key shouldn't be `None`") + + if isinstance(target, PeanutLayer): + target.update_layer( + adapter_name, + peanut_config.r, + config=peanut_config, + ) + else: + new_module = self._create_new_module(peanut_config, adapter_name, target) + if adapter_name not in self.active_adapters: + new_module.requires_grad_(False) + self._replace_module(parent, target_name, new_module, target) + + @staticmethod + def _create_new_module(peanut_config, adapter_name, target): + 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, + r=peanut_config.r, + config=peanut_config, + ) + + raise NotImplementedError(f"PEANuT does not support target modules of type {type(target_base_layer)} yet.") diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/poly/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/poly/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1c18933eba3fa44106ba9fa89ba34ecd12a2bed4 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/poly/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/poly/config.py new file mode 100644 index 0000000000000000000000000000000000000000..c4a77bc5db447edd4ba97c1b1c407f3cfc620cb4 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/poly/layer.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/poly/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..cceb41f05c84a198fef0a4c4b4a4a30d6466dc15 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/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 +from torch import 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 TypeError(f"Unsupported layer type {type(base_layer)}") + + self.in_features = in_features + self.out_features = out_features + + def update_layer(self, adapter_name, config: PolyConfig, inference_mode: bool = False, **kwargs): + if config.r <= 0: + raise ValueError(f"`r` should be a positive integer value but the value passed is {config.r}") + + self.r[adapter_name] = config.r + self.n_tasks[adapter_name] = config.n_tasks + self.n_skills[adapter_name] = config.n_skills + self.n_splits[adapter_name] = config.n_splits + self.poly_type[adapter_name] = config.poly_type + + self.poly_lora_A[adapter_name] = nn.Parameter( + torch.empty( + config.n_splits, + config.n_skills, + self.in_features // config.n_splits, + config.r, + ) + ) + self.poly_lora_B[adapter_name] = nn.Parameter( + torch.empty( + config.n_splits, + config.n_skills, + config.r, + self.out_features // config.n_splits, + ) + ) + self.poly_router[adapter_name] = get_router(config) + + self.reset_poly_parameters(adapter_name, init_weights=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, config=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, _, _ = 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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/poly/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/poly/model.py new file mode 100644 index 0000000000000000000000000000000000000000..7a831f56ccbc2b35ef219f476849cbe17a374b84 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/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, config=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 TypeError( + 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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/poly/router.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/poly/router.py new file mode 100644 index 0000000000000000000000000000000000000000..3dda3e75e35b6a9fbd5a2412815a0f05421f2ef4 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/prefix_tuning/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/prefix_tuning/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..939f74d3f689f400dfdcb0139f4a2cf04cce52fc --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/prefix_tuning/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/prefix_tuning/config.py new file mode 100644 index 0000000000000000000000000000000000000000..37a7ac5e1de744ca0aac7464de9127502b7db97b --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/prefix_tuning/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/prefix_tuning/model.py new file mode 100644 index 0000000000000000000000000000000000000000..5ff6dbeeb0d17fc6cc9e23d7ac66a044adf798e9 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/prompt_tuning/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/prompt_tuning/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c99ca6a26fea22e3d829c16eec378e82633e1b7b --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/prompt_tuning/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/prompt_tuning/config.py new file mode 100644 index 0000000000000000000000000000000000000000..b41669efe898e88dfd015042e0c78258fb9b3a14 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/prompt_tuning/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/prompt_tuning/model.py new file mode 100644 index 0000000000000000000000000000000000000000..3c6fc50d156fa98d2c8ebf8f1aaaa5a6fa1b7c9e --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/psoft/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/psoft/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2901fbac1eac8dde6a92d7acbb989096dea22c27 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/psoft/__init__.py @@ -0,0 +1,24 @@ +# Copyright 2026-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 PsoftConfig +from .layer import Linear, PsoftLayer +from .model import PsoftModel + + +__all__ = ["Linear", "PsoftConfig", "PsoftLayer", "PsoftModel"] + +register_peft_method(name="psoft", config_cls=PsoftConfig, model_cls=PsoftModel, prefix="psoft_") diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/psoft/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/psoft/config.py new file mode 100644 index 0000000000000000000000000000000000000000..b8f6a731d56af34788b7a03c20e10bfeb550cdb1 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/psoft/config.py @@ -0,0 +1,313 @@ +# Copyright 2026-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 + + +@dataclass +class PsoftConfig(PeftConfig): + """ + Configuration for PSOFT (Efficient Orthogonal Fine-Tuning with Principal Subspace Adaptation). + + PSOFT inserts an r*r orthogonal transformation R between low-rank matrices A and B, so the low-rank update is ΔW = + B @ (R-I) @ A. Only R (and optional tunable vectors) are trained; A and B are initialized with psoft_init + (SVD-based, row-orthogonal A) and frozen. + + Args: + r (`int`): + Defaults to 32. PSOFT rank (r) controls the adapter capacity through an r*r transformation R. Smaller ranks + 32-128 are typically sufficient for simple tasks, More complex tasks may benefit from 64-256, increasing + expressiveness at the cost of additional parameters and computation. See the paper for empirically + validated settings: https://openreview.net/forum?id=FSHrinMArK. + 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/Conv1D modules are chosen (if + the model is a PreTrainedModel, the output layer excluded). 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. + 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. + psoft_alpha (`int`): Defaults to 32. It controls PSOFT scaling factor. Same semantics as LoRA alpha. + psoft_dropout (`float`): Defaults to 0.0. Dropout for PSOFT path. Same semantics as LoRA dropout. + 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`. + ab_svd_init (`Literal["psoft_init", "pissa_init"]`): + Defaults to 'psoft_init'. Initialization strategy for A and B used to construct the principal subspace in + PSOFT. 'psoft_init': SVD-based initialization with row-orthogonal A, ensuring strict orthogonality (PSOFT). + 'pissa_init': SVD-based initialization with symmetric A and B (standard PiSSA). + psoft_svd (`Literal["full", "lowrank"]`): + Defaults to 'full'. SVD backend for initialization: 'full' uses torch.linalg.svd; 'lowrank' uses + torch.svd_lowrank. + psoft_svd_lowrank_niter (`int`): + Only used when psoft_svd='lowrank'. Defaults to 10. Number of power iterations used by torch.svd_lowrank + when psoft_svd='lowrank'. + psoft_orth (`bool`): + Defaults to 'True'. If True, constrains R to be orthogonal via Cayley parameterization, preserving the + geometric relationships among column of the pre-trained weight vectors. If False, R is a free matrix + without orthogonality constraints. + psoft_mag_b (`bool`): + Defaults to 'True'. If True, learns a diagonal scaling vector on the 'output' side of R. Commonly paired + with psoft_mag_a to increase task adaptability, with slight distortion to the pre-trained geometry. + psoft_mag_a (`bool`): + Defaults to 'True'. If True, learns a diagonal scaling vector on the 'input' side of R. Commonly paired + with psoft_mag_b to increase task adaptability, with slight distortion to the pre-trained geometry. + use_cayley_neumann (`bool`): + Defaults to 'False'. Whether to use the Cayley-Neumann formulation of PSOFT or not. Set to True to improve + computational efficiency but comes at costs of bigger approximation error for orthogonality. + num_cayley_neumann_terms (`int`): + Defaults to 5. Only used when use_cayley_neumann=True. Number of Cayley-Neumann terms to use. Higher number + results in less approximation error for orthogonality. + cayley_neumann_eps (`optional[float]`): + Defaults to 'None'. Only used when use_cayley_neumann=True. Optional Frobenius-norm bound for the generator + matrix Q in the Cayley-Neumann approximation. If None (default), no rescaling is applied. If set to a value + in (0, 1) (e.g., 0.9), Q is rescaled whenever ||Q||_F exceeds the threshold to improve numerical stability. + See https://spherelab.ai/oftv2/ for details. + init_weights (`bool`): + Defaults to 'True'. Whether to initialize the weights of the PSOFT layers with their default + initialization. Don't change this setting, except if you know exactly what you're doing. + modules_to_save (`List[str]`): + List of modules apart from adapter layers to be set as trainable and saved in the final checkpoint. + 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'`. + """ + + r: int = field( + default=32, + metadata={ + "help": ( + "PSOFT rank (r) controls the adapter capacity through an r*r transformation R. " + "Smaller ranks 32-128 are typically sufficient for simple tasks, More complex tasks may benefit from 64-256, " + "increasing expressiveness at the cost of additional parameters and computation. " + "See the paper for empirically validated settings: https://openreview.net/forum?id=FSHrinMArK. " + ) + }, + ) + 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 PSOFT. " + "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'. " + "This can also be a wildcard 'all-linear' which matches all linear/Conv1D " + "(if the model is a PreTrainedModel, the output layer excluded). " + "If 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. " + ), + }, + ) + 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 PSOFT. "}, + ) + psoft_alpha: int = field( + default=32, metadata={"help": "It controls PSOFT scaling factor. Same semantics as LoRA alpha. "} + ) + psoft_dropout: float = field( + default=0.0, metadata={"help": "Dropout for PSOFT path. Same semantics as LoRA dropout. "} + ) + 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). "}, + ) + ab_svd_init: Literal["psoft_init", "pissa_init"] = field( + default="psoft_init", + metadata={ + "help": ( + "Initialization strategy for A and B used to construct the principal subspace in PSOFT. " + "- 'psoft_init': SVD-based initialization with row-orthogonal A (asymmetric A and B), ensuring strict orthogonality (PSOFT). " + "- 'pissa_init': SVD-based initialization with symmetric A and B, without strict orthogonality constraint (standard PiSSA). " + ) + }, + ) + psoft_svd: Literal["full", "lowrank"] = field( + default="full", + metadata={ + "help": "SVD backend for initialization: 'full' uses torch.linalg.svd; 'lowrank' uses torch.svd_lowrank. " + }, + ) + psoft_svd_lowrank_niter: int = field( + default=10, + metadata={ + "help": "Number of power iterations used by torch.svd_lowrank when psoft_svd='lowrank'. Only used when psoft_svd='lowrank'. " + }, + ) + psoft_orth: bool = field( + default=True, + metadata={ + "help": ( + "If True, constrains R to be orthogonal via Cayley parameterization, preserving the geometric relationships among column of the pre-trained weight vectors. " + "If False, R is a free matrix without orthogonality constraints. " + ) + }, + ) + psoft_mag_b: bool = field( + default=True, + metadata={ + "help": ( + "If True, learns a diagonal scaling vector on the 'output' side of R. " + "Commonly paired with psoft_mag_a to increase task adaptability, with slight distortion to the pre-trained geometry. " + ) + }, + ) + psoft_mag_a: bool = field( + default=True, + metadata={ + "help": ( + "If True, learns a diagonal scaling vector on the 'input' side of R. " + "Commonly paired with psoft_mag_b to increase task adaptability, with slight distortion to the pre-trained geometry. " + ) + }, + ) + use_cayley_neumann: bool = field( + default=False, + metadata={ + "help": "Whether to use the Cayley-Neumann Formulation of PSOFT 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. Only used when use_cayley_neumann=True." + }, + ) + cayley_neumann_eps: Optional[float] = field( + default=None, + metadata={ + "help": ( + "Optional Frobenius-norm bound for the generator matrix Q in the Cayley-Neumann approximation. Only used when use_cayley_neumann=True. " + "If None (default), no rescaling is applied. " + "If set to a value in (0, 1) (e.g., 0.9), Q is rescaled whenever ||Q||_F exceeds the threshold to improve numerical stability. " + "See https://spherelab.ai/oftv2/ for details. " + ) + }, + ) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": ( + "List of modules apart from PSOFT 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 PSOFT 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. " + "This only works when target_modules is a list of str." + ) + }, + ) + 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 only works when target_modules is a list of str. This should target the `nn.ModuleList` of the " + "model, which is often called `'layers'` or `'h'`. " + ) + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.PSOFT + 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 + ) + + # if target_modules is a regex expression, then layers_to_transform should be None + if isinstance(self.target_modules, str) and self.layers_to_transform is not None: + raise ValueError("`layers_to_transform` cannot be used when `target_modules` is a str.") + + # if target_modules is a regex expression, then layers_pattern should be None + if isinstance(self.target_modules, str) and self.layers_pattern is not None: + raise ValueError("`layers_pattern` cannot be used when `target_modules` is a str.") + + # 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: + raise ValueError(f"`r` must be a positive integer; got {self.r}.") + + allowed_inits = {"psoft_init", "pissa_init"} + if self.ab_svd_init not in allowed_inits: + raise ValueError(f"`ab_svd_init` must be one of {sorted(allowed_inits)}; got {self.ab_svd_init!r}.") + + allowed_svd_backends = {"full", "lowrank"} + if self.psoft_svd not in allowed_svd_backends: + raise ValueError(f"`psoft_svd` must be one of {sorted(allowed_svd_backends)}; got {self.psoft_svd!r}.") + + DEFAULT_LOW_RANK_NITER = self.__dataclass_fields__["psoft_svd_lowrank_niter"].default + if self.psoft_svd != "lowrank" and self.psoft_svd_lowrank_niter != DEFAULT_LOW_RANK_NITER: + warnings.warn( + "`psoft_svd_lowrank_niter` is only used when `psoft_svd='lowrank'`. " + f"Got psoft_svd={self.psoft_svd!r}, so psoft_svd_lowrank_niter=" + f"{self.psoft_svd_lowrank_niter} will be ignored.", + UserWarning, + ) + + DEFAULT_NUM_CAYLEY_NEUMANN_TERMS = self.__dataclass_fields__["num_cayley_neumann_terms"].default + if self.use_cayley_neumann: + if self.num_cayley_neumann_terms <= 0: + raise ValueError( + f"`num_cayley_neumann_terms` must be a positive integer; got {self.num_cayley_neumann_terms}." + ) + if self.cayley_neumann_eps is not None and not (0.0 < self.cayley_neumann_eps < 1.0): + raise ValueError(f"`cayley_neumann_eps` must be in (0, 1) when set; got {self.cayley_neumann_eps}.") + else: + if self.num_cayley_neumann_terms != DEFAULT_NUM_CAYLEY_NEUMANN_TERMS: + warnings.warn( + "`num_cayley_neumann_terms` is only used when `use_cayley_neumann=True`. " + f"Since `use_cayley_neumann=False`, `num_cayley_neumann_terms={self.num_cayley_neumann_terms}` will be ignored.", + UserWarning, + ) + if self.cayley_neumann_eps is not None: + warnings.warn( + "`cayley_neumann_eps` is only used when `use_cayley_neumann=True`. " + f"Since `use_cayley_neumann=False`, `cayley_neumann_eps={self.cayley_neumann_eps}` will be ignored.", + UserWarning, + ) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/psoft/layer.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/psoft/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..121c0a61d247dfbf230458d3166269934d95c142 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/psoft/layer.py @@ -0,0 +1,488 @@ +# Copyright 2026-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 torch +from torch import nn, svd_lowrank + +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 gather_params_ctx +from peft.utils.other import transpose + +from .config import PsoftConfig + + +class OrthLayer(nn.Module): + """ + r*r orthogonal transformation R used in PSOFT between A and B. Forward: output = input @ R.T + """ + + def __init__( + self, + size: int, + orth: bool = True, + mag_b: bool = True, + mag_a: bool = True, + use_cayley_neumann: bool = False, + num_cayley_neumann_terms: int = 5, + cayley_neumann_eps: Optional[float] = None, + ): + super().__init__() + self.size = size + self.orth = orth + self.mag_b = mag_b + self.mag_a = mag_a + self.use_cayley_neumann = use_cayley_neumann + self.num_cayley_neumann_terms = num_cayley_neumann_terms + self.cayley_neumann_eps = cayley_neumann_eps + + if orth: + self.weight = nn.Parameter(torch.empty((size * (size - 1)) // 2)) + rows, cols = torch.triu_indices(size, size, 1) + self.register_buffer("rows", rows, persistent=False) + self.register_buffer("cols", cols, persistent=False) + else: + self.weight = nn.Parameter(torch.empty(size, size)) + + self.vector_b = nn.Parameter(torch.empty(size)) if mag_b else None + self.vector_a = nn.Parameter(torch.empty(size)) if mag_a else None + + def reset_parameters(self, init_weights: bool = True) -> None: + params = [self.weight] + if self.vector_b is not None: + params.append(self.vector_b) + if self.vector_a is not None: + params.append(self.vector_a) + + if any(p.is_meta for p in params): + return + + with torch.no_grad(): + if init_weights: + if self.orth: + self.weight.zero_() + else: + nn.init.eye_(self.weight) + + if self.vector_b is not None: + self.vector_b.fill_(1.0) + if self.vector_a is not None: + self.vector_a.fill_(1.0) + else: + if self.orth: + nn.init.normal_(self.weight, mean=0.0, std=0.1) + else: + nn.init.eye_(self.weight) + self.weight.add_(torch.randn_like(self.weight) * 0.1) + + if self.vector_b is not None: + self.vector_b.fill_(1.0) + if self.vector_a is not None: + self.vector_a.fill_(1.0) + + def forward(self, input: torch.Tensor) -> torch.Tensor: + R = self.get_matrix() + + if input.device.type == "cpu" and input.dtype in (torch.float16, torch.bfloat16): + compute_dtype = torch.float32 + else: + compute_dtype = input.dtype + + return (input.to(compute_dtype) @ R.to(compute_dtype).t()).to(input.dtype) + + # Adapted from the Cayley/Neumann-based orthogonal parametrization used in OFT v2 + # (PEFT implementation: https://github.com/huggingface/peft/blob/main/src/peft/tuners/oft/layer.py) #L104 + def _skew_symmetric(self) -> torch.Tensor: + Q = torch.zeros((self.size, self.size), device=self.weight.device, dtype=self.weight.dtype) + Q = Q.index_put((self.rows, self.cols), self.weight) + return Q - Q.transpose(0, 1) + + # Adapted from the Cayley/Neumann-based orthogonal parametrization used in OFT v2 + # (PEFT implementation: https://github.com/huggingface/peft/blob/main/src/peft/tuners/oft/layer.py) #L160 + def _project_Q(self, Q: torch.Tensor, eps: float = 0.9) -> torch.Tensor: + norm = torch.linalg.norm(Q, ord="fro") + if torch.isfinite(norm) and norm > eps: + Q = Q * (eps / (norm + 1e-12)) + return Q + + # R = (I+Q)(I-Q)^(-1) + def get_matrix(self) -> torch.Tensor: + cast_to_fp32 = False + orig_dtype = None + + if not self.orth: + R = self.weight + else: + Q = self._skew_symmetric() + orig_dtype = Q.dtype + + id_mat = torch.eye(self.size, device=Q.device, dtype=Q.dtype) + + if self.use_cayley_neumann: + if self.cayley_neumann_eps is not None: + Q = self._project_Q(Q, eps=self.cayley_neumann_eps) + t = int(self.num_cayley_neumann_terms) + + R = id_mat.clone() + if t > 1: + R.add_(Q, alpha=2.0) + if t > 2: + Q_squared = Q @ Q + R.add_(Q_squared, alpha=2.0) + + Q_power = Q_squared + for _ in range(3, t - 1): + Q_power = Q_power @ Q + R.add_(Q_power, alpha=2.0) + + Q_power = Q_power @ Q + R.add_(Q_power) + else: + cast_to_fp32 = orig_dtype in (torch.float16, torch.bfloat16) + if cast_to_fp32: + Q = Q.float() # solver requires float32 + R = torch.linalg.solve(id_mat - Q, id_mat + Q, left=False) + + # Apply scaling vectors to R + if self.vector_b is not None: + R = self.vector_b[:, None] * R + if self.vector_a is not None: + R = R * self.vector_a[None, :] + + if cast_to_fp32: + R = R.to(orig_dtype) + + return R + + def __repr__(self) -> str: + return ( + f"psoft.{self.__class__.__name__}(" + f"size={self.size}, orth={self.orth}, " + f"use_cayley_neumann={self.use_cayley_neumann}, " + f"num_cayley_neumann_terms={int(self.num_cayley_neumann_terms)}, " + f"cayley_neumann_eps={self.cayley_neumann_eps}, " + f"mag_a={self.mag_a}, mag_b={self.mag_b}" + f")" + ) + + +class PsoftLayer(BaseTunerLayer): + adapter_layer_names: tuple[str, ...] = ("psoft_R",) + other_param_names: tuple[str, ...] = ( + "r", + "psoft_alpha", + "scaling", + "psoft_dropout", + "psoft_svd", + "psoft_svd_lowrank_niter", + "ab_svd_init", + ) + + def __init__(self, base_layer: nn.Module, **kwargs) -> None: + super().__init__() + self.base_layer = base_layer + + # per-adapter hyperparams + self.r: dict[str, int] = {} + self.psoft_alpha: dict[str, float] = {} + self.scaling: dict[str, float] = {} + self.psoft_dropout = nn.ModuleDict({}) + self.psoft_svd: dict[str, str] = {} + self.psoft_svd_lowrank_niter: dict[str, int] = {} + self.ab_svd_init: dict[str, Optional[str]] = {} + + # per-adapter trainable module + self.psoft_R = nn.ModuleDict({}) + + # per-adapter cache state + self._psoft_A_cache = BufferDict(persistent=False) + self._psoft_B_cache = BufferDict(persistent=False) + + self.merged_adapters: list[str] = [] + self._disable_adapters = False + self.kwargs = kwargs + + self.fan_in_fan_out = False + + base_layer = self.get_base_layer() + in_features, out_features = _get_in_out_features(base_layer) + self.in_features = in_features + self.out_features = out_features + + def _get_psoft_ab_cache_buffers(self, adapter_name: str): + return self._psoft_A_cache[adapter_name], self._psoft_B_cache[adapter_name] + + def _set_psoft_ab_cache_buffers(self, adapter_name: str, A: torch.Tensor, B: torch.Tensor) -> None: + self._psoft_A_cache[adapter_name] = A + self._psoft_B_cache[adapter_name] = B + + def update_layer(self, adapter_name: str, config: PsoftConfig, **kwargs: Any) -> None: + ab_svd_init = config.ab_svd_init + init_weights = config.init_weights + + r = int(config.r) + + self.fan_in_fan_out = config.fan_in_fan_out + + self.r[adapter_name] = r + self.psoft_alpha[adapter_name] = config.psoft_alpha + self.scaling[adapter_name] = config.psoft_alpha / r + + self.psoft_dropout[adapter_name] = ( + nn.Dropout(p=config.psoft_dropout) if config.psoft_dropout > 0.0 else nn.Identity() + ) + + self.ab_svd_init[adapter_name] = config.ab_svd_init + self.psoft_svd[adapter_name] = config.psoft_svd + self.psoft_svd_lowrank_niter[adapter_name] = config.psoft_svd_lowrank_niter + + self.psoft_R[adapter_name] = OrthLayer( + size=r, + orth=config.psoft_orth, + mag_b=config.psoft_mag_b, + mag_a=config.psoft_mag_a, + use_cayley_neumann=config.use_cayley_neumann, + num_cayley_neumann_terms=config.num_cayley_neumann_terms, + cayley_neumann_eps=config.cayley_neumann_eps, + ) + + self._move_adapter_to_device_of_base_layer(adapter_name) + self.psoft_R[adapter_name].reset_parameters(init_weights=init_weights) + self.psoft_R[adapter_name].requires_grad_(True) + + with gather_params_ctx(self.get_base_layer().weight): + self._build_psoft_ab_cache_buffers(adapter_name, ab_svd_init) + + self.set_adapter([adapter_name]) + + # Adapted from the asymmetric SVD used in PiSSA + # (PEFT implementation: https://github.com/huggingface/peft/blob/main/src/peft/tuners/lora/layer.py) #L316 + def _build_psoft_ab_cache_buffers(self, adapter_name: str, init_type: str) -> None: + with torch.no_grad(): + base = self.get_base_layer() + weight = base.weight + dtype = weight.dtype + if dtype not in (torch.float32, torch.float16, torch.bfloat16): + raise TypeError("PSOFT init requires float32/float16/bfloat16. Re-quantize after init if needed.") + + # W: (out, in) fp32 + W = transpose(weight.to(torch.float32), self.fan_in_fan_out) + + r = self.r[adapter_name] + Vr, Sr, Uhr = self._compute_svd_factors( + W, + r, + svd_mode=self.psoft_svd[adapter_name], + niter=self.psoft_svd_lowrank_niter[adapter_name], + ) + + Sr_scaled = Sr / self.scaling[adapter_name] + + if init_type == "psoft_init": + A = Uhr # (r, in) + B = Vr @ torch.diag(Sr_scaled) # (out, r) + elif init_type == "pissa_init": + s_sqrt = torch.sqrt(Sr_scaled) + A = torch.diag(s_sqrt) @ Uhr # (r, in) + B = Vr @ torch.diag(s_sqrt) # (out, r) + else: + raise ValueError(f"Unknown ab_svd_init: {init_type}") + + A = A.contiguous().detach() + B = B.contiguous().detach() + + self._set_psoft_ab_cache_buffers(adapter_name, A, B) + + def _compute_svd_factors(self, weight: torch.Tensor, r: int, *, svd_mode: str, niter: int): + # weight: (out, in) fp32 + if svd_mode == "full": + U, S, Vh = torch.linalg.svd(weight.data, full_matrices=False) + Vr = U[:, :r] # (out, r) + Sr = S[:r] # (r,) + Uhr = Vh[:r, :] # (r, in) + elif svd_mode == "lowrank": + U, S, V = svd_lowrank(weight.data, q=r, niter=niter) # V: (in, r) + Vr = U[:, :r] + Sr = S[:r] + Uhr = V[:, :r].t() # (r, in) + else: + raise ValueError(f"Unknown svd_mode: {svd_mode}") + return Vr, Sr, Uhr + + +class Linear(nn.Module, PsoftLayer): + def __init__( + self, + base_layer: nn.Module, + adapter_name: str, + config: PsoftConfig, + **kwargs: Any, + ) -> None: + super().__init__() + PsoftLayer.__init__(self, base_layer, **kwargs) + + self.fan_in_fan_out = config.fan_in_fan_out + self._active_adapter = adapter_name + self.update_layer(adapter_name, config=config, **kwargs) + + def _get_R_matrix(self, adapter_name: str) -> torch.Tensor: + return self.psoft_R[adapter_name].get_matrix() + + def get_delta_weight(self, adapter_name: str) -> torch.Tensor: + """ + ΔW = scaling * B (R - id_mat) A Returns in base weight layout (respecting fan_in_fan_out). + """ + + A, B = self._get_psoft_ab_cache_buffers(adapter_name) + base_w = self.get_base_layer().weight + device = base_w.device + out_dtype = base_w.dtype + + R = self._get_R_matrix(adapter_name) + r = self.r[adapter_name] + + compute_dtype = ( + torch.float32 if (device.type == "cpu" and out_dtype in (torch.float16, torch.bfloat16)) else out_dtype + ) + + A_c = A.to(device=device, dtype=compute_dtype) + B_c = B.to(device=device, dtype=compute_dtype) + R_c = R.to(device=device, dtype=compute_dtype) + + id_mat = torch.eye(r, device=device, dtype=compute_dtype) + delta = B_c @ (R_c - id_mat) @ A_c # (out, in) + delta = transpose(delta, self.fan_in_fan_out) + delta = delta * self.scaling[adapter_name] + + return delta.to(dtype=out_dtype) + + 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: + return + + base_layer = self.get_base_layer() + + for active_adapter in adapter_names: + if active_adapter not in self.psoft_R: + continue + + if safe_merge: + orig_weight = base_layer.weight.data.clone() + orig_dtype = orig_weight.dtype + + delta_weight = self.get_delta_weight(active_adapter) + orig_weight += delta_weight.to(orig_dtype) + + if not torch.isfinite(orig_weight).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = orig_weight + else: + delta_weight = self.get_delta_weight(active_adapter) + base_layer.weight.data += delta_weight.to(base_layer.weight.dtype) + + self.merged_adapters.append(active_adapter) + + def supports_lora_conversion(self, adapter_name: str = "default") -> bool: + return True + + def unmerge(self) -> None: + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.", UserWarning) + return + + weight = self.get_base_layer().weight + + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + + if active_adapter not in self.psoft_R: + continue + + orig_dtype = weight.dtype + delta_weight = self.get_delta_weight(active_adapter) + weight.data -= delta_weight.to(orig_dtype) + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> 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) + torch_result_dtype = result.dtype + + psoft_keys = self.psoft_R.keys() + for active_adapter in self.active_adapters: + if active_adapter not in psoft_keys: + continue + + A, B = self._get_psoft_ab_cache_buffers(active_adapter) + + dropout = self.psoft_dropout[active_adapter] + scaling = self.scaling[active_adapter] + R_layer = self.psoft_R[active_adapter] + + x_cast = self._cast_input_dtype(x, A.dtype) + x_d = dropout(x_cast) + + A_c = A.to(device=x_d.device, dtype=x_d.dtype) + B_c = B.to(device=x_d.device, dtype=x_d.dtype) + + xa = x_d @ A_c.t() + xr = R_layer(xa) + + delta_y = (xr - xa) @ B_c.t() + result = result + (delta_y * scaling) + + result = result.to(torch_result_dtype) + + return result + + def __repr__(self) -> str: + return "psoft." + super().__repr__() + + +def dispatch_default( + target: nn.Module, + adapter_name: str, + config: PsoftConfig, + **kwargs, +) -> Optional[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): + if config.fan_in_fan_out: + warnings.warn( + "fan_in_fan_out=True is not compatible with `torch.nn.Linear`. Setting fan_in_fan_out=False." + ) + config.fan_in_fan_out = False + new_module = Linear(target, adapter_name, config=config, **kwargs) + + return new_module diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/psoft/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/psoft/model.py new file mode 100644 index 0000000000000000000000000000000000000000..27e0306b2f3ac55bc4c6d5d3a413b991ab6df2dc --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/psoft/model.py @@ -0,0 +1,84 @@ +# Copyright 2026-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 typing import Optional + +from torch import nn + +from peft.tuners.tuners_utils import BaseTuner, get_device_map +from peft.utils import TRANSFORMERS_MODELS_TO_PSOFT_TARGET_MODULES_MAPPING + +from .config import PsoftConfig +from .layer import PsoftLayer, dispatch_default + + +class PsoftModel(BaseTuner): + """ + PSOFT (Efficient Orthogonal Fine-Tuning with Principal Subspace Adaptation) model. + + Inserts an r*r orthogonal (or scaled) transformation R between low-rank A and B: ΔW = B @ (R-I) @ A. Use + ab_svd_init="psoft_init" to initialize A/B from SVD and freeze them, training only R (and optional magnitude + vectors). + + Args: + model: The model to adapt. + config: PsoftConfig. + adapter_name: Adapter name, default "default". + low_cpu_mem_usage: Create empty adapter weights on meta device. + """ + + prefix: str = "psoft_" + tuner_layer_cls = PsoftLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_PSOFT_TARGET_MODULES_MAPPING + + def _create_and_replace( + self, + peft_config: PsoftConfig, + adapter_name: str, + target: nn.Module, + target_name: str, + parent: nn.Module, + current_key: str, + *, + parameter_name: Optional[str] = None, + ) -> None: + if current_key is None: + raise ValueError("Current key must not be None.") + + kwargs = { + "target_name": current_key, + "parameter_name": parameter_name, + } + + if isinstance(target, PsoftLayer): + target.update_layer(adapter_name, config=peft_config, **kwargs) + return + + device_map = get_device_map(self.model) + new_module = self._create_new_module(peft_config, adapter_name, target, device_map=device_map, **kwargs) + + if adapter_name not in self.active_adapters: + new_module.requires_grad_(False) + self._replace_module(parent, target_name, new_module, target) + + @staticmethod + def _create_new_module(psoft_config: PsoftConfig, adapter_name: str, target: nn.Module, **kwargs) -> nn.Module: + new_module = dispatch_default(target, adapter_name, config=psoft_config, **kwargs) + if new_module is None: + raise ValueError( + f"Target module {target} is not supported by minimal PSOFT. Only torch.nn.Linear is supported." + ) + return new_module diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/pvera/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/pvera/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2cc9e19c0f67276d8a054b01a3ef08faed51d3fa --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/pvera/__init__.py @@ -0,0 +1,26 @@ +# 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 PveraConfig +from .layer import Linear, PveraLayer +from .model import PveraModel + + +__all__ = ["Linear", "PveraConfig", "PveraLayer", "PveraModel"] + + +register_peft_method(name="pvera", config_cls=PveraConfig, model_cls=PveraModel, prefix="pvera_lambda_") diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/pvera/bnb.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/pvera/bnb.py new file mode 100644 index 0000000000000000000000000000000000000000..20d03c142df113c32e23e152308c066553ab527e --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/pvera/bnb.py @@ -0,0 +1,413 @@ +# 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 +import torch.nn.functional as F + +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 .config import PveraConfig +from .layer import PveraLayer + + +if is_bnb_available(): + + class Linear8bitLt(torch.nn.Module, PveraLayer): + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + pvera_A, + pvera_B, + r: int, + config: PveraConfig, + **kwargs, + ) -> None: + super().__init__() + PveraLayer.__init__(self, base_layer) + self.fan_in_fan_out = config.fan_in_fan_out + self.sample_at_inference = config.sample_at_inference + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + pvera_A, + pvera_B, + r, + config=config, + ) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + if self.merged: + warnings.warn( + f"Already following adapters were merged {','.join(self.merged_adapters)}. " + f"You are now additionally merging {','.join(self.active_adapters)}." + ) + + 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.pvera_lambda_d.keys(): + continue + + warnings.warn( + "Merge pvera module to 8-bit linear may get different generations due to rounding errors." + ) + pvera_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(pvera_data.dtype).to(pvera_data.device) + pvera_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: + 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.pvera_lambda_d.keys(): + continue + warnings.warn( + "Unmerge pvera module to 8-bit linear may get different generations due to rounding errors." + ) + pvera_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(pvera_data.dtype).to(pvera_data.device) - pvera_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_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. + + Returns: + torch.Tensor: The computed delta weight for the PVeRA adapter. + + Note: + This method implements the PVeRA-specific weight update. Unlike LoRA, PVeRA uses shared projection + matrices (pvera_A and pvera_B) across all layers, along with per-layer trainable parameters (lambda_d + and lambda_b). + """ + # Retrieve shared projection matrices + pvera_A = self.pvera_A[adapter] + pvera_B = self.pvera_B[adapter] + + # Retrieve per-layer trainable parameters + device = pvera_B.device + dtype = pvera_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) + + lambda_d = self.pvera_lambda_d[adapter] + lambda_b = self.pvera_lambda_b[adapter] + + if cast_to_fp32: + pvera_A = pvera_A.float() + pvera_B = pvera_B.float() + lambda_d = lambda_d.float() + lambda_b = lambda_b.float() + + sliced_A = pvera_A[:, : self.in_features].to(lambda_d.device) + sliced_B = pvera_B[: self.out_features, :].to(lambda_d.device) + lambda_b = lambda_b.unsqueeze(-1) + lambda_d = lambda_d.unsqueeze(-1) + + # In PVeRA, the first half of the lambda_d and sliced_A vector corresponds to the mean (mu) and the second half to the log-variance (logvar). When merging, we can only do mean sampling, and therefore only need the first half + lambda_d = lambda_d[: lambda_d.size(0) // 2, :] + sliced_A = sliced_A[: sliced_A.size(0) // 2, :] + + # PVeRA-specific computation: + # 1. Apply lambda_d to the input projection (pvera_A) + # 2. Apply lambda_b to the output projection (pvera_B) + # 3. Compute the outer product of the scaled projections + output_tensor = transpose((lambda_b * sliced_B) @ (lambda_d * sliced_A), self.fan_in_fan_out) + + if cast_to_fp32: + output_tensor = output_tensor.to(dtype=dtype) + + return output_tensor + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + """ + Perform the forward pass using the PVeRA adapter. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + torch.Tensor: Output tensor after applying the PVeRA adaptation. + + Note: + This method implements the PVeRA-specific forward pass. It applies the shared projections (pvera_A and + pvera_B) along with the per-layer trainable parameters (lambda_d and lambda_b) 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.pvera_lambda_d.keys(): + continue + + lambda_d = self.pvera_lambda_d[active_adapter] + lambda_b = self.pvera_lambda_b[active_adapter] + + pvera_A = self.pvera_A[active_adapter] + pvera_B = self.pvera_B[active_adapter] + + dropout = self.pvera_dropout[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + compute_dtype = lambda_d.dtype + if x.dtype != compute_dtype: + x = x.to(compute_dtype) + + sliced_A = pvera_A[:, : self.in_features].to(x.device) + sliced_B = pvera_B[: self.out_features, :].to(x.device) + + x_temp = dropout(x.to(lambda_d.dtype)) + mu, logvar = (lambda_d * F.linear(x_temp, sliced_A)).chunk(2, dim=-1) + adapter_output = lambda_b * F.linear( + self._reparametrize(mu, logvar, self.sample_at_inference), sliced_B + ) + + if requires_conversion: + adapter_output = adapter_output.to(expected_dtype) + + result = result + adapter_output + + # 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 "pvera." + rep + + +if is_bnb_4bit_available(): + + class Linear4bit(torch.nn.Module, PveraLayer): + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + pvera_A, + pvera_B, + r: int, + config: PveraConfig, + **kwargs, + ) -> None: + super().__init__() + PveraLayer.__init__(self, base_layer) + self.fan_in_fan_out = config.fan_in_fan_out + self.sample_at_inference = config.sample_at_inference + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + pvera_A, + pvera_B, + r, + config=config, + ) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + if self.merged: + warnings.warn( + f"Already following adapters were merged {','.join(self.merged_adapters)}. " + f"You are now additionally merging {','.join(self.active_adapters)}." + ) + + 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.pvera_lambda_d.keys(): + continue + + warnings.warn( + "Merge pvera module to 4-bit linear may get different generations due to rounding errors." + ) + pvera_data = self.get_delta_weight(active_adapter) + + weight = self.get_base_layer().weight + kwargs = weight.__dict__ + # torch.compile can introduce attributes preceded by '_', remove them + kwargs = {k: v for k, v in kwargs.items() if not k.startswith("_")} + w_data = bnb.functional.dequantize_4bit(weight.data, weight.quant_state) + pvera_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: + 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.pvera_lambda_d.keys(): + continue + warnings.warn( + "Unmerge pvera module to 4-bit linear may get different generations due to rounding errors." + ) + pvera_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) - pvera_data + + self.get_base_layer().weight = bnb.nn.Params4bit(w_data.to("cpu"), requires_grad=False, **kwargs).to( + weight.device + ) + + def get_delta_weight(self, adapter) -> torch.Tensor: + pvera_A = self.pvera_A[adapter] + pvera_B = self.pvera_B[adapter] + + device = pvera_B.device + dtype = pvera_B.dtype + + cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16) + + lambda_d = self.pvera_lambda_d[adapter] + lambda_b = self.pvera_lambda_b[adapter] + + if cast_to_fp32: + pvera_A = pvera_A.float() + pvera_B = pvera_B.float() + lambda_d = lambda_d.float() + lambda_b = lambda_b.float() + + sliced_A = pvera_A[:, : self.in_features].to(lambda_d.device) + sliced_B = pvera_B[: self.out_features, :].to(lambda_d.device) + lambda_b = lambda_b.unsqueeze(-1) + lambda_d = lambda_d.unsqueeze(-1) + + # In PVeRA, the first half of the lambda_d and sliced_A vector corresponds to the mean (mu) and the second half to the log-variance (logvar). When merging, we can only do mean sampling, and therefore only need the first half + lambda_d = lambda_d[: lambda_d.size(0) // 2, :] + sliced_A = sliced_A[: sliced_A.size(0) // 2, :] + + output_tensor = transpose((lambda_b * sliced_B) @ (lambda_d * sliced_A), self.fan_in_fan_out) + + if cast_to_fp32: + output_tensor = output_tensor.to(dtype=dtype) + + return output_tensor + + 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.pvera_lambda_d.keys(): + continue + + lambda_d = self.pvera_lambda_d[active_adapter] + lambda_b = self.pvera_lambda_b[active_adapter] + + pvera_A = self.pvera_A[active_adapter] + pvera_B = self.pvera_B[active_adapter] + + dropout = self.pvera_dropout[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + compute_dtype = lambda_d.dtype + if x.dtype != compute_dtype: + x = x.to(compute_dtype) + + sliced_A = pvera_A[:, : self.in_features].to(x.device) + sliced_B = pvera_B[: self.out_features, :].to(x.device) + + x_temp = dropout(x.to(lambda_d.dtype)) + mu, logvar = (lambda_d * F.linear(x_temp, sliced_A)).chunk(2, dim=-1) + adapter_output = lambda_b * F.linear( + self._reparametrize(mu, logvar, self.sample_at_inference), sliced_B + ) + + if requires_conversion: + adapter_output = adapter_output.to(expected_dtype) + + result = result + adapter_output + + # 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 "pvera." + rep diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/pvera/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/pvera/config.py new file mode 100644 index 0000000000000000000000000000000000000000..8d13ec4b6f659f5e016d75a97e3ebef0729fb0b7 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/pvera/config.py @@ -0,0 +1,210 @@ +# 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 Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class PveraConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`PveraModel`]. + + Paper: https://www.arxiv.org/abs/2512.07703. + + Args: + r (`int`, *optional*, defaults to `256`): + PVeRA parameter dimension ("rank"). Choose higher values than LoRA ranks here, since PVeRA shares + parameters across layers and therefore uses far fewer parameters than LoRA. + target_modules (`Union[List[str], str]`): + The names of the modules to apply PVeRA to. Only linear layers are supported. When passing a string, a + regex match will be performed. If this is specified as 'all-linear', then all linear/Conv1D modules are + chosen. If this is not specified, modules will bechosen according to the model architecture. If the + architecture is not known, an error will be raised. + projection_prng_key (`int`): + PVeRA PRNG init key. Used for initialising pvera_A and pvera_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 pvera_A / pvera_B projections in the state dict alongside per layer lambda_b / lambda_d + weights. This will increase the size of the checkpoint, but guarantee that we can reload the checkpoint on + all system configurations. Defaults to `True`. + pvera_dropout (`float`): + The dropout probability for PVeRA layers. + d_initial (`float`, *optional*, defaults to `0.1`): + Initial value for `pvera_lambda_d` vector used when initializing the PVeRA parameters. Small values (<=0.1) + are recommended. + 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 for PVeRA. Can be 'none', 'all' or 'pvera_only'. If 'all' or 'pvera_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 PVeRA layers to be set as trainable and saved in the final checkpoint. + init_weights (`bool`): + Whether to initialize the weights of the PVeRA 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 PVeRA transformations on + the layer indexes that are specified in this list. If a single integer is passed, it will apply the PVeRA + 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'`. + sample_at_inference (`bool` | `dict`, defaults to `False`): + Whether to sample from the learned PVeRA distribution at inference. If false, the learned mean is used. The + default is False (indicating false for all adapters). If True is provided, then the value will be true for + all adapters. If a dict is provided, then a specific value can be specified per adapter (with False by + default for non-specified adapters). For example + `sample_at_inference={'encoder.layer.0.attention.attention.query': True}` will only sample at inference for + one specific adapter. + generator_seed (`int`, defaults to None): + Random seed for the generator for sampling from the learned distribution. + """ + + r: int = field( + default=256, + metadata={ + "help": ( + "PVeRA parameter dimension ('rank'). Choose higher values than LoRA ranks here, since PVeRA shares " + "parameters across layers and therefore uses far fewer parameters than LoRA." + ) + }, + ) + + target_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": ( + "The names of the modules to apply PVeRA to. Only linear layers are supported. When passing a string, a " + "regex match will be performed. If this is specified as 'all-linear', then all linear/Conv1D modules are " + "chosen. If this is not specified, modules will bechosen according to the model architecture. If the " + "architecture is not known, an error will be raised." + ) + }, + ) + projection_prng_key: int = field( + default=0, + metadata={ + "help": ( + "PVeRA PRNG init key. Used for initialising pvera_A and pvera_B for new models or when loading a checkpoint " + "that did not include these projections. Defaults to `0`." + ) + }, + ) + save_projection: bool = field( + default=True, + metadata={ + "help": ( + "Whether to save the pvera_A / pvera_B projections in the state dict alongside per layer lambda_b / lambda_d " + "weights. This will increase the size of the checkpoint, but guarantee that we can reload the checkpoint on " + "all system configurations. Defaults to `True`." + ) + }, + ) + pvera_dropout: float = field(default=0.0, metadata={"help": "The dropout probability for PVeRA layers."}) + d_initial: float = field(default=0.1, metadata={"help": "Initial value for d vector. Default is 0.1."}) + 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). For example, gpt-2 uses " + "`Conv1D` which stores weights like (fan_in, fan_out) and hence this should be set to `True`." + ) + }, + ) + bias: str = field( + default="none", + metadata={ + "help": ( + "Bias type for PVeRA. Can be 'none', 'all' or 'pvera_only'. If 'all' or 'pvera_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: Optional[list[str]] = field( + default=None, + metadata={ + "help": ( + "List of modules apart from PVeRA layers to be set as trainable and saved in the final checkpoint." + ) + }, + ) + init_weights: bool = field( + default=True, + metadata={ + "help": ( + "Whether to initialize the weights of the PVeRA 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, if this argument is specified, it will apply the PVeRA transformations on " + "the layer indexes that are specified in this list. If a single integer is passed, it will apply the PVeRA " + "transformations on 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 from `None`. This should target the " + "`nn.ModuleList` of the model, which is often called `'layers'` or `'h'`." + ) + }, + ) + sample_at_inference: bool = field( + default=False, + metadata={ + "help": ( + "Whether to sample from the learned PVeRA distribution at inference. If false, the learned mean is used. The " + "default is False (indicating false for all adapters). If True is provided, then the value will be true for " + "all adapters. If a dict is provided, then a specific value can be specified per adapter (with False by " + "default for non-specified adapters). For example " + "`sample_at_inference={'encoder.layer.0.attention.attention.query': True}` will only sample at inference for " + "one specific adapter." + ), + }, + ) + generator_seed: int = field( + default=None, metadata={"help": "Random seed for the generator for sampling from the learned distribution."} + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.PVERA + self.target_modules = ( + set(self.target_modules) if isinstance(self.target_modules, list) else self.target_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 not self.save_projection: + warnings.warn( + "Specified to not save pvera_A and pvera_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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/pvera/layer.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/pvera/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..b08e213c7c3c0a5dad16b949c36cb5ee19321e03 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/pvera/layer.py @@ -0,0 +1,316 @@ +# 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.functional as F +from torch import nn +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 +from .config import PveraConfig + + +class PveraLayer(BaseTunerLayer): + # List all names of layers that may contain adapter weights + adapter_layer_names = ("pvera_lambda_b", "pvera_lambda_d") + other_param_names = ("pvera_A", "pvera_B") + + def __init__(self, base_layer: nn.Module, **kwargs): + self.base_layer = base_layer + self.r = {} + self.pvera_dropout = nn.ModuleDict({}) + + # For storing vector scale + self.pvera_lambda_b = nn.ParameterDict({}) + self.pvera_lambda_d = nn.ParameterDict({}) + + # Stores a reference to the pvera_A/B BufferDict. + # Set to `None` otherwise to avoid computation with random weights + self.pvera_A: Optional[BufferDict] = None + self.pvera_B: Optional[BufferDict] = None + + # 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 + 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: str, + pvera_A: BufferDict, + pvera_B: BufferDict, + r: int, + config: PveraConfig, + **kwargs, + ) -> None: + if r <= 0: + raise ValueError(f"`r` should be a positive integer value but the value passed is {r}") + + pvera_dropout = config.pvera_dropout + init_weights = config.init_weights + d_initial = config.d_initial + inference_mode = config.inference_mode + + self.r[adapter_name] = r + if pvera_dropout > 0.0: + pvera_dropout_layer = nn.Dropout(p=pvera_dropout) + else: + pvera_dropout_layer = nn.Identity() + + if config.generator_seed is not None: + self.generator = torch.Generator() + self.generator.manual_seed(config.generator_seed) + else: + self.generator = None + + self.pvera_dropout.update(nn.ModuleDict({adapter_name: pvera_dropout_layer})) + # Actual trainable parameters + self.pvera_lambda_b[adapter_name] = nn.Parameter(torch.ones(self.out_features), requires_grad=True) + self.pvera_lambda_d[adapter_name] = nn.Parameter(torch.randn(r * 2), requires_grad=True) + + # non trainable references to pvera_A/B buffers + self.pvera_A = pvera_A + self.pvera_B = pvera_B + if adapter_name not in pvera_A: + # This means that this is not the first PVeRA adapter. We have to add an entry in the dict for this adapter. + if len(self.pvera_A) < 1: + raise ValueError( + "The `pvera_A` and `pvera_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 + pvera_A_param = next(iter(self.pvera_A.values())) + pvera_B_param = next(iter(self.pvera_B.values())) + + error_tmpl = ( + "{} has a size of {} but {} or greater is required; this probably happened because an additional PVeRA " + "adapter was added after the first one with incompatible shapes." + ) + # check input size + if pvera_A_param.shape[1] < self.in_features: + raise ValueError(error_tmpl.format("pvera_A", pvera_A_param.shape[1], self.in_features)) + # check output size + if pvera_B_param.shape[0] < self.out_features: + raise ValueError(error_tmpl.format("pvera_B", pvera_B_param.shape[0], self.out_features)) + # check r + error_tmpl = ( + "{} has a size of {} but {} or greater is required; this probably happened because an additional PVeRA " + "adapter with a lower rank was added after the first one; loading the adapters " + "in reverse order may solve this." + ) + if pvera_A_param.shape[0] < self.r[adapter_name]: + raise ValueError(error_tmpl.format("pvera_A", pvera_A_param.shape[0], self.r[adapter_name])) + if pvera_B_param.shape[1] < self.r[adapter_name]: + raise ValueError(error_tmpl.format("pvera_B", pvera_B_param.shape[1], self.r[adapter_name])) + + self.pvera_A[adapter_name] = pvera_A_param + self.pvera_B[adapter_name] = pvera_B_param + + if init_weights: + self.reset_pvera_parameters(adapter_name, d_initial=d_initial) + + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def reset_pvera_parameters(self, adapter_name, d_initial: float = 0.1): + if adapter_name in self.pvera_lambda_d.keys(): + with torch.no_grad(): + nn.init.zeros_(self.pvera_lambda_d[adapter_name]).fill_(d_initial) + nn.init.zeros_(self.pvera_lambda_b[adapter_name]) + + def _reparametrize(self, mu, logvar, sample_at_inference): + if self.training or (not self.training and sample_at_inference): + std = torch.exp(0.5 * logvar) + eps = torch.randn_like(std, generator=self.generator) + z = mu + eps * std + else: + z = mu + return z + + +class Linear(nn.Linear, PveraLayer): + # PVeRA implemented in a dense layer + def __init__( + self, + base_layer, + pvera_A: BufferDict, + pvera_B: BufferDict, + adapter_name: str, + r: int, + config: PveraConfig, + is_target_conv_1d_layer: bool = False, + **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__() + PveraLayer.__init__(self, base_layer, **kwargs) + self.fan_in_fan_out = config.fan_in_fan_out + self.sample_at_inference = config.sample_at_inference + + self._active_adapter = adapter_name + self.update_layer(adapter_name, pvera_A, pvera_B, r, config=config) + 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.pvera_lambda_d.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.pvera_lambda_d.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. + """ + pvera_A = self.pvera_A[adapter] + pvera_B = self.pvera_B[adapter] + + device = pvera_B.device + dtype = pvera_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) + + lambda_d = self.pvera_lambda_d[adapter] + lambda_b = self.pvera_lambda_b[adapter] + + if cast_to_fp32: + pvera_A = pvera_A.float() + pvera_B = pvera_B.float() + lambda_d = lambda_d.float() + lambda_b = lambda_b.float() + + sliced_A = pvera_A[:, : self.in_features].to(lambda_d.device) + sliced_B = pvera_B[: self.out_features, :].to(lambda_d.device) + lambda_b = lambda_b.unsqueeze(-1) + lambda_d = lambda_d.unsqueeze(-1) + + # In PVeRA, the first half of the lambda_d and sliced_A vector corresponds to the mean (mu) and the second half to the log-variance (logvar). When merging, we can only do mean sampling, and therefore only need the first half + lambda_d = lambda_d[: lambda_d.size(0) // 2, :] + sliced_A = sliced_A[: sliced_A.size(0) // 2, :] + + output_tensor = transpose((lambda_b * sliced_B) @ (lambda_d * sliced_A), self.fan_in_fan_out) + + if cast_to_fp32: + output_tensor = output_tensor.to(dtype=dtype) + + return output_tensor + + 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.pvera_lambda_d.keys(): + continue + + lambda_d = self.pvera_lambda_d[active_adapter] + lambda_b = self.pvera_lambda_b[active_adapter] + + pvera_A = self.pvera_A[active_adapter] + pvera_B = self.pvera_B[active_adapter] + + # As adapted layers may have different shapes and PVeRA 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 pvera_A and pvera_B. + sliced_A = pvera_A[:, : self.in_features].to(x.device) + sliced_B = pvera_B[: self.out_features, :].to(x.device) + + dropout = self.pvera_dropout[active_adapter] + x = x.to(lambda_d.dtype) + mu, logvar = (lambda_d * F.linear(dropout(x), sliced_A)).chunk(2, dim=-1) + result = result + lambda_b * F.linear( + self._reparametrize(mu, logvar, self.sample_at_inference), sliced_B + ) + + result = result.to(previous_dtype) + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "pvera." + rep diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/pvera/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/pvera/model.py new file mode 100644 index 0000000000000000000000000000000000000000..943cce7022057a6ee82759811beb86711d6054d3 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/pvera/model.py @@ -0,0 +1,263 @@ +# 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 torch import nn +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_PVERA_TARGET_MODULES_MAPPING, +) + +from .._buffer_dict import BufferDict +from ..tuners_utils import _maybe_include_all_linear_layers +from .config import PveraConfig +from .layer import Linear, PveraLayer + + +class PveraModel(BaseTuner): + """ + Creates Probabilistic Vector-based Random Matrix Adaptation (PVeRA) model from a pretrained transformers model. + + Args: + model ([`~transformers.PreTrainedModel`]): The model to be adapted. + config ([`PveraConfig`]): The configuration of the PVeRA 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 PVeRA model. + + Example: + + ```py + >>> from transformers import AutoModel + >>> from peft import PveraConfig, get_peft_model + + >>> base_model = AutoModel.from_pretrained("facebook/dinov2-base") + >>> config = PveraConfig(r=128, sample_at_inference=False) + >>> model = get_peft_model(base_model, config) + ``` + + **Attributes**: + - **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted. + - **peft_config** ([`PveraConfig`]): The configuration of the PVeRA model. + """ + + prefix: str = "pvera_lambda_" + tuner_layer_cls = PveraLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_PVERA_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 PVeRA. + + This will be used for determining the size of the shared pvera_A and pvera_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 PVeRA were found. Please check `peft_config.target_modules`." + raise ValueError(msg) + + return largest_shape + + def _init_pvera_A_pvera_B(self, config: PveraConfig, adapter_name: str) -> None: + linear_out_dim, linear_in_dim = self._find_dim(config) + + # use of persistent to exclude pvera_A and pvera_B from the state dict if we choose not to save them. + self.pvera_A = BufferDict({}, persistent=config.save_projection) + self.pvera_B = BufferDict({}, persistent=config.save_projection) + + # deterministic init of pvera_A and pvera_B if we know the key + generator = torch.Generator(device="cpu").manual_seed(config.projection_prng_key) + pvera_A = torch.nn.init.kaiming_uniform_(torch.empty(config.r * 2, linear_in_dim), generator=generator) + pvera_B = torch.nn.init.kaiming_uniform_(torch.empty(linear_out_dim, config.r), generator=generator) + + self.pvera_A[adapter_name] = pvera_A + self.pvera_B[adapter_name] = pvera_B + + def _pre_injection_hook(self, model: nn.Module, config: PveraConfig, adapter_name: str) -> None: + self._init_pvera_A_pvera_B(config, adapter_name) + + def _check_new_adapter_config(self, config: PveraConfig) -> 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"PVeRA 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 = {config.save_projection for config in self.peft_config.values()} + if len(save_project_unique_values) > 1: + raise ValueError( + "PVeRA 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, + pvera_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 = pvera_config.r + bias = hasattr(target, "bias") and target.bias is not None + kwargs = { + "r": r, + "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, + pvera_A=self.pvera_A, + pvera_B=self.pvera_B, + r=r, + config=pvera_config, + ) + else: + new_module = self._create_new_module( + pvera_config, self.pvera_A, self.pvera_B, adapter_name, target, current_key, **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(pvera_config, pvera_A, pvera_B, adapter_name, target, current_key, **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, pvera_A, pvera_B, config=pvera_config, **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, pvera_A, pvera_B, config=pvera_config, **fourbit_kwargs) + elif isinstance(target_base_layer, torch.nn.Linear): + if pvera_config.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." + ) + pvera_config.fan_in_fan_out = False + elif isinstance(target_base_layer, Conv1D): + if not pvera_config.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." + ) + pvera_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`." + ) + + if isinstance(pvera_config.sample_at_inference, bool): + module_sample_at_inference = pvera_config.sample_at_inference + else: + module_sample_at_inference = pvera_config.sample_at_inference.get(current_key, False) + + new_module = Linear( + target, + pvera_A, + pvera_B, + adapter_name, + config=pvera_config, + **kwargs, + ) + + return new_module diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/randlora/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/randlora/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fbad681aeb0231254f5caae6b9bf9aa3a2c76ef0 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/randlora/bnb.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/randlora/bnb.py new file mode 100644 index 0000000000000000000000000000000000000000..7df7e576923ed609a0407b68d5c90d288eaeeff0 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/randlora/bnb.py @@ -0,0 +1,451 @@ +# 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 .config import RandLoraConfig +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, + config: RandLoraConfig, + randlora_A, + randlora_B, + r: int = 0, + randlora_alpha: int = 0, + init_weights: bool = True, + **kwargs, + ) -> None: + super().__init__() + RandLoraLayer.__init__(self, base_layer) + self.fan_in_fan_out = config.fan_in_fan_out + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + randlora_A, + randlora_B, + r, + config=config, + ) + + 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, + config: RandLoraConfig, + randlora_A, + randlora_B, + r: int = 0, + randlora_alpha: int = 0, + init_weights: bool = True, + **kwargs, + ) -> None: + super().__init__() + RandLoraLayer.__init__(self, base_layer) + self.fan_in_fan_out = config.fan_in_fan_out + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + randlora_A, + randlora_B, + r, + config=config, + ) + + 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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/randlora/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/randlora/config.py new file mode 100644 index 0000000000000000000000000000000000000000..b194b974331dd9abcb5777295ae4e79d8b81da56 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/randlora/layer.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/randlora/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..303db973386cda67338db000df67b4b26b24c6e9 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/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.functional as F +from torch import nn +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 +from .config import RandLoraConfig + + +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, + config: RandLoraConfig, + inference_mode: bool = False, + **kwargs, + ): + randlora_alpha = config.randlora_alpha + randlora_dropout = config.randlora_dropout + init_weights = config.init_weights + + 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 = next(iter(self.randlora_A.values())) + randlora_B_param = next(iter(self.randlora_B.values())) + + 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, + config: RandLoraConfig, + r: int = 0, + is_target_conv_1d_layer: bool = False, + **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 = config.fan_in_fan_out + self._active_adapter = adapter_name + self.update_layer(adapter_name, randlora_A, randlora_B, r, config=config) + 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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/randlora/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/randlora/model.py new file mode 100644 index 0000000000000000000000000000000000000000..6d1140dc74cc69df3218ecd638d3b6fd8757bd8c --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/randlora/model.py @@ -0,0 +1,366 @@ +# 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 +from accelerate.utils.imports import is_bf16_available +from torch import nn +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, + "fan_in_fan_out": randlora_config.fan_in_fan_out, + "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, + config=randlora_config, + ) + 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, + config=randlora_config, + randlora_A=randlora_A, + randlora_B=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, + config=randlora_config, + randlora_A=randlora_A, + randlora_B=randlora_B, + **fourbit_kwargs, + ) + elif isinstance(target_base_layer, torch.nn.Linear): + if randlora_config.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." + ) + randlora_config.fan_in_fan_out = False + elif isinstance(target_base_layer, Conv1D): + kwargs["is_target_conv_1d_layer"] = True + if not randlora_config.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." + ) + 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, + config=randlora_config, + bias=bias, + **kwargs, + ) + + return new_module diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/road/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/road/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..97b2f0f54fc113f3470c5c7835b0b2cec133319e --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/road/__init__.py @@ -0,0 +1,47 @@ +# 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. + + +# Based on implementation made available in https://github.com/ppetrushkov/peft/tree/road (not from paper authors) + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available +from peft.utils import register_peft_method + +from .config import RoadConfig +from .layer import Linear, RoadLayer +from .model import RoadModel + + +__all__ = [ + "Linear", + "RoadConfig", + "RoadLayer", + "RoadModel", +] + +register_peft_method(name="road", config_cls=RoadConfig, model_cls=RoadModel, is_mixed_compatible=True) + + +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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/road/bnb.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/road/bnb.py new file mode 100644 index 0000000000000000000000000000000000000000..4de2e38440438d916cf9524640e3f76d4b2f4d41 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/road/bnb.py @@ -0,0 +1,405 @@ +# 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 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 .config import RoadConfig, RoadVariant +from .layer import RoadLayer, _apply_road, _get_delta_weight + + +if is_bnb_available(): + + class Linear8bitLt(torch.nn.Module, RoadLayer): + # Road implemented in a dense layer + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + config: RoadConfig, + variant: RoadVariant = "road_1", + group_size: int = 64, + init_weights: bool = True, + **kwargs, + ) -> None: + super().__init__() + RoadLayer.__init__(self, base_layer) + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + config=config, + ) + + 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._available_adapters: + warnings.warn( + "Merge road 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) + road_R = _get_delta_weight( + self.variant[active_adapter], + self.group_size[active_adapter], + self.road_theta[active_adapter].data, + self.road_alpha[active_adapter].data, + ) + + w_data = torch.matmul(road_R, output.to(road_R.dtype)) + w_data = w_data.to(road_R.dtype).to(road_R.device).contiguous() + + 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.get_base_layer().bias is not None: + bias = self.get_base_layer().bias + orig_dtype = bias.dtype + bias_data = bias.data + new_bias = torch.matmul(road_R, bias_data.to(road_R.dtype)) + bias.data = new_bias.to(orig_dtype) + + 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 in self._available_adapters: + warnings.warn( + "Unmerge road 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) + + road_R = _get_delta_weight( + self.variant[active_adapter], + self.group_size[active_adapter], + self.road_theta[active_adapter].data, + self.road_alpha[active_adapter].data, + ) + inv_road_R = torch.linalg.inv(road_R.to(torch.float32)).to(road_R.dtype) + + w_data = torch.matmul(inv_road_R, output.to(road_R.dtype)) + w_data = w_data.to(road_R.dtype).to(road_R.device).contiguous() + + 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.get_base_layer().bias is not None: + bias = self.get_base_layer().bias + orig_dtype = bias.dtype + bias_data = bias.data + new_bias = torch.matmul(inv_road_R, bias_data) + bias.data = new_bias.to(orig_dtype) + + state.reset_grads() + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> 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) + + for active_adapter in self.active_adapters: + if active_adapter not in self._available_adapters: + continue + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + result = self._cast_input_dtype(result, self.road_theta[active_adapter].dtype) + + result = _apply_road( + self.variant[active_adapter], + self.group_size[active_adapter], + self.road_theta[active_adapter], + self.road_alpha[active_adapter], + result, + ) + + if requires_conversion: + x = x.to(expected_dtype) + + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "road." + rep + + def dispatch_bnb_8bit(target: torch.nn.Module, adapter_name: str, road_config: RoadConfig, **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=road_config, **eightbit_kwargs) + + return new_module + + +if is_bnb_4bit_available(): + + class Linear4bit(torch.nn.Module, RoadLayer): + # OFT implemented in a dense layer + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + config: RoadConfig, + variant: RoadVariant = "road_1", + group_size: int = 64, + init_weights: bool = True, + **kwargs, + ) -> None: + super().__init__() + RoadLayer.__init__(self, base_layer) + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + config=config, + ) + + 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._available_adapters: + 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) + + road_R = _get_delta_weight( + self.variant[active_adapter], + self.group_size[active_adapter], + self.road_theta[active_adapter].data, + self.road_alpha[active_adapter].data, + ) + w_data = torch.matmul(road_R, output.to(road_R.dtype)) + w_data = w_data.to(road_R.dtype).to(road_R.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) + + if self.get_base_layer().bias is not None: + bias = self.get_base_layer().bias + orig_dtype = bias.dtype + bias_data = bias.data + new_bias = torch.matmul(road_R, bias_data.to(road_R.dtype)) + bias.data = new_bias.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: + active_adapter = self.merged_adapters.pop() + if active_adapter in self._available_adapters: + 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) + + road_R = _get_delta_weight( + self.variant[active_adapter], + self.group_size[active_adapter], + self.road_theta[active_adapter].data, + self.road_alpha[active_adapter].data, + ) + inv_road_R = torch.linalg.inv(road_R.to(torch.float32)).to(road_R.dtype) + + w_data = torch.matmul(inv_road_R, output.to(road_R.dtype)) + w_data = w_data.to(road_R.dtype).to(road_R.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) + + if self.get_base_layer().bias is not None: + bias = self.get_base_layer().bias + orig_dtype = bias.dtype + bias_data = bias.data + new_bias = torch.matmul(inv_road_R, bias_data) + bias.data = new_bias.to(orig_dtype) + + 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) + # 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._available_adapters: + continue + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + result = self._cast_input_dtype(result, self.road_theta[active_adapter].dtype) + + result = _apply_road( + self.variant[active_adapter], + self.group_size[active_adapter], + self.road_theta[active_adapter], + self.road_alpha[active_adapter], + result, + ) + if requires_conversion: + x = x.to(expected_dtype) + + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "oft." + rep + + def dispatch_bnb_4bit(target: torch.nn.Module, adapter_name: str, road_config: RoadConfig, **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=road_config, **fourbit_kwargs) + + return new_module diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/road/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/road/config.py new file mode 100644 index 0000000000000000000000000000000000000000..26c37a1fd03d36baaff536ca33cae56231df7356 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/road/config.py @@ -0,0 +1,126 @@ +# 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 Literal, Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + + +RoadVariant = Literal["road_1", "road_2", "road_4"] + + +@dataclass +class RoadConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`RoadModel`]. RoAd adapter is proposed in + https://huggingface.co/papers/2409.00119. + + Args: + variant (Union[`RoadVariant`, `str`]): + The variant of the Road model to use. It can be one of road_1, road_2, or road_4. Refer to the paper for + more details. + - road_1: Uses the same scale and angle for all pairs of elements. + This variant has lowest number of parameters, it stores a number equal to the output hidden size of + parameters for each layer that RoAd is applied to. + - road_2: Uses the same scale and angle for each element. + This variant has 2x the number of parameters compared to road_1. + - road_4: Uses two different scales and angles for each ellement. + This variant has 4x the number of parameters compared to road_1. + group_size (`int`): + Group size defines how elements are grouped together into 2D vectors for rotation. Within each group + element 0 is paired with element group_size/2, then element 1 is paired with element group_size/2+1 and so + on. This has no effect on the model performance, since elements are unordered, however it has some effect + on inference speed when used in e.g. VLLM. For best speed group size of at least 32 or 64 (the default) is + recommended. Note that model hidden size (or hidden size per partition when used with tensor parallelism) + must be divisible by group_size, so for very small models you might need to reduce this parameter. + init_weights (`bool`): + Whether to perform initialization of RoAd weights. + 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/Conv1D modules are chosen (if + the model is a PreTrainedModel, the output layer excluded). 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. + modules_to_save (`List[str]`): + List of modules apart from Road layers to be set as trainable and saved in the final checkpoint. + """ + + variant: Union[str, RoadVariant] = field( + default="road_1", + metadata={"help": ("Variant of the Road model to use.")}, + ) + group_size: int = field( + default=64, + metadata={ + "help": ( + "Group size defines how elements are grouped together into 2D vectors for rotation. " + "Within each group element 0 is paired with element group_size/2, " + "then element 1 is paired with element group_size/2+1 and so on. " + "This has no effect on the model performance, since elements are unordered, " + "however it has some effect on inference speed when used in e.g. VLLM. " + "For best speed group size of at least 64 is recommended. " + "Note that model hidden size (or hidden size per partition when used with tensor parallelism) " + "must be divisible by group_size, so for very small models you might need to reduce this parameter." + ) + }, + ) + init_weights: bool = field( + default=True, + metadata={ + "help": ( + "Whether to initialize the weights of the RoAd layers with their default initialization. Don't change " + "this setting, except if you know exactly what you're doing." + ), + }, + ) + 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 Road." + "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'." + "This can also be a wildcard 'all-linear' which matches all linear/Conv1D " + "(if the model is a PreTrainedModel, the output layer excluded)." + "If 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." + ), + }, + ) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": ( + "List of modules apart from RoAd 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.ROAD + self.target_modules = ( + set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules + ) + if self.variant not in ["road_1", "road_2", "road_4"]: + raise ValueError(f"Invalid variant {self.variant} specified. Please choose from road_1, road_2 or road_4") + if self.group_size <= 0 or self.group_size % 2 != 0: + raise ValueError(f"The group_size must be divisible by 2 when using RoadLayer, but got {self.group_size}.") diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/road/layer.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/road/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..8af05a3356b9fc42635c654654a6218547d1e741 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/road/layer.py @@ -0,0 +1,416 @@ +# 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 Any, Optional + +import torch +from torch import nn + +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge + +from .config import RoadConfig, RoadVariant + + +class RoadLayer(BaseTunerLayer): + """ + Road layer. + + Generally the idea of RoAD is to split the input vector into many 2D vectors and rotate each 2D vector with its own + 2D rotation matrix. For additional flexibility, each rotation matrix is multiplied by a trainable scale. + + when applied to vector R @ x each pair of elements of x is transformed like this: `y₀ = x₀ * α * cosθ - xₙ * α * + sinθ` and `yₙ = x₀ * α * sinθ + xₙ * α * cosθ` + + The scales α and angles θ are learned for each pair of elements and, moreover, each of the 4 instances in the + rotation matrix may actually be different (when using variant 2 or 4). + + Note that instead of using two consecutive elements x₀ x₁ we first split the whole vector into groups and pair + elements from the first with the second half of the same group, which allows for more efficient inference + implementation. + + The adapter needs to only store the angles θ and scales α, rather than the full matrix R and the inference + implementation only needs to do elementwise vector multiplications. + + For merging the weights, we make use of the following formula: R @ (W @ x + b) = (R @ W) @ x + R @ b. The lhs part + is how it is used in unmerged state (using efficient elementwise implementation instead of matrix multiplication) + and the rhs part is how it is used in merged state where (R @ W) becomes the new weight matrix and R @ b becomes + the new bias. + + """ + + adapter_layer_names: tuple[str, ...] = ("road_theta", "road_alpha") + other_param_names: tuple[str, ...] = ("variant", "group_size") + + def __init__(self, base_layer: nn.Module, ephemeral_gpu_offload: bool = False, **kwargs) -> None: + self.base_layer = base_layer + self.variant = {} + self.group_size = {} + self.road_theta = nn.ParameterDict({}) + self.road_alpha = nn.ParameterDict({}) + + 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 TypeError(f"Unsupported layer type '{type(base_layer)}' encountered, cannot apply RoAd adapter.") + self.in_features = in_features + self.out_features = out_features + + @property + def _available_adapters(self) -> set[str]: + return {*self.road_theta} + + def update_layer( + self, + adapter_name, + config: RoadConfig, + inference_mode: bool = False, + ): + variant = config.variant + group_size = config.group_size + init_weights = config.init_weights + + self.variant[adapter_name] = variant + self.group_size[adapter_name] = group_size + + if self.out_features % group_size != 0: + raise ValueError( + f"The out_features of the base layer must be divisible by group_size ({group_size}) when using RoadLayer." + ) + + # Actual trainable parameters + if variant == "road_1": + size = self.out_features // 2 + elif variant == "road_2": + size = self.out_features + elif variant == "road_4": + size = self.out_features * 2 + else: + raise ValueError( + f"Unsupported variant {variant} for RoadLayer. Supported variants are road_1, road_2, and road_4." + ) + self.road_theta[adapter_name] = nn.Parameter(torch.empty(size)) + self.road_alpha[adapter_name] = nn.Parameter(torch.empty(size)) + + self.reset_parameters(adapter_name, init_weights) + self._move_adapter_to_device_of_base_layer(adapter_name) + + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def reset_parameters(self, adapter_name, init_weights): + if init_weights is False: + nn.init.normal_(self.road_theta[adapter_name].data, mean=0.0, std=0.5) + nn.init.normal_(self.road_alpha[adapter_name].data, mean=1.0, std=0.5) + return + nn.init.zeros_(self.road_theta[adapter_name].data) + nn.init.ones_(self.road_alpha[adapter_name].data) + + +class Linear(nn.Module, RoadLayer): + # Road implemented in a dense layer + def __init__( + self, + base_layer, + adapter_name: str, + config: RoadConfig, + **kwargs, + ) -> None: + super().__init__() + RoadLayer.__init__(self, base_layer, **kwargs) + + self._active_adapter = adapter_name + + self.update_layer( + adapter_name, + config=config, + ) + + def _check_forward_args(self, x, *args, **kwargs): + """Check if the arguments are compatible with the configs and state of the model""" + adapter_names = kwargs.get("adapter_names", None) + if adapter_names is None: + return + + if len(x) != len(adapter_names): + msg = ( + "Length of `adapter_names` should be the same as the number of inputs, but got " + f"{len(adapter_names)} and {len(x)} respectively." + ) + raise ValueError(msg) + + if self.merged: + # It is unclear what would be the right thing to do if users pass adapter_names and there are merged + # adapters. Therefore, it is better to raise an error in this case. + msg = "Cannot pass `adapter_names` when there are merged adapters, please call `unmerge_adapter` first." + raise ValueError(msg) + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> 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) + elif adapter_names is not None: + result = self._mixed_batch_forward(x, *args, adapter_names=adapter_names, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + torch_result_dtype = result.dtype + + for active_adapter in self.active_adapters: + if active_adapter not in self._available_adapters: + continue + + result = self._cast_input_dtype(result, self.road_theta[active_adapter].dtype) + result = _apply_road( + self.variant[active_adapter], + self.group_size[active_adapter], + self.road_theta[active_adapter], + self.road_alpha[active_adapter], + result, + ) + + result = result.to(torch_result_dtype) + + return result + + 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._available_adapters: + continue + + dtype = self.road_theta[active_adapter].data.dtype + + # getting the sub-batch, passing it to Road layers and updating the corresponding indices of the linear + # layer output + sub_batch = result[sub_batch_indices_list[i]].to(dtype) + result[sub_batch_indices_list[i]] = _apply_road( + self.variant[active_adapter], + self.group_size[active_adapter], + self.road_theta[active_adapter], + self.road_alpha[active_adapter], + sub_batch, + ) + + return result + + 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._available_adapters: + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.dtype + road_R = _get_delta_weight( + self.variant[active_adapter], + self.group_size[active_adapter], + self.road_theta[active_adapter].data, + self.road_alpha[active_adapter].data, + ) + 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() + orig_weight = torch.matmul(road_R.to(orig_dtype), orig_weight) + + if not torch.isfinite(orig_weight).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = orig_weight.contiguous().to(orig_dtype) + + if base_layer.bias is not None: + orig_bias = base_layer.bias.clone() + orig_bias = torch.matmul(road_R.to(orig_dtype), orig_bias) + + if not torch.isfinite(orig_bias).all(): + raise ValueError( + f"NaNs detected in the merged bias. The adapter {active_adapter} seems to be broken" + ) + + base_layer.bias.data = orig_bias.contiguous().to(orig_dtype) + else: + orig_weight = base_layer.weight.data + orig_weight = torch.matmul(road_R.to(orig_dtype), orig_weight) + base_layer.weight.data = orig_weight.contiguous().to(orig_dtype) + + if base_layer.bias is not None: + orig_bias = base_layer.bias.data + orig_bias = torch.matmul(road_R.to(orig_dtype), orig_bias) + base_layer.bias.data = orig_bias.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 + while len(self.merged_adapters) > 0: + # Going in reverse order + active_adapter = self.merged_adapters.pop() + if active_adapter in self._available_adapters: + weight = self.get_base_layer().weight + orig_dtype = weight.dtype + road_R = _get_delta_weight( + self.variant[active_adapter], + self.group_size[active_adapter], + self.road_theta[active_adapter].data, + self.road_alpha[active_adapter].data, + ) + # Since our matrix are not necessarily orthogonal we need inverse instead of transpose. + # In practice we expect this to basically always work since we start from block diagonal rotation matrix. + inv_road_R = torch.linalg.inv(road_R.to(torch.float32)).to(orig_dtype) + orig_weight = torch.matmul(inv_road_R, weight.data) + weight.data = orig_weight.contiguous() + + if self.get_base_layer().bias is not None: + orig_bias = torch.matmul(inv_road_R, self.get_base_layer().bias.data) + self.get_base_layer().bias.data = orig_bias.contiguous() + + def __repr__(self) -> str: + rep = super().__repr__() + return "road." + rep + + +def _get_delta_weight(variant: RoadVariant, group_size: int, road_theta: torch.Tensor, road_alpha: torch.Tensor): + first_col, second_col = _prepare_cols(variant, group_size, road_theta, road_alpha) + + # To help understand the logic below consider how rope embeddings work + # here it is similar, but done in groups. + # https://discuss.huggingface.co/t/is-llama-rotary-embedding-implementation-correct/44509/3 + + # First column is simply put on the main diagonal + output_tensor = torch.diag(first_col) + # For second column we need to swap each half groups and add minus sign + size = second_col.shape[0] + swapped_second_col = second_col.reshape(-1, 2, group_size // 2)[:, [1, 0], :].flatten() + rotated_diag_second_col = torch.diag(swapped_second_col).reshape(-1, 2, group_size // 2, size)[:, [1, 0], :, :] + rotated_diag_second_col[:, 0, :, :] *= -1 + rotated_diag_second_col = rotated_diag_second_col.reshape(size, size) + output_tensor += rotated_diag_second_col + + return output_tensor + + +def _prepare_cols( + variant: RoadVariant, group_size: int, road_theta: torch.Tensor, road_alpha: torch.Tensor +) -> tuple[torch.Tensor, torch.Tensor]: + # In inference mode, this can be cached + if variant == "road_1": + # In each group there are only group_size // 2 parameters that are reused + road_theta = road_theta.reshape(-1, group_size // 2).repeat_interleave(2, dim=0).flatten() + road_alpha = road_alpha.reshape(-1, group_size // 2).repeat_interleave(2, dim=0).flatten() + + theta_cos = road_theta.cos() + theta_sin = road_theta.sin() + + first_col = road_alpha * theta_cos + second_col = road_alpha * theta_sin + elif variant == "road_2": + # Each group has exactly group_size parameters + theta_cos = road_theta.cos() + theta_sin = road_theta.sin() + + first_col = road_alpha * theta_cos + second_col = road_alpha * theta_sin + elif variant == "road_4": + # Each group has 2*group_size parameters, first half used for first column, second half for second column + road_theta = road_theta.reshape(-1, 2, group_size) + theta_cos = road_theta[:, 0, :].cos().flatten() + theta_sin = road_theta[:, 1, :].sin().flatten() + road_alpha = road_alpha.reshape(-1, 2, group_size) + alpha_1 = road_alpha[:, 0, :].flatten() + alpha_2 = road_alpha[:, 1, :].flatten() + + first_col = alpha_1 * theta_cos + second_col = alpha_2 * theta_sin + else: + raise ValueError( + f"Unsupported variant {variant} for RoadLayer. Supported variants are road_1, road_2, and road_4." + ) + + return first_col, second_col + + +def _apply_road( + variant: RoadVariant, group_size: int, road_theta: torch.Tensor, road_alpha: torch.Tensor, x: torch.Tensor +): + first_col, second_col = _prepare_cols(variant, group_size, road_theta, road_alpha) + + # Split in half groups and join back + # See equation 4 in the RoAD paper + x_grouped = x.reshape(-1, 2, group_size // 2) + x1 = x_grouped[:, 0, :] + x2 = x_grouped[:, 1, :] + rotate_half_x = torch.stack((-x2, x1), dim=1).reshape(x.shape) + result = x * first_col + rotate_half_x * second_col + return result + + +def dispatch_default( + target: torch.nn.Module, + adapter_name: str, + road_config: RoadConfig, + **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, config=road_config, **kwargs) + + return new_module diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/road/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/road/model.py new file mode 100644 index 0000000000000000000000000000000000000000..6beeb5a66bd015a248ce64de763f732e77098f17 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/road/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 operator +from contextlib import contextmanager +from functools import partial + +from torch import nn + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available +from peft.tuners.road.config import RoadConfig +from peft.tuners.tuners_utils import ( + BaseTuner, + get_device_map, +) +from peft.utils import TRANSFORMERS_MODELS_TO_ROAD_TARGET_MODULES_MAPPING + +from .layer import RoadLayer, dispatch_default + + +def _adapter_names_pre_forward_hook(target, args, kwargs, adapter_names): + # pre-forward hook to inject the adapter_names argument when using mixed adapter batches inference + kwargs["adapter_names"] = adapter_names + return args, kwargs + + +class RoadModel(BaseTuner): + prefix: str = "road_" + tuner_layer_cls = RoadLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_ROAD_TARGET_MODULES_MAPPING + + def _create_and_replace( + self, + road_config: RoadConfig, + adapter_name: str, + target: nn.Module, + target_name: str, + parent: nn.Module, + current_key, + ) -> None: + if current_key is None: + raise ValueError("Current Key shouldn't be `None`") + + kwargs = { + "loaded_in_8bit": getattr(self.model, "is_loaded_in_8bit", False), + "loaded_in_4bit": getattr(self.model, "is_loaded_in_4bit", False), + } + # for torchao merging, we need the get_apply_tensor_subclass from the quantization config + try: + kwargs["get_apply_tensor_subclass"] = operator.attrgetter( + "hf_quantizer.quantization_config.get_apply_tensor_subclass" + )(self.model) + except AttributeError: + pass + + if isinstance(target, RoadLayer): + target.update_layer( + adapter_name, + config=road_config, + ) + else: + device_map = get_device_map(self.model) + new_module = self._create_new_module(road_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) + + @staticmethod + def _create_new_module(road_config: RoadConfig, adapter_name, target, **kwargs): + 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_default, + ] + ) + + new_module = None + for dispatcher in dispatchers: + new_module = dispatcher(target, adapter_name, road_config=road_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`." + ) + + return new_module + + @contextmanager + def _enable_peft_forward_hooks(self, *args, **kwargs): + # If adapter_names is passed as an argument, we inject it into the forward arguments. + adapter_names = kwargs.pop("adapter_names", None) + if adapter_names is None: + # nothing to do + yield + return + + if self.training: + raise ValueError("Cannot pass `adapter_names` when the model is in training mode.") + + # Check that users only passed actually existing adapters. + # Note: We cannot do this on the layer level, as each individual layer may not have each adapter. Still, we want + # to check that there is at least one layer with the given name, or else something like typos can easily slip. + expected_adapters = set() + for layer in self.modules(): + if isinstance(layer, RoadLayer): + expected_adapters |= layer.road_theta.keys() + unique_adapters = {name for name in adapter_names if name != "__base__"} + unexpected_adapters = unique_adapters - expected_adapters + if unexpected_adapters: + raise ValueError(f"Trying to infer with non-existing adapter(s): {', '.join(sorted(unexpected_adapters))}") + + hook_handles = [] + for module in self.modules(): + if isinstance(module, RoadLayer): + pre_forward = partial(_adapter_names_pre_forward_hook, adapter_names=adapter_names) + handle = module.register_forward_pre_hook(pre_forward, with_kwargs=True) + hook_handles.append(handle) + + # TODO LoRA also has hooks for beam search, ignore this for now + + yield + + for handle in hook_handles: + handle.remove() diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/shira/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/shira/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d5391b96059fc08580a12adb8b216b3a8bfd8024 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/shira/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/shira/config.py new file mode 100644 index 0000000000000000000000000000000000000000..d868e51490637c47c13b3c0ae2cb1f5c88cb7ebc --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/shira/layer.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/shira/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..db80e7356955b3737e68c89ed603d323b7abc9d1 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/shira/layer.py @@ -0,0 +1,224 @@ +# 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.functional as F +from torch import nn + +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge + +from .config import ShiraConfig + + +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, + config: ShiraConfig, + inference_mode: bool = False, + **kwargs, + ): + init_weights = config.init_weights + + 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, + config: ShiraConfig, + r: int = 0, + **kwargs, + ) -> None: + super().__init__() + ShiraLayer.__init__(self, base_layer, **kwargs) + self.fan_in_fan_out = config.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, config=config) + + 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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/shira/mask_functions.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/shira/mask_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..3304989b3f59c92400ed7d518bca3c6be437f35e --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/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 +from torch import 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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/shira/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/shira/model.py new file mode 100644 index 0000000000000000000000000000000000000000..d07b9a2d49c3bf57564556b9cb74ad2e5111faa6 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/shira/model.py @@ -0,0 +1,139 @@ +# 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, + config=shira_config, + ) + 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): + _ = 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 shira_config.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." + ) + shira_config.fan_in_fan_out = False + else: + raise TypeError( + 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, + config=shira_config, + r=shira_config.r, + **kwargs, + ) + + return new_module diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/tinylora/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/tinylora/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d8287a4fa1ce5609d2de1b64862207541108051b --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/tinylora/__init__.py @@ -0,0 +1,25 @@ +# Copyright 2026-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 TinyLoraConfig +from .layer import Embedding, Linear, TinyLoraLayer +from .model import TinyLoraModel + + +__all__ = ["Embedding", "Linear", "TinyLoraConfig", "TinyLoraLayer", "TinyLoraModel"] + + +register_peft_method(name="tinylora", config_cls=TinyLoraConfig, model_cls=TinyLoraModel, prefix="tinylora_") diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/tinylora/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/tinylora/config.py new file mode 100644 index 0000000000000000000000000000000000000000..24a9e90358e96295355e1f26995dfb0a12174e88 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/tinylora/config.py @@ -0,0 +1,202 @@ +# Copyright 2026-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 Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class TinyLoraConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`TinyLoraModel`]. + + TinyLoRA is an extremely parameter-efficient fine-tuning method based on the paper "Learning to Reason in 13 + Parameters" (arXiv:2602.04118). It uses SVD decomposition of frozen weights and projects a tiny trainable vector + through fixed random tensors. + + Paper: https://arxiv.org/abs/2602.04118 + + Args: + r (`int`, *optional*, defaults to `2`): + SVD rank for the frozen U, Sigma, V decomposition. The paper recommends r=2. + u (`int`, *optional*, defaults to `64`): + Trainable vector dimension per group. This controls the expressivity of the adaptation. Can be as low as + 1-13 for extreme parameter efficiency. + weight_tying (`float`, *optional*, defaults to `0.0`): + Degree of weight tying across target modules, as a ratio between 0.0 and 1.0. Controls how many modules + share the same trainable vector v. 0.0 means no sharing (each module has its own v). 1.0 means full sharing + (all modules share one v). Values in between give partial sharing. + projection_seed (`int`, *optional*, defaults to `42`): + Random seed for generating the fixed projection matrices P. + save_projection (`bool`, *optional*, defaults to `True`): + Whether to save the projection tensors P in the state dict. If False, they will be regenerated from the + seed when loading. + init_v_bound (`float`, *optional*, defaults to `0.02`): + Uniform initialization bound for the trainable vector v. Values are initialized in [-init_v_bound, + init_v_bound]. + target_modules (`Union[List[str], str]`, *optional*): + The names of the modules to apply TinyLoRA to. This can be a list of module names (e.g. `['q_proj', + 'v_proj']`), a regex pattern (e.g. `'.*decoder.*(q|v)_proj$'`), or the special keyword `"all-linear"` to + target all linear modules. Only `nn.Linear`, `nn.Embedding`, and `transformers.pytorch_utils.Conv1D` layers + are supported. + tinylora_dropout (`float`, *optional*, defaults to `0.0`): + The dropout probability for TinyLoRA layers. + fan_in_fan_out (`bool`, *optional*, defaults to `False`): + 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). + bias (`str`, *optional*, defaults to `"none"`): + Bias type for TinyLoRA. Can be 'none', 'all' or 'tinylora_only'. + modules_to_save (`List[str]`, *optional*): + List of modules apart from TinyLoRA layers to be set as trainable and saved. + init_weights (`bool` | `Literal["uniform"]`, *optional*, defaults to `True`): + How to initialize the trainable vector v. Passing `True` (default) initializes v to zeros, making the + adapter a no-op (identity operation). Passing `"uniform"` initializes v with uniform random values in + `[-init_v_bound, init_v_bound]`. Passing `False` leaves v uninitialized (for advanced use cases). + layers_to_transform (`Union[List[int], int]`, *optional*): + The layer indexes to transform. If specified, only these layers will be adapted. + layers_pattern (`Optional[Union[List[str], str]]`, *optional*): + The layer pattern name, used only if `layers_to_transform` is different from `None`. + + Example: + ```python + from peft import get_peft_model, TinyLoraConfig + + config = TinyLoraConfig( + r=2, # SVD rank (paper recommends 2) + u=64, # Trainable vector dimension + weight_tying=0.0, # No weight tying (0.0 = none, 1.0 = full) + target_modules=["q_proj", "v_proj"], + projection_seed=42, + ) + model = get_peft_model(base_model, config) + ``` + """ + + r: int = field(default=2, metadata={"help": "TinyLoRA SVD rank (frozen)"}) + u: int = field(default=64, metadata={"help": "Trainable vector dimension per group"}) + weight_tying: float = field( + default=0.0, + metadata={ + "help": ( + "Degree of weight tying across target modules (0.0 to 1.0). " + "0.0 = no sharing, 1.0 = full sharing (all modules share one v)." + ) + }, + ) + projection_seed: int = field( + default=42, + metadata={ + "help": ( + "Random seed for generating the fixed projection matrices P. Used for initialising " + "projections 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 projection tensors P in the state dict. If False, they will be " + "regenerated from the seed when loading. Setting to True increases checkpoint size but " + "guarantees reproducibility across system configurations." + ) + }, + ) + init_v_bound: float = field(default=0.02, metadata={"help": "Uniform init bound for v in [-bound, bound]"}) + target_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": ( + "List of module names, regex expression, or the keyword 'all-linear' to replace with TinyLoRA. " + "For example, ['q_proj', 'v_proj'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'. " + "Only nn.Linear, nn.Embedding, and transformers.pytorch_utils.Conv1D layers are supported." + ) + }, + ) + tinylora_dropout: float = field(default=0.0, metadata={"help": "TinyLoRA dropout"}) + 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: str = field( + default="none", metadata={"help": "Bias type for TinyLoRA. Can be 'none', 'all' or 'tinylora_only'"} + ) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": ( + "List of modules apart from TinyLoRA 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: Union[bool, str] = field( + default=True, + metadata={ + "help": ( + "How to initialize the trainable vector v. True (default) initializes v to zeros, making the " + "adapter a no-op. 'uniform' initializes v with uniform random values. False leaves v uninitialized." + ), + }, + ) + layers_to_transform: Optional[Union[list[int], int]] = field( + default=None, + metadata={ + "help": ( + "The layer indexes to transform. If 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'`." + ) + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.TINYLORA + self.target_modules = ( + set(self.target_modules) if isinstance(self.target_modules, list) else self.target_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 not self.save_projection: + warnings.warn( + "Specified to not save projection tensors P within the state dictionary. They will be restored " + "using the PRNG key stored in `config.projection_seed`. Consider setting `config.save_projection` " + "to `True` to guarantee restoring the checkpoint correctly on all system configurations." + ) + if self.r <= 0: + raise ValueError(f"`r` should be a positive integer value but the value passed is {self.r}") + if self.u <= 0: + raise ValueError(f"`u` should be a positive integer value but the value passed is {self.u}") + if not (0.0 <= self.weight_tying <= 1.0): + raise ValueError( + f"`weight_tying` should be a float between 0.0 and 1.0 but the value passed is {self.weight_tying}" + ) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/tinylora/layer.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/tinylora/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..a533820c5a18b1180260911daf1fc26386b590ab --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/tinylora/layer.py @@ -0,0 +1,608 @@ +# Copyright 2026-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.nn.functional as F +from torch import nn + +from peft.tuners.tuners_utils import BaseTunerLayer, _get_in_out_features, check_adapters_to_merge +from peft.utils.other import transpose + +from .._buffer_dict import BufferDict +from .config import TinyLoraConfig + + +class TinyLoraLayer(BaseTunerLayer): + """ + TinyLoRA layer implementation. + + TinyLoRA is based on LoRA-XS and uses SVD decomposition of frozen weights. The key innovation is replacing the + trainable r×r matrix R with: + R = sum_i(v[i] * P[i]) + where v is a tiny trainable vector and P_i are fixed random projection matrices. + + The forward pass computes: + result += lora_B(R(lora_A(x))) + where lora_A and lora_B are frozen SVD components. + """ + + # List all names of layers that may contain adapter weights + # Note: tinylora_v is a reference to the per-adapter ParameterDict (shared across layers in the same group) + adapter_layer_names = ("tinylora_v",) + other_param_names = ("tinylora_A", "tinylora_B", "tinylora_P") + + def __init__(self, base_layer: nn.Module, layer_idx: int, **kwargs): + self.base_layer = base_layer + self.r = {} + self.u = {} + self.tinylora_dropout = nn.ModuleDict({}) + self._layer_idx = layer_idx # used for deterministic seeding of projection matrices + + # Reference to the model-level ModuleDict (set during update_layer). + # PyTorch won't double-register the same ModuleDict object across layers. + self.tinylora_v: Optional[nn.ModuleDict] = None + + # Direct references to this adapter's v parameter, cached for O(1) forward pass access. + # Plain dict to avoid PyTorch double-registering the same Parameter. + self._tinylora_v_ref: dict[str, nn.Parameter] = {} + + # Frozen SVD components as buffers (following LoRA-XS convention) + # tinylora_A corresponds to V from SVD (shape: r x in_features) + # tinylora_B corresponds to U @ diag(S) from SVD (shape: out_features x r) + self.tinylora_A = BufferDict({}, persistent=True) + self.tinylora_B = BufferDict({}, persistent=True) + + # Fixed random projection tensors P ∈ R^{u×r×r} + self.tinylora_P = BufferDict({}, persistent=True) + + # Mark the weight as unmerged + self._disable_adapters = False + self.merged_adapters = [] + + self.in_features, self.out_features = _get_in_out_features(self.get_base_layer()) + self.kwargs = kwargs + + def _all_available_adapter_names(self) -> list[str]: + """Return a sorted list of all available adapter names.""" + adapter_names = set() + adapter_names.update(self._tinylora_v_ref.keys()) + for name in self.other_param_names: + attr = getattr(self, name, None) + if attr is not None and hasattr(attr, "keys"): + adapter_names.update(attr.keys()) + return sorted(adapter_names) + + def delete_adapter(self, adapter_name: str) -> None: + """Delete an adapter from the layer.""" + # Delete direct v reference + if adapter_name in self._tinylora_v_ref: + del self._tinylora_v_ref[adapter_name] + + # Delete from other params that use adapter name directly + for attr in self.other_param_names: + param_dict = getattr(self, attr, None) + if param_dict is not None and adapter_name in param_dict: + del param_dict[adapter_name] + + # Delete r and u tracking + if adapter_name in self.r: + del self.r[adapter_name] + if adapter_name in self.u: + del self.u[adapter_name] + + # Delete dropout layer + if adapter_name in self.tinylora_dropout: + del self.tinylora_dropout[adapter_name] + + # Handle active adapters + if adapter_name in self.active_adapters: + active_adapters = self.active_adapters[:] + active_adapters.remove(adapter_name) + if active_adapters: + self.set_adapter(active_adapters) + else: + remaining_adapters = self._all_available_adapter_names() + if not remaining_adapters: + self.set_adapter([]) + else: + new_active_adapter = remaining_adapters[0] + warnings.warn( + f"Adapter {adapter_name} was active which is now deleted. Setting active adapter to " + f"{new_active_adapter}." + ) + self.set_adapter(new_active_adapter) + + def supports_lora_conversion(self, adapter_name: str = "default") -> bool: + return True + + def _get_layer_seed(self, adapter_name: str, base_seed: int) -> int: + """Get a deterministic seed for this layer's projection matrices.""" + return base_seed + self._layer_idx + + def update_layer( + self, + adapter_name: str, + tinylora_v: nn.ModuleDict, + v_key: str, + r: int, + config: TinyLoraConfig, + **kwargs, + ) -> None: + """Initialize layer with SVD decomposition and projection tensors.""" + # Extract config values + u = config.u + tinylora_dropout = config.tinylora_dropout + projection_seed = config.projection_seed + inference_mode = config.inference_mode + fan_in_fan_out = config.fan_in_fan_out + + if r <= 0: + raise ValueError(f"`r` should be a positive integer value but the value passed is {r}") + if u <= 0: + raise ValueError(f"`u` should be a positive integer value but the value passed is {u}") + + self.u[adapter_name] = u + + if tinylora_dropout > 0.0: + tinylora_dropout_layer = nn.Dropout(p=tinylora_dropout) + else: + tinylora_dropout_layer = nn.Identity() + + self.tinylora_dropout.update(nn.ModuleDict({adapter_name: tinylora_dropout_layer})) + + # Store reference to model-level ModuleDict (for base class parameter management) + self.tinylora_v = tinylora_v + # Cache direct reference to this adapter's v parameter for O(1) forward pass access + self._tinylora_v_ref[adapter_name] = tinylora_v[adapter_name][v_key] + + # Compute truncated SVD of base weights (following LoRA-XS convention) + # actual_r may be less than r if matrix dimensions are smaller + self._init_svd(adapter_name, r, fan_in_fan_out) + + # Initialize random projection tensors P using the actual rank + self._init_projection(adapter_name, u, projection_seed) + + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def _init_svd(self, adapter_name: str, r: int, fan_in_fan_out: bool) -> None: + """ + Compute truncated SVD of base weights and store as frozen buffers. + + Compute truncated SVD and distribute singular values to both A and B: + - W = U @ S @ V^T (full SVD) + - We store: tinylora_A = diag(sqrt(S[:r])) @ V[:r, :] (shape: r x in_features) + - We store: tinylora_B = U[:, :r] @ diag(sqrt(S[:r])) (shape: out_features x r) + + Distributing S equally avoids imbalanced norms between A and B. This allows: delta_W = tinylora_B @ R @ + tinylora_A. + """ + base_layer = self.get_base_layer() + weight = base_layer.weight.data + + # Handle Conv1D which stores weights as (in, out) + weight = transpose(weight, fan_in_fan_out) + + dtype = weight.dtype + + # Compute SVD in float32 for numerical stability + # W has shape (out_features, in_features) + weight_fp32 = weight.float() + U, S, Vh = torch.linalg.svd(weight_fp32, full_matrices=False) + + # The actual rank is limited by the matrix dimensions + max_rank = min(weight.shape[0], weight.shape[1]) + actual_r = min(r, max_rank) + + # Truncate to actual rank + U_r = U[:, :actual_r].to(dtype) + S_r = S[:actual_r].to(dtype) + V_r = Vh[:actual_r, :].to(dtype) + sqrt_S_r = torch.sqrt(S_r) + + # Distribute singular values equally to both A and B via sqrt(S_r) + # tinylora_A = diag(sqrt(S_r)) @ V_r (actual_r x in_features) + # tinylora_B = U_r @ diag(sqrt(S_r)) (out_features x actual_r) + # Use .contiguous() to ensure tensors can be saved with safetensors + self.tinylora_A[adapter_name] = (sqrt_S_r.unsqueeze(1) * V_r).contiguous() + self.tinylora_B[adapter_name] = (U_r * sqrt_S_r.unsqueeze(0)).contiguous() + self.r[adapter_name] = actual_r + + def _init_projection(self, adapter_name: str, u: int, base_seed: int): + """Initialize fixed random projection tensors P ∈ R^{u×r×r}.""" + seed = self._get_layer_seed(adapter_name, base_seed) + gen = torch.Generator().manual_seed(seed) + r = self.r[adapter_name] + + # P has shape (u, r, r) + # Note: The paper describes P as "fixed random matrices" but does not specify the distribution. + # We sample from N(0, 1/r) which is standard for random projections + # (see Johnson-Lindenstrauss lemma: https://en.wikipedia.org/wiki/Johnson-Lindenstrauss_lemma). + P = torch.normal(mean=0.0, std=1.0 / (r**0.5), size=(u, r, r), generator=gen) + self.tinylora_P[adapter_name] = P + + def _compute_R(self, adapter_name: str) -> torch.Tensor: + """Reconstruct R matrix from v and P: R = sum_i(v[i] * P[i]).""" + v = self._tinylora_v_ref[adapter_name] # Shape: (u,) + P = self.tinylora_P[adapter_name] # Shape: (u, r, r) + + # Move P to same device/dtype as v + P = P.to(device=v.device, dtype=v.dtype) + + # R = sum over i of v[i] * P[i] + R = torch.einsum("i,ijk->jk", v, P) # Shape: (r, r) + return R + + def get_delta_weight(self, adapter_name: str) -> torch.Tensor: + """ + Compute delta_W = tinylora_B @ R @ tinylora_A for merging. + + Returns weight update in the same shape as the base layer weight. For Conv1D layers (fan_in_fan_out=True), the + result is transposed to match the (in_features, out_features) convention. + """ + A = self.tinylora_A[adapter_name] # (r, in_features) + B = self.tinylora_B[adapter_name] # (out_features, r) + R = self._compute_R(adapter_name) # (r, r) + + device = A.device + dtype = A.dtype + + # Move components to same device/dtype + B = B.to(device=device, dtype=dtype) + R = R.to(device=device, dtype=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 + cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16) + + if cast_to_fp32: + A = A.float() + B = B.float() + R = R.float() + + # delta_W = B @ R @ A + # B: (out, r), R: (r, r), A: (r, in) + # Result: (out, in) + delta = B @ R @ A + + # Transpose for Conv1D layers which store weights as (in, out) + fan_in_fan_out = getattr(self, "fan_in_fan_out", False) + delta = transpose(delta, fan_in_fan_out) + + if cast_to_fp32: + delta = delta.to(dtype=dtype) + + return delta + + +class Linear(nn.Linear, TinyLoraLayer): + """TinyLoRA implemented in a dense layer.""" + + def __init__( + self, + base_layer: nn.Module, + tinylora_v: nn.ModuleDict, + v_key: str, + adapter_name: str, + config: TinyLoraConfig, + **kwargs, + ) -> None: + # this gets the init from nn.Linear's super perspective, i.e. nn.Module.__init__ + super(nn.Linear, self).__init__() + TinyLoraLayer.__init__(self, base_layer, **kwargs) + + self.fan_in_fan_out = config.fan_in_fan_out + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + tinylora_v, + v_key, + config.r, + config, + ) + self.is_target_conv_1d_layer = kwargs.get("is_target_conv_1d_layer", False) + + 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.tinylora_A.keys(): + base_layer = self.get_base_layer() + if safe_merge: + orig_weights = base_layer.weight.data.clone() + delta_weight = self.get_delta_weight(active_adapter) + orig_weights += delta_weight + + 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: + delta_weight = self.get_delta_weight(active_adapter) + base_layer.weight.data += delta_weight + + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """Unmerge all merged adapters 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 in self.tinylora_A.keys(): + delta_weight = self.get_delta_weight(active_adapter) + self.get_base_layer().weight.data -= delta_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: + result = self.base_layer(x, *args, **kwargs) + for active_adapter in self.active_adapters: + if active_adapter not in self.tinylora_A.keys(): + continue + + A = self.tinylora_A[active_adapter] # (r, in_features) + B = self.tinylora_B[active_adapter] # (out_features, r) + R = self._compute_R(active_adapter) # (r, r) + + dropout = self.tinylora_dropout[active_adapter] + x_dropped = dropout(x) + x_dropped = x_dropped.to(A.dtype) + + # Move components to input device + device = x_dropped.device + A = A.to(device) + B = B.to(device) + R = R.to(device) + + # Forward computation following LoRA-XS pattern: + # delta = x @ A^T @ R^T @ B^T + # Using F.linear(x, W) = x @ W^T: + # h = F.linear(x, A) -> x @ A^T -> (batch, seq, r) + # h = F.linear(h, R) -> h @ R^T -> (batch, seq, r) + # delta = F.linear(h, B) -> h @ B^T -> (batch, seq, out) + h = F.linear(x_dropped, A) # (batch, seq, r) + h = F.linear(h, R) # (batch, seq, r) + delta = F.linear(h, B) # (batch, seq, out) + + result = result + delta + + result = result.to(previous_dtype) + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "tinylora." + rep + + +class Embedding(nn.Module, TinyLoraLayer): + """TinyLoRA implemented in an Embedding layer.""" + + def __init__( + self, + base_layer: nn.Module, + tinylora_v: nn.ModuleDict, + v_key: str, + adapter_name: str, + config: TinyLoraConfig, + **kwargs, + ) -> None: + super().__init__() + TinyLoraLayer.__init__(self, base_layer, **kwargs) + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + tinylora_v, + v_key, + config.r, + config, + ) + + def update_layer( + self, + adapter_name: str, + tinylora_v: nn.ModuleDict, + v_key: str, + r: int, + config, + **kwargs, + ) -> None: + """Initialize layer with SVD decomposition and projection tensors.""" + # Extract config values + u = config.u + tinylora_dropout = config.tinylora_dropout + projection_seed = config.projection_seed + inference_mode = config.inference_mode + + if r <= 0: + raise ValueError(f"`r` should be a positive integer value but the value passed is {r}") + if u <= 0: + raise ValueError(f"`u` should be a positive integer value but the value passed is {u}") + + self.u[adapter_name] = u + + if tinylora_dropout > 0.0: + tinylora_dropout_layer = nn.Dropout(p=tinylora_dropout) + else: + tinylora_dropout_layer = nn.Identity() + + self.tinylora_dropout.update(nn.ModuleDict({adapter_name: tinylora_dropout_layer})) + + # Store reference to model-level ModuleDict (for base class parameter management) + self.tinylora_v = tinylora_v + # Cache direct reference to this adapter's v parameter for O(1) forward pass access + self._tinylora_v_ref[adapter_name] = tinylora_v[adapter_name][v_key] + + # Compute truncated SVD of embedding weights + self._init_svd_embedding(adapter_name, r) + + # Initialize random projection tensors P using the actual rank + self._init_projection(adapter_name, u, projection_seed) + + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def _init_svd_embedding(self, adapter_name: str, r: int) -> None: + """ + Compute truncated SVD of embedding weights and store as frozen buffers. + + Embedding weight shape: (num_embeddings, embedding_dim) We treat this as W where: + - W = U @ S @ V^T (full SVD) + - tinylora_A = diag(sqrt(S[:r])) @ V[:r, :] (shape: r x embedding_dim) + - tinylora_B = U[:, :r] @ diag(sqrt(S[:r])) (shape: num_embeddings x r) + """ + base_layer = self.get_base_layer() + weight = base_layer.weight.data # (num_embeddings, embedding_dim) + + dtype = weight.dtype + + # Compute SVD in float32 for numerical stability + weight_fp32 = weight.float() + U, S, Vh = torch.linalg.svd(weight_fp32, full_matrices=False) + + # The actual rank is limited by the matrix dimensions + max_rank = min(weight.shape[0], weight.shape[1]) + actual_r = min(r, max_rank) + + # Truncate to actual rank + U_r = U[:, :actual_r].to(dtype) + S_r = S[:actual_r].to(dtype) + V_r = Vh[:actual_r, :].to(dtype) + sqrt_S_r = torch.sqrt(S_r) + + # Distribute singular values equally to both A and B via sqrt(S_r) + self.tinylora_A[adapter_name] = (sqrt_S_r.unsqueeze(1) * V_r).contiguous() + self.tinylora_B[adapter_name] = (U_r * sqrt_S_r.unsqueeze(0)).contiguous() + self.r[adapter_name] = actual_r + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """Merge the active adapter weights into the base weights.""" + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + return + + for active_adapter in adapter_names: + if active_adapter in self.tinylora_A.keys(): + base_layer = self.get_base_layer() + if safe_merge: + orig_weights = base_layer.weight.data.clone() + delta_weight = self.get_delta_weight(active_adapter) + orig_weights += delta_weight + + 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: + delta_weight = self.get_delta_weight(active_adapter) + base_layer.weight.data += delta_weight + + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """Unmerge all merged adapters 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 in self.tinylora_A.keys(): + delta_weight = self.get_delta_weight(active_adapter) + self.get_base_layer().weight.data -= delta_weight + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + 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) + + for active_adapter in self.active_adapters: + if active_adapter not in self.tinylora_A.keys(): + continue + + A = self.tinylora_A[active_adapter] # (r, embedding_dim) + B = self.tinylora_B[active_adapter] # (num_embeddings, r) + R = self._compute_R(active_adapter) # (r, r) + + dropout = self.tinylora_dropout[active_adapter] + + # Move components to input device + device = result.device + dtype = result.dtype + A = A.to(device=device, dtype=dtype) + B = B.to(device=device, dtype=dtype) + R = R.to(device=device, dtype=dtype) + + # For embedding, we need to: + # 1. Look up B[x] to get the low-rank representation (batch, seq, r) + # 2. Multiply by R to get (batch, seq, r) + # 3. Multiply by A to get the delta (batch, seq, embedding_dim) + # delta = B[x] @ R @ A + + # B[x]: embedding lookup in the low-rank space + after_B = F.embedding(x, B) # (batch, seq, r) + after_B = dropout(after_B) + + # Multiply by R and A + after_R = after_B @ R # (batch, seq, r) + delta = after_R @ A # (batch, seq, embedding_dim) + + result = result + delta + + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "tinylora." + rep diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/tinylora/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/tinylora/model.py new file mode 100644 index 0000000000000000000000000000000000000000..bf10cf61b6a2b711fdefe2c51e6a23a4c0849031 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/tinylora/model.py @@ -0,0 +1,306 @@ +# Copyright 2026-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 torch import nn +from transformers.pytorch_utils import Conv1D + +from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer +from peft.utils import ( + TRANSFORMERS_MODELS_TO_TINYLORA_TARGET_MODULES_MAPPING, +) + +from ..tuners_utils import _maybe_include_all_linear_layers +from .config import TinyLoraConfig +from .layer import Embedding, Linear, TinyLoraLayer + + +class TinyLoraModel(BaseTuner): + """ + Creates TinyLoRA model from a pretrained transformers model. + + TinyLoRA is an extremely parameter-efficient fine-tuning method that uses SVD decomposition of frozen weights and + projects a tiny trainable vector through fixed random tensors. Based on the paper "Learning to Reason in 13 + Parameters" (arXiv:2602.04118). + + Args: + model ([`~transformers.PreTrainedModel`]): The model to be adapted. + config ([`TinyLoraConfig`]): The configuration of the TinyLoRA 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 TinyLoRA model. + + Example: + ```python + >>> from transformers import AutoModelForCausalLM + >>> from peft import TinyLoraConfig, get_peft_model + + >>> base_model = AutoModelForCausalLM.from_pretrained("facebook/opt-125m") + >>> config = TinyLoraConfig(r=2, u=64, target_modules=["q_proj", "v_proj"]) + >>> model = get_peft_model(base_model, config) + ``` + + **Attributes**: + - **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted. + - **peft_config** ([`TinyLoraConfig`]): The configuration of the TinyLoRA model. + """ + + prefix: str = "tinylora_" + tuner_layer_cls = TinyLoraLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_TINYLORA_TARGET_MODULES_MAPPING + + def __init__(self, model, config, adapter_name, low_cpu_mem_usage=False, **kwargs): + super().__init__(model, config, adapter_name, low_cpu_mem_usage, **kwargs) + + def _init_tinylora_v(self, config: TinyLoraConfig, adapter_name: str) -> None: + """Re-initialize the tinylora_v vectors with uniform random values.""" + if adapter_name in self.tinylora_v: + for v in self.tinylora_v[adapter_name].values(): + nn.init.uniform_(v, -config.init_v_bound, config.init_v_bound) + + def _pre_injection_hook(self, model: nn.Module, config: TinyLoraConfig, adapter_name: str) -> None: + """Initialize shared trainable vectors on first adapter creation.""" + # Nested structure: tinylora_v[adapter_name][str(group_idx)] = nn.Parameter + if not hasattr(self, "tinylora_v"): + self.tinylora_v = nn.ModuleDict({}) + + def _build_target_key_mapping(self, config: TinyLoraConfig) -> dict[str, int]: + """Build an ordered mapping from target module key to index. + + Iterates the model in the same order as ``inject_adapter`` to assign each target module a deterministic index + used for group assignment (weight_tying) and projection seeding. + """ + 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) + + # Also match TinyLoraLayer since modules may already be wrapped when adding a second adapter + target_types = (nn.Linear, Conv1D, nn.Embedding, TinyLoraLayer) + + mapping: dict[str, int] = {} + idx = 0 + for key, module in self.model.named_modules(): + if not self._check_target_module_exists(peft_config, key): + continue + if isinstance(module, target_types): + mapping[key] = idx + idx += 1 + + return mapping + + def _check_new_adapter_config(self, config: TinyLoraConfig) -> None: + """Check the config when a new adapter is being added.""" + super()._check_new_adapter_config(config) + + save_projection_unique_values = sorted({c.save_projection for c in self.peft_config.values()}) + if len(save_projection_unique_values) > 1: + raise TypeError( + "TinyLoRA projection tensors must be saved for all adapters or none, but got multiple different values: " + f"{save_projection_unique_values}" + ) + + def _create_and_replace( + self, + tinylora_config: TinyLoraConfig, + adapter_name: str, + target: nn.Module, + target_name: str, + parent: nn.Module, + current_key: str, + **optional_kwargs, + ): + if current_key is None: + raise ValueError("Current Key shouldn't be `None`") + + # Build the target key mapping lazily on first call per injection cycle. + # This is needed because add_adapter calls inject_adapter directly without _pre_injection_hook. + if not hasattr(self, "_target_key_to_idx") or current_key not in self._target_key_to_idx: + self._target_key_to_idx = self._build_target_key_mapping(tinylora_config) + + # Look up the deterministic index for this module + layer_idx = self._target_key_to_idx[current_key] + num_target_layers = len(self._target_key_to_idx) + + # Determine the group for this layer based on weight_tying + # weight_tying=0.0 → num_groups = num_target_layers (no sharing) + # weight_tying=1.0 → num_groups = 1 (full sharing) + num_groups = max(1, round(num_target_layers * (1.0 - tinylora_config.weight_tying))) + group_size = max(1, num_target_layers // num_groups) + group_idx = min(layer_idx // group_size, num_groups - 1) + v_key = str(group_idx) + + # Initialize the adapter's ParameterDict if not present + if adapter_name not in self.tinylora_v: + self.tinylora_v[adapter_name] = nn.ParameterDict({}) + + # Initialize v for this group if not already done + if v_key not in self.tinylora_v[adapter_name]: + # Get dtype from target layer's weight + if hasattr(target, "weight"): + dtype = target.weight.dtype + else: + dtype = None # Will default to float32 + v = nn.Parameter(torch.empty(tinylora_config.u, dtype=dtype)) + if tinylora_config.init_weights is True: + # Default: initialize to zeros for identity/no-op operation + nn.init.zeros_(v) + elif tinylora_config.init_weights == "uniform": + nn.init.uniform_(v, -tinylora_config.init_v_bound, tinylora_config.init_v_bound) + # If init_weights is False, leave v uninitialized + self.tinylora_v[adapter_name][v_key] = v + + if isinstance(target, TinyLoraLayer): + target.update_layer( + adapter_name, + self.tinylora_v, + v_key, + tinylora_config.r, + tinylora_config, + ) + else: + new_module = self._create_new_module( + tinylora_config, self.tinylora_v, v_key, adapter_name, target, layer_idx=layer_idx + ) + + 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) + + # Ensure the shared v parameters remain trainable for the active adapter, + # but only if the adapter is not in inference mode + if adapter_name in self.active_adapter: + inference_mode = getattr(tinylora_config, "inference_mode", False) + if not inference_mode: + for param in self.tinylora_v[adapter_name].values(): + param.requires_grad = True + + @staticmethod + def _create_new_module( + tinylora_config: TinyLoraConfig, + tinylora_v: nn.ModuleDict, + v_key: str, + adapter_name: str, + target: nn.Module, + **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): + if tinylora_config.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." + ) + tinylora_config.fan_in_fan_out = False + new_module = Linear( + target, + tinylora_v, + v_key, + adapter_name, + tinylora_config, + **kwargs, + ) + elif isinstance(target_base_layer, Conv1D): + kwargs["is_target_conv_1d_layer"] = True + if not tinylora_config.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." + ) + tinylora_config.fan_in_fan_out = True + new_module = Linear( + target, + tinylora_v, + v_key, + adapter_name, + tinylora_config, + **kwargs, + ) + elif isinstance(target_base_layer, torch.nn.Embedding): + new_module = Embedding( + target, + tinylora_v, + v_key, + adapter_name, + tinylora_config, + **kwargs, + ) + else: + raise TypeError( + f"Target module {target} is not supported. Currently, only the following modules are supported: " + "`torch.nn.Linear`, `torch.nn.Embedding`, `transformers.pytorch_utils.Conv1D`." + ) + + return new_module + + def _cast_adapter_dtype(self, adapter_name: str, autocast_adapter_dtype: bool = True) -> None: + """ + Cast the adapter weights to the correct dtype. + + Override to also handle the model-level tinylora_v parameters. + """ + # Call parent implementation for layer-level parameters + super()._cast_adapter_dtype(adapter_name, autocast_adapter_dtype) + + if not autocast_adapter_dtype: + return + + # Handle model-level tinylora_v parameters + dtypes_to_convert_to_fp32 = {torch.float16, torch.bfloat16} + if adapter_name in self.tinylora_v: + for param in self.tinylora_v[adapter_name].values(): + if param.dtype in dtypes_to_convert_to_fp32: + param.data = param.data.to(torch.float32) + + def delete_adapter(self, adapter_name: str) -> None: + """Delete an adapter and clean up the model-level shared v parameters.""" + super().delete_adapter(adapter_name) + + # Remove the adapter's shared v parameters from the model-level ModuleDict + if adapter_name in self.tinylora_v: + del self.tinylora_v[adapter_name] + + def _mark_only_adapters_as_trainable(self, model: nn.Module) -> None: + """ + Mark only the adapter layers as trainable. + + Override the base class method to manage the shared tinylora_v parameters which are stored at the model level + and thus invisible to the base class's per-layer logic. + """ + # First, call the parent implementation + super()._mark_only_adapters_as_trainable(model) + + # Freeze all tinylora_v parameters first, then selectively unfreeze for active non-inference adapters + for adapter_params in self.tinylora_v.values(): + for param in adapter_params.values(): + param.requires_grad = False + + for active_adapter in self.active_adapters: + if active_adapter in self.peft_config: + inference_mode = getattr(self.peft_config[active_adapter], "inference_mode", False) + if inference_mode: + continue + if active_adapter in self.tinylora_v: + for param in self.tinylora_v[active_adapter].values(): + param.requires_grad = True diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/trainable_tokens/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/trainable_tokens/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4aa7bf8e5fc4705cb7b190cee0de53ac8db89573 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/trainable_tokens/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/trainable_tokens/config.py new file mode 100644 index 0000000000000000000000000000000000000000..7412d7f06474c510679e0f3004ae10c20910b00f --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/trainable_tokens/layer.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/trainable_tokens/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..d31432b2aaa6e48ada2b0b5f94dad4e68ea1a2fb --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/trainable_tokens/layer.py @@ -0,0 +1,274 @@ +# 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.functional as F +from torch import nn + +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 + +from .config import TrainableTokensConfig + + +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, + config: TrainableTokensConfig | dict | None = None, + 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, + config: TrainableTokensConfig | None = None, + tied_adapter: nn.Module | None = None, + **kwargs, + ): + # config can be None when update_layer is called through _set_trainable, in which case the relevant + # arguments should be in kwargs + if tied_adapter is not None: + # as a tied adapter, we're just following whatever the adpater we're tied to does, we don't update anything. + return + + token_indices = config.token_indices if (config is not None) else kwargs["token_indices"] + init_weights = config.init_weights if (config is not None) else kwargs.get("init_weights", True) + + self.token_indices[adapter_name] = token_indices + + # 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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/trainable_tokens/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/trainable_tokens/model.py new file mode 100644 index 0000000000000000000000000000000000000000..2fcff41f19b1feaf4ec7f12724f89b13acd40ad8 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/trainable_tokens/model.py @@ -0,0 +1,135 @@ +# 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 torch import 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) + peft_config = self.peft_config[adapter_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 + tied_adapter = self.model.get_input_embeddings() + new_module = self._create_new_module( + peft_config, adapter_name, target.base_layer, tied_adapter=tied_adapter + ) + self._replace_module(parent, target_name, new_module, target.base_layer) + else: + # Module hasn't been wrapped yet, create and replace normally + tied_adapter = self.model.get_input_embeddings() + self._create_and_replace( + peft_config, + adapter_name, + target, + target_name, + parent, + matched_keys[0], + tied_adapter=tied_adapter, + ) + + 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( + self, + peft_config: PeftConfig, + adapter_name: str, + target: nn.Module, + target_name: str, + parent: nn.Module, + current_key: str, + tied_adapter: nn.Module | None = None, + ) -> None: + if isinstance(target, TrainableTokensLayer): + target.update_layer(adapter_name, config=peft_config, tied_adapter=tied_adapter) + else: + new_module = self._create_new_module(peft_config, adapter_name, target, tied_adapter=tied_adapter) + self._replace_module(parent, target_name, new_module, target) + + @staticmethod + def _create_new_module(peft_config, adapter_name, target, tied_adapter: nn.Module | None): + new_module = TrainableTokensLayer( + target, + adapter_name, + config=peft_config, + tied_adapter=tied_adapter, + ) + new_module.update_layer( + adapter_name, + config=peft_config, + tied_adapter=tied_adapter, + ) + + return new_module diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/tuners_utils.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/tuners_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..85345b67814ba246b6006aba1ae70d2ad52d7778 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/tuners_utils.py @@ -0,0 +1,2249 @@ +# 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 copy +import dataclasses +import os +import re +import textwrap +import warnings +from abc import ABC, abstractmethod +from collections.abc import Sequence +from contextlib import contextmanager, nullcontext +from typing import Any, Optional, Union, overload + +import torch +from accelerate.hooks import AlignDevicesHook +from accelerate.utils import named_module_tensors, offload_state_dict +from packaging import version +from torch import nn +from tqdm import tqdm +from transformers import PreTrainedModel +from transformers.pytorch_utils import Conv1D + +from peft.import_utils import is_transformers_ge_v5 +from peft.mapping import PEFT_TYPE_TO_PREFIX_MAPPING +from peft.utils import INCLUDE_LINEAR_LAYERS_SHORTHAND, UPCAST_DTYPES +from peft.utils.constants import ( + DUMMY_MODEL_CONFIG, + DUMMY_TARGET_MODULES, + EMBEDDING_LAYER_NAMES, + MIN_TARGET_MODULES_FOR_OPTIMIZATION, + SEQ_CLS_HEAD_NAMES, +) +from peft.utils.integrations import init_empty_weights +from peft.utils.other import ( + AuxiliaryTrainingWrapper, + _get_module_names_tied_with_embedding, + _set_adapter, + _set_layer_requires_grad, + is_gptqmodel_quant_linear, + match_target_against_key, + set_additional_trainable_modules, +) +from peft.utils.peft_types import PeftType, TaskType +from peft.utils.quantization_utils import QuantizationBackend +from peft.utils.warning import PeftWarning + +from ..config import PeftConfig +from ..utils import _get_submodules +from ._buffer_dict import BufferDict + + +warn_msg_weight_tying = ( + "Model has `tie_word_embeddings=True` and a tied layer is part of the adapter, " + "but no implementation exists to tie the adapters. " + "This can lead to complications, for example when merging the adapter " + "or converting your model to formats other than safetensors. " + "Check the discussion here: https://github.com/huggingface/peft/issues/2777" +) +_torch_supports_dtensor = version.parse(torch.__version__) >= version.parse("2.5.0") +_torch_supports_distributed = _torch_supports_dtensor and torch.distributed.is_available() + + +@contextmanager +def onload_layer(layer): + r""" + A utility for modifying a module containing one or more tuners and a base layer, any of which are offloaded to the + CPU or disk. Moves a module's sub-modules to the execution device before some action is performed, after that the + base layer state dictionary is re-assigned (if that layer was offloaded to the disk) and finally the parameters are + offloaded. + + If the module has no offloaded sub-modules, this function does nothing. + + Args: + layer ('torch.nn.Module'): + layer with tuners to be merged + """ + + offloaded_modules = [] + for name, module in layer.named_modules(): + if name in ["", "base_layer"]: + continue + if hasattr(module, "_hf_hook") and isinstance(module._hf_hook, AlignDevicesHook) and module._hf_hook.offload: + module._hf_hook.pre_forward(module) + offloaded_modules.append(module) + + base_layer_offload = False + if hasattr(layer, "base_layer") and ( + hasattr(layer.base_layer, "_hf_hook") + and isinstance(layer.base_layer._hf_hook, AlignDevicesHook) + and layer.base_layer._hf_hook.offload + ): + # check if the base layer is disk-offloaded (must contain a 'dataset' and an offload index) + if torch.device("meta") in layer.base_layer._hf_hook.original_devices.values() and hasattr( + layer.base_layer._hf_hook.weights_map, "dataset" + ): + # find the disk-offload index (maps modules to safetensors) from the `dataset` (OffloadedWeightsLoader object) + index = layer.base_layer._hf_hook.weights_map.dataset.index + module_name = next(iter(dict(layer.base_layer._hf_hook.weights_map.dataset).keys())) # any module will do + file_name = index[module_name]["safetensors_file"] + base_name_arr = [] + # get effective dir name + for i in os.path.split(file_name): + if "--" in i: + base_name_arr.append(i) + break + base_name_arr.append(i) + base_name = os.path.join(*base_name_arr) + safetensors_filename = base_name + "-merged" + layer.base_layer._hf_hook.pre_forward(layer.base_layer) + base_layer_offload = True + + yield + + for module in offloaded_modules: + module._hf_hook.post_forward(module, torch.tensor([])) + + if base_layer_offload: + # re-make weights map (must be on cpu to send params to the disk via memmap if disk offload) + layer.base_layer._hf_hook.weights_map = { + name: param.to("cpu") for name, param in named_module_tensors(layer.base_layer) + } + # offload weights map to disk if original device is the disk + if torch.device("meta") in layer.base_layer._hf_hook.original_devices.values() and hasattr( + layer.base_layer._hf_hook.weights_map, "dataset" + ): + # rewrite directory with merged weights + offload_state_dict(safetensors_filename, layer.base_layer._hf_hook.weights_map) + layer.base_layer._hf_hook.post_forward(layer.base_layer, torch.tensor([])) + + +def _check_lora_target_modules_mamba(peft_config: PeftConfig, model: nn.Module, target_name: str): + """ + Prevent applying LoRA to incompatible modules in specific architectures (e.g., Mamba). + """ + + lora_like_types = {"LORA", "ADALORA", "XLORA", "RANDLORA"} + incompatible_modules = {"out_proj", "conv1d"} + mamba_model_types = {"falcon_h1", "mamba", "mamba2", "falcon_mamba"} + + if ( + peft_config.peft_type in lora_like_types + and hasattr(model, "config") + and getattr(model.config, "model_type", None) in mamba_model_types + ): + if target_name in incompatible_modules: + raise ValueError( + f"[PEFT:{peft_config.peft_type}] Module '{target_name}' is incompatible with Mamba-based models " + f"(model_type='{model.config.model_type}'). Incompatible modules: {incompatible_modules}. " + "Please remove it from `target_modules` to avoid compatibility issues." + ) + + +def _get_in_out_features(module: nn.Module) -> tuple[int, int] | tuple[None, None]: + """ + Get the in_features and out_features of the layer. + + Returns in_features and out_features as a tuple. If they cannot be determined, return a tuple of None and None. + This function covers a broad range of layers, some of which the caller might not support. Therefore, just because + this function returns a valid result does not imply that the layer type is supported. + """ + if isinstance(module, nn.Linear): + if _torch_supports_distributed and isinstance(module.weight, torch.distributed.tensor.DTensor): + # If Tensor Parallel is used, the weight is sharded, so we need to get the local shape + out_features, in_features = module.weight.to_local().shape + else: + in_features, out_features = module.in_features, module.out_features + elif isinstance(module, (nn.Conv1d, nn.Conv2d, nn.Conv3d)): + in_features, out_features = module.in_channels, module.out_channels + elif isinstance(module, nn.Embedding): + in_features, out_features = module.num_embeddings, module.embedding_dim + elif isinstance(module, Conv1D): + in_features, out_features = ( + module.weight.ds_shape if hasattr(module.weight, "ds_shape") else module.weight.shape + ) + elif isinstance(module, nn.MultiheadAttention): + if not module._qkv_same_embed_dim: + raise ValueError("Only same dim for query/key/value is supported as of now for MultiheadAttention.") + in_features, out_features = module.embed_dim, 3 * module.embed_dim + elif hasattr(module, "infeatures") and hasattr(module, "outfeatures"): + # QuantLinear + in_features, out_features = module.infeatures, module.outfeatures + elif hasattr(module, "input_size") and hasattr(module, "output_size"): + # Megatron ColumnParallelLinear,RowParallelLinear + in_features, out_features = module.input_size, module.output_size + elif module.__class__.__name__ == "Linear" or module.__class__.__name__ == "LayerNormLinear": + # TransformerEngine + in_features, out_features = module.in_features, module.out_features + elif module.__class__.__name__ == "LayerNormMLP": + # TransformerEngine + ln_weight = module.layer_norm_weight + ln_size = ln_weight.shape[0] + in_features, out_features = ln_size, ln_size + elif hasattr(module, "codebooks") and module.__class__.__name__ == "QuantizedLinear": + # AQLM QuantLinear + in_features, out_features = module.in_features, module.out_features + elif is_gptqmodel_quant_linear(module): + # GPT-QModel quantized linears + in_features, out_features = module.in_features, module.out_features + elif module.__class__.__name__ == "EetqLinear": + if hasattr(module, "in_features"): + # Eetq layers + in_features, out_features = module.in_features, module.out_features + else: + # Transformers Eetq layers + # https://github.com/huggingface/transformers/blob/c220ea9ecee9231927a47d97a63d5604a09d4c63/src/transformers/integrations/eetq.py#L74 + in_features, out_features = module.weight.shape + elif hasattr(module, "W_q") and module.__class__.__name__ == "HQQLinear": + # HQQ layers + in_features, out_features = module.in_features, module.out_features + elif module.__class__.__name__ == "PatchedLinear": + # INC layers + in_features, out_features = module.in_features, module.out_features + else: + # possibly support user provided custom layer types using dynamic dispatch + if hasattr(module, "in_features") and hasattr(module, "out_features"): + in_features, out_features = module.in_features, module.out_features + else: + in_features, out_features = None, None + warnings.warn(f"Unsupported layer type '{type(module)}' encountered, proceed at your own risk.", UserWarning) + return in_features, out_features + + +class BaseTuner(nn.Module, ABC): + r""" + A base tuner model that provides the common methods and attributes for all tuners that are injectable into a + torch.nn.Module + + For adding a new Tuner class, one needs to overwrite the following methods: + + - **_prepare_adapter_config**: + A private method to eventually prepare the adapter config, for example in case the field `target_modules` is + missing. + - **_create_and_replace**: + A private method to create and replace the target module with the adapter module. + - **_check_target_module_exists**: + A private helper method to check if the passed module's key name matches any of the target modules in the + adapter_config. + + The easiest is to check what is done in the `peft.tuners.lora.LoraModel` class. + + Attributes: + model (`torch.nn.Module`): + The model to which the adapter tuner layers will be attached. + forward (`Callable`): + The forward method of the model. + peft_config (`Union[`PeftConfig`, dict[str, PeftConfig]]`): + The adapter configuration object, it should be a dictionary of `str` to `PeftConfig` objects. One can also + pass a PeftConfig object and a new adapter will be created with the default name `adapter` or create a new + dictionary with a key `adapter_name` and a value of that peft config. + config (`dict[str, Any]`): + The model configuration object, it should be a dictionary of `str` to `Any` objects. + targeted_module_names (`list[str]`): + The list of module names that were actually adapted. Can be useful to inspect if you want to quickly + double-check that the `config.target_modules` were specified correctly. + targeted_parameter_names (`list[str]`): + The list of parameter names that were actually adapted. Can be useful to inspect if you want to quickly + double-check that the `config.target_parameters` were specified correctly. + prefix (`str`) + The PEFT-method specific unique prefix. E.g. `"lora_"` for LoRA. + """ + + # Required attributes for child classes: + + # The unique prefix for this PEFT method, e.g. 'lora_' for LoRA. + prefix: str + # The class of the tuner layer, e.g. `LoraLayer` for LoRA. + tuner_layer_cls: type[BaseTunerLayer] + # The default target modules for various transformers model architectures, like Llama. This is useful to allow users + # to skip specifying the `target_modules` in the config of the PEFT method. The default is often something like + # `{'llama': ['q_proj', 'v_proj'], ...}`. + target_module_mapping: dict[str, list[str]] + + def __init__( + self, + model, + peft_config: Union[PeftConfig, dict[str, PeftConfig]], + adapter_name: str, + low_cpu_mem_usage: bool = False, + state_dict: Optional[dict[str, torch.Tensor]] = None, + ) -> None: + super().__init__() + + self.model = model + self.targeted_module_names: list[str] = [] + self.targeted_parameter_names: list[str] = [] + + # For advanced developers, if you want to attach multiple adapters to your + # model, just add a `peft_config` dict attribute to your model. + if not hasattr(self, "peft_config"): + self.peft_config = {adapter_name: peft_config} if isinstance(peft_config, PeftConfig) else peft_config + else: + warnings.warn( + "Already found a `peft_config` attribute in the model. This will lead to having multiple adapters" + " in the model. Make sure to know what you are doing!" + ) + if isinstance(peft_config, PeftConfig): + self.peft_config[adapter_name] = peft_config + else: + # user is adding a dict of PeftConfigs + self.peft_config.update(peft_config) + + self.active_adapter: str | list[str] = adapter_name + self._pre_injection_hook(self.model, self.peft_config[adapter_name], adapter_name) + if peft_config != PeftType.XLORA or peft_config[adapter_name] != PeftType.XLORA: + self.inject_adapter(self.model, adapter_name, low_cpu_mem_usage=low_cpu_mem_usage, state_dict=state_dict) + + self._post_injection_hook(self.model, self.peft_config[adapter_name], adapter_name) + + # Copy the peft_config in the injected model. + self.model.peft_config = self.peft_config + + @property + def active_adapters(self) -> list[str]: + if isinstance(self.active_adapter, str): + return [self.active_adapter] + # is already a list of str + return self.active_adapter + + def forward(self, *args: Any, **kwargs: Any): + return self.model.forward(*args, **kwargs) + + def _pre_injection_hook(self, model: nn.Module, config: PeftConfig, adapter_name: str) -> None: + r""" + A hook to be called before the adapter is injected into the model. This method can be overridden by child + classes to perform any pre-injection operations. + + Args: + model (`nn.Module`): + The model to be adapted. + config (`PeftConfig`): + The adapter config. + adapter_name (`str`): + The adapter name. + """ + + def _post_injection_hook(self, model: nn.Module, config: PeftConfig, adapter_name: str) -> None: + r""" + A hook to be called after the adapter is injected into the model. This method can be overridden by child + classes to perform any post-injection operations. + + Args: + model (`nn.Module`): + The model to be adapted. + config (`PeftConfig`): + The adapter config. + adapter_name (`str`): + The adapter name. + """ + + def _prepare_adapter_config(self, peft_config: PeftConfig, model_config: dict) -> PeftConfig: + r""" + A private method to prepare the adapter config. + + For transformers based models, if `peft_config.target_modules` is None, for some model architectures, we can + automatically infer the target modules from the `TRANSFORMERS_MODELS_TO_XXX_TARGET_MODULES_MAPPING`. + + Args: + peft_config (`PeftConfig`): + The adapter config. + model_config (`dict`): + The transformers model config, that config should contain the `model_type` key. + + Returns: + peft_config (`PeftConfig`): + The PEFT config with updated `target_modules`. + + Raises: + ValueError: + Raises an error if the model type was not recognized. + """ + if peft_config.target_modules is None: + target_modules = self.target_module_mapping.get(model_config["model_type"]) + if target_modules is None: + raise ValueError("Please specify `target_modules` in `peft_config`") + if isinstance(target_modules, str): + peft_config.target_modules = target_modules + else: + peft_config.target_modules = set(target_modules) + return peft_config + + def _prepare_model(self, peft_config: PeftConfig, model: nn.Module): + r""" + A private method to modify the model structure before adapter is applied. + + See `peft.tuner.lora.LoraModel._prepare_model` for an example. + + Args: + peft_config (`PeftConfig`): + The prepared adapter config. + model (`nn.Module`): + The model that is going to be adapted. + """ + + @staticmethod + def _check_tied_module_exists(peft_config: PeftConfig, key: str) -> bool | re.Match[str] | None: + """ + A helper method to check if the passed module's key name matches any of the tied modules + + Args: + config (`PeftConfig`): + A config to match target modules from. + key (`str`): + A key to search any matches in config. + + Returns: + `bool` + True if key matches any tied modules from config, False if no match found. + """ + target_modules_to_tie = getattr(peft_config, "target_modules_to_tie", []) or [] + return key in target_modules_to_tie or any( + key.endswith(f".{target_key}") for target_key in target_modules_to_tie + ) + + @staticmethod + def _check_target_module_exists(peft_config: PeftConfig, key: str) -> bool | re.Match[str] | None: + """ + A helper method to check if the passed module's key name matches any of the target modules in the + adapter_config. + + Args: + config (`PeftConfig`): + A config to match target modules from. + key (`str`): + A key to search any matches in config. + + Returns: + `bool` | `re.Match[str]` | `None`: + True or re.Match object if key matches any target modules from config, False or None if no match found. + """ + return check_target_module_exists(peft_config, key) + + @abstractmethod + def _create_and_replace( + self, + peft_config: PeftConfig, + adapter_name: str, + target: nn.Module, + target_name: str, + parent: nn.Module, + current_key: str, + parameter_name: Optional[str] = None, + ) -> None: + r""" + Inplace replacement of the target module with the adapter layer. This method needs to be overridden by all the + tuner classes. + + Check `peft.tuners.lora.LoraModel._create_and_replace` for an example. + + Args: + peft_config (`PeftConfig`): + The adapter config. + adapter_name (`str`): + The adapter name. + target (`nn.Module`): + The target module. + target_name (`str`): + The target module's name. + parent (`nn.Module`): + The parent module. + current_key (`str`): + The key of the current target being adapted. + parameter_name (`str`, *optional*) + If, and only if, an `nn.Parameter` is being targeted, this is the name of the parameter. + """ + ... + + def _mark_only_adapters_as_trainable(self, model: nn.Module) -> None: + """ + A helper method to mark only the adapter layers as trainable (i.e. module.requires_grad = False). + """ + for n, p in model.named_parameters(): + if self.prefix not in n: + p.requires_grad = False + + for active_adapter in self.active_adapters: + bias = getattr(self.peft_config[active_adapter], "bias", "none") + if bias == "none": + continue + + if bias == "all": + for n, p in model.named_parameters(): + if "bias" in n: + p.requires_grad = True + elif bias.endswith("_only"): # e.g. "lora_only" or "boft_only" + for m in model.modules(): + if isinstance(m, self.tuner_layer_cls) and hasattr(m, "bias") and m.bias is not None: + m.bias.requires_grad = True + else: + raise NotImplementedError(f"Requested bias: {bias}, is not implemented.") + + def _enable_adapter_layers(self, enabled: bool = True) -> None: + for module in self.model.modules(): + if isinstance(module, (BaseTunerLayer, AuxiliaryTrainingWrapper)): + module.enable_adapters(enabled) + + def disable_adapter_layers(self) -> None: + """ + Disable all adapters in-place. + + When disabling all adapters, the model output corresponds to the output of the base model. + """ + # TODO: deprecate in favor of enable_adapters + for active_adapter in self.active_adapters: + bias_val = getattr(self.peft_config[active_adapter], "bias", "none") + if bias_val != "none": + msg = ( + f"Careful, disabling adapter layers with bias configured to be '{bias_val}' does not produce the " + "same output as the base model would without adaption." + ) + warnings.warn(msg) + self._enable_adapter_layers(enabled=False) + + def enable_adapter_layers(self) -> None: + """ + Enable all adapters in-place + """ + # TODO: deprecate in favor of enable_adapters + self._enable_adapter_layers(enabled=True) + + def delete_adapter(self, adapter_name: str) -> None: + """ + Deletes an existing adapter. + + Args: + adapter_name (str): Name of the adapter to be deleted. + """ + if adapter_name not in list(self.peft_config.keys()): + raise ValueError(f"Adapter {adapter_name} does not exist") + del self.peft_config[adapter_name] + + new_adapter = delete_adapter( + model=self.model, adapter_name=adapter_name, prefix=self.prefix, layer_cls=self.tuner_layer_cls + ) + self.active_adapter = new_adapter or [] + + def set_requires_grad(self, adapter_names: str | Sequence[str], requires_grad: bool = True) -> None: + """ + Enable or disable gradients on the given adapter(s). + + Args: + adapter_name (`str` or `Sequence[str]`): + The name of the adapter(s) whose gradients should be enabled/disabled. + requires_grad (`bool`, *optional*) + Whether to enable (`True`, default) or disable (`False`). + """ + set_requires_grad(self.model, adapter_names=adapter_names, requires_grad=requires_grad) + + def _check_new_adapter_config(self, config: PeftConfig) -> None: + """ + A helper method to check the config of a new adapter being added. + + Raise a ValueError if there is something wrong with the config or if it conflicts with existing adapters. + + """ + if len(self.peft_config) <= 1: + return + + # It is assumed that the config was added to self.peft_config *before* calling this check. We should thus never + # encounter the error below. Still, it is better to verify this, or else subsequent checks could be incorrect. + if not any(conf is config for conf in self.peft_config.values()): + raise ValueError( + "_check_new_peft_config was called incorrectly, this should not happen. Please open an issue and " + "report the error: https://github.com/huggingface/peft/issues" + ) + + bias_values = [getattr(conf, "bias", "none") for conf in self.peft_config.values()] + if sum(bias_value != "none" for bias_value in bias_values) > 1: + raise ValueError( + f"{self.__class__.__name__} supports only 1 adapter with bias. When using multiple adapters, " + "set bias to 'none' for all adapters." + ) + + def _cast_adapter_dtype(self, adapter_name: str, autocast_adapter_dtype: bool = True) -> None: + """ + A helper method to cast the adapter weights to the correct dtype. + + Currently, this only upcasts float16 and bfloat16 to float32. + + Args: + adapter_name (`str`): + The adapter name. + autocast_adapter_dtype (`bool`, *optional*): + Whether to autocast the adapter dtype. Defaults to `True`. + + """ + cast_adapter_dtype(self.model, adapter_name=adapter_name, autocast_adapter_dtype=autocast_adapter_dtype) + + def _check_merge_allowed(self): + """Helper method to check whether the adapter can be merged. + + Raise a ValueError if it is not possible to merge the adapter with the given configuration. + """ + example_code = textwrap.dedent( + """ + ```python + from transformers import AutoModelForCausalLM + + # Load original tied model + model = AutoModelForCausalLM.from_pretrained("google/gemma-2-2b-it", tie_word_embeddings=False) + + # Set the randomly initialized lm_head to the previously tied embeddings + model.lm_head.weight.data = model.model.embed_tokens.weight.data.clone() + + # Save the untied model + untied_model_dir = "dir/for/untied/model" + model.save_pretrained(untied_model_dir) + model.config.save_pretrained(untied_model_dir) + + # Now use the original model but in untied format + model = AutoModelForCausalLM.from_pretrained(untied_model_dir) + ``` + """ + ) + tied_target_modules = self._get_tied_target_modules(self.model) + if tied_target_modules: + warnings.warn( + f"Model with `tie_word_embeddings=True` and the {tied_target_modules=} are part of the adapter. " + "This can lead to complications. " + "You can opt to merge the adapter after cloning the weights (to untie the embeddings). " + "You can untie the embeddings by loading the model with `tie_word_embeddings=False`. For example:" + + example_code + ) + + def _unload_and_optionally_merge( + self, + merge: bool = True, + progressbar: bool = False, + safe_merge: bool = False, + adapter_names: Optional[list[str]] = None, + ) -> None: + if merge: + self._check_merge_allowed() + + key_list = [key for key, _ in self.model.named_modules() if self.prefix not in key] + desc = "Unloading " + ("and merging " if merge else "") + "model" + for key in tqdm(key_list, disable=not progressbar, desc=desc): + try: + parent, target, target_name = _get_submodules(self.model, key) + except AttributeError: + continue + with onload_layer(target): + if hasattr(target, "unload_and_optionally_merge_module"): + # if layers have special unloading method, like MultiheadAttention, use that + unloaded_module = target.unload_and_optionally_merge_module( + merge=merge, safe_merge=safe_merge, adapter_names=adapter_names + ) + self._replace_module(parent, target_name, unloaded_module, target) + elif hasattr(target, "base_layer"): + if merge: + target.merge(safe_merge=safe_merge, adapter_names=adapter_names) + self._replace_module(parent, target_name, target.get_base_layer(), target) + + # Clean up peft_config from the model since all PEFT modules have been removed. + # This prevents spurious warnings when re-wrapping the model with get_peft_model(). + if hasattr(self.model, "peft_config"): + del self.model.peft_config + + # If embeddings have diverged (e.g. after vocab resize), fix config to match actual state. + if merge: + model_config = self.get_model_config(self.model) + if model_config.get("tie_word_embeddings"): + try: + out_emb = self.model.get_output_embeddings() + in_emb = self.model.get_input_embeddings() + if (out_emb is not None) and (in_emb is not None): + out_w = getattr(out_emb, "weight", None) + in_w = getattr(in_emb, "weight", None) + if (out_w is not None) and (in_w is not None) and (out_w.data_ptr() != in_w.data_ptr()): + self.model.config.tie_word_embeddings = False + warnings.warn( + "Input and output embeddings are no longer tied after merging. " + "Setting `tie_word_embeddings=False` in the model config." + ) + except (NotImplementedError, AttributeError): + pass + + return self.model + + def merge_and_unload( + self, progressbar: bool = False, safe_merge: bool = False, adapter_names: Optional[list[str]] = None + ) -> torch.nn.Module: + r""" + This method merges the adapter layers into the base model. + + This is needed if someone wants to use the base model as a standalone model. The returned model has the same + architecture as the original base model. + + It is important to assign the returned model to a variable and use it, this is not an in-place operation! + + Args: + progressbar (`bool`): + whether to show a progressbar indicating the unload and merge process (default: False). + safe_merge (`bool`): + whether to activate the safe merging check to check if there is any potential Nan in the adapter + weights. + 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`. + + Example: + + ```py + >>> from transformers import AutoModelForCausalLM + >>> from peft import PeftModel + + >>> model_id = ... + >>> base_model = AutoModelForCausalLM.from_pretrained(model_id) + >>> peft_model_id = ... + >>> model = PeftModel.from_pretrained(base_model, peft_model_id) + >>> merged_model = model.merge_and_unload() + ``` + """ + return self._unload_and_optionally_merge( + progressbar=progressbar, safe_merge=safe_merge, adapter_names=adapter_names + ) + + def unload(self) -> torch.nn.Module: + """ + Return the base model by removing all the PEFT modules. + + It is important to assign the returned model to a variable and use it, this is not an in-place operation! + """ + return self._unload_and_optionally_merge(merge=False) + + def _check_target_module_compatiblity(self, peft_config: PeftConfig, model: nn.Module, target_name: str): + """ + Prevent applying LoRA to incompatible modules in specific architectures (e.g., Mamba). + """ + _check_lora_target_modules_mamba(peft_config, model, target_name) + + def _create_and_replace_parameter( + self, peft_config, adapter_name, target, target_name, parent, current_key + ) -> None: + raise NotImplementedError(f"{self.__class__.__name__} does not support targeting nn.Parameter.") + + def inject_adapter( + self, + model: nn.Module, + adapter_name: str, + autocast_adapter_dtype: bool = True, + low_cpu_mem_usage: bool = False, + state_dict: Optional[dict[str, torch.Tensor]] = None, + ) -> None: + r""" + Creates adapter layers and replaces the target modules with the adapter layers. This method is called under the + hood by `peft.mapping.get_peft_model` if a non-prompt tuning adapter class is passed. + + The corresponding PEFT config is directly retrieved from the `peft_config` attribute of the BaseTuner class. + + Args: + model (`nn.Module`): + The model to be tuned. + adapter_name (`str`): + The adapter name. + autocast_adapter_dtype (`bool`, *optional*): + Whether to autocast the adapter dtype. Defaults to `True`. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the loading process. + state_dict (`dict`, *optional*, defaults to `None`) + If a state_dict is passed here, the adapters will be injected based on the entries of the state_dict. + This can be useful when the exact `target_modules` of the PEFT method is unknown, for instance because + the checkpoint was created without meta data. Note that the values from the state_dict are not used, + only the keys are used to determine the correct layers that should be adapted. + + """ + ################################### + # PREPARATION OF MODEL AND CONFIG # + ################################### + is_transformers_like_model = hasattr(getattr(model, "config", None), "model_type") + if is_transformers_ge_v5 and is_transformers_like_model: + # TODO remove once transformers < v5.0 is no longer supported + # For Transformers v5, some architectures were changed compared to v4, e.g. the MoE layers of Mixtral. To + # still make it possible to load adapters trained with v4, we have to update the PEFT config so that the + # right layers are targeted. Call this first and overwrite the peft_config to be sure that changes are + # applied. + from peft.utils.transformers_weight_conversion import ( + convert_peft_config_for_transformers, + get_model_conversion_mapping, + ) + + weight_conversions = get_model_conversion_mapping(model) + convert_peft_config_for_transformers( + self.peft_config[adapter_name], + model=model, + conversions=weight_conversions, + ) + + peft_config = self.peft_config[adapter_name] + excluded_modules = [] + unmatched_modules = [] + targeted_modules_from_peft_config: list[str] = [] # only relevant if state_dict is passed + targets_to_tie: list[str] = [] + # Note: If possible, all checks should be performed *at the start of this method*. + # This way, we can raise early if something goes wrong, without leaving the model + # in a bad (half-initialized) state. + self._check_new_adapter_config(peft_config) + + self._check_tied_modules(model, peft_config) + + model_config = self.get_model_config(model) + + peft_config = self._prepare_adapter_config(peft_config, model_config) + + self._prepare_model(peft_config, model) + + if getattr(peft_config, "target_parameters", []) and state_dict: + raise ValueError( + "Trying to inject a PEFT adapter from a state_dict but the PEFT config uses `target_parameters`. This " + "is not supported -- when using `target_parameters`, please inject the adapter without the state_dict." + ) + + named_modules = list(model.named_modules()) + key_list = [key for key, _ in named_modules] + + uses_dummy_target_modules = getattr(peft_config, "target_modules", None) == DUMMY_TARGET_MODULES + if uses_dummy_target_modules: + # dummy adapter, we allow not matching any module + named_modules = [] + key_list = [] + + # update peft_config.target_modules if required + peft_config = _maybe_include_all_linear_layers(peft_config, model) + + # This is an optimization to reduce the number of entries in the target_modules list. The reason is that in some + # circumstances, target_modules can contain hundreds of entries. Since each target module is checked against + # each module of the net (which can be thousands), this can become quite expensive when many adapters are being + # added. Often, the target_modules can be condensed in such a case, which speeds up the process. + # A context in which this can happen is when diffusers loads non-PEFT LoRAs. As there is no meta info on + # target_modules in that case, they are just inferred by listing all keys from the state_dict, which can be + # quite a lot. See: https://github.com/huggingface/diffusers/issues/9297 + # As there is a small chance for undiscovered bugs, we apply this optimization only if the list of + # target_modules is sufficiently big. + # We also exclude IA³ from this optimization. This is because IA³ has both target_modules and + # feedforward_modules, which are coupled (the latter must be a subset). It would be possible to change the logic + # to keep both in sync, but it's not quite trivial and probably not worth the effort. See #2429. + if ( + isinstance(peft_config.target_modules, (list, set)) + and (len(peft_config.target_modules) >= MIN_TARGET_MODULES_FOR_OPTIMIZATION) + and (peft_config.peft_type != PeftType.IA3) + ): + suffixes = tuple("." + suffix for suffix in peft_config.target_modules) + names_no_target = [ + name for name in key_list if (name not in peft_config.target_modules) and not name.endswith(suffixes) + ] + new_target_modules = _find_minimal_target_modules(peft_config.target_modules, names_no_target) + if len(new_target_modules) < len(peft_config.target_modules): + peft_config.target_modules = new_target_modules + + ############################### + # MATCHING & CREATING MODULES # + ############################### + + existing_adapter_prefixes = [] + for key, module in named_modules: + if isinstance(module, BaseTunerLayer): + existing_adapter_prefixes.append(key + ".") + + # TODO: check if this the most robust way + module_names: set[str] = set() + if state_dict is not None: + prefix = PEFT_TYPE_TO_PREFIX_MAPPING[peft_config.peft_type] + # Find the module name from the state_dict. Also defensively remove '_orig_mod.', which might be inserted if + # the model was torch.compiled beforehand + module_names = {k.rsplit("." + prefix, 1)[0].removeprefix("_orig_mod.") for k in state_dict} + + for key, module in named_modules: + if not key: + continue + + # It is possible that we're adding an additional adapter, so if we encounter a key that clearly belongs to a + # previous adapter we can skip here since we don't want to interfere with adapter internals. + for adapter_key in existing_adapter_prefixes: + if key.startswith(adapter_key): + excluded_modules.append(key) + break + + if excluded_modules and excluded_modules[-1] == key: + continue + + if state_dict is None: + # normal mechanism: match the modules using the peft_config + result = self._check_target_module_exists(peft_config, key) + # If the module is a tied layer, then we skip injecting + # any adapter here and tie it later to the adapter of the source layer. + # In this loop we only add adapters to the source layer (eg: embed_tokens) + # Only applicable if `ensure_weight_tying = True` for LoraConfig + if self._check_tied_module_exists(peft_config, key): + targets_to_tie.append(key) + continue + if isinstance(result, _ExcludedModule): + excluded_modules.append(key) + elif not result: + unmatched_modules.append(key) + else: + self.targeted_module_names.append(key) + parent, target, target_name = _get_submodules(model, key) + self._check_target_module_compatiblity(peft_config, model, target_name) + ctx = init_empty_weights if low_cpu_mem_usage else nullcontext + with ctx(): + self._create_and_replace( + peft_config, adapter_name, target, target_name, parent, current_key=key + ) + else: + # defensively remove _orig_mod prefix in case the model is compiled + key = key.removeprefix("_orig_mod.") + # use the state_dict to match modules instead + if key not in module_names: + unmatched_modules.append(key) + else: + # If the module is a tied layer, then we skip injecting + # any adapter here and tie it later to the adapter of the source layer. + # In this loop we only add adapters to the source layer (eg: embed_tokens) + # Only applicable if `ensure_weight_tying = True` for LoraConfig + if self._check_tied_module_exists(peft_config, key): + targets_to_tie.append(key) + continue + self.targeted_module_names.append(key) + parent, target, target_name = _get_submodules(model, key) + self._check_target_module_compatiblity(peft_config, model, target_name) + ctx = init_empty_weights if low_cpu_mem_usage else nullcontext + with ctx(): + self._create_and_replace( + peft_config, adapter_name, target, target_name, parent, current_key=key + ) + + # still record what would have been matched via the config so that the two results can be compared + if self._check_target_module_exists(peft_config, key): + targeted_modules_from_peft_config.append(key) + + if getattr(peft_config, "target_parameters", []): + # Note: We don't need to check for no state_dict being passed, since we already checked this earlier. + self._inject_parameters( + peft_config=peft_config, model=model, adapter_name=adapter_name, low_cpu_mem_usage=low_cpu_mem_usage + ) + + # Here we inject tied adapters for all the layers which were tied + # Only applicable if `ensure_weight_tying = True` for LoraConfig + for key in targets_to_tie: + self.targeted_module_names.append(key) + parent, target, target_name = _get_submodules(model, key) + self._check_target_module_compatiblity(peft_config, model, target_name) + ctx = init_empty_weights if low_cpu_mem_usage else nullcontext + with ctx(): + self._create_and_replace(peft_config, adapter_name, target, target_name, parent, current_key=key) + + #################### + # CHECK FOR ERRORS # + #################### + + if state_dict is not None: + # in case that the state_dict was used as source of truth and it resulted in different outcomes than what + # would have been matched with the PEFT config, warn the user about that. + targeted_set_from_peft_config = set(targeted_modules_from_peft_config) + targeted_set_from_state_dict = set(self.targeted_module_names) + diff_peft_config = targeted_set_from_peft_config - targeted_set_from_state_dict + diff_state_dict = targeted_set_from_state_dict - targeted_set_from_peft_config + warning_msg = "" + if diff_peft_config or diff_state_dict: + warning_msg = ( + "While injecting the PEFT adapters, an inconsistency was discovered between the PEFT config and " + "the provided state_dict. This is not necessarily an issue and can be ignored if this was the " + "intent. " + ) + if diff_peft_config: + warning_msg += ( + f"The PEFT config contained these additional target modules: {sorted(diff_peft_config)}. " + ) + if diff_state_dict: + warning_msg += f"The state_dict contained these additional target modules: {sorted(diff_state_dict)}. " + if warning_msg: + warnings.warn(warning_msg, RuntimeWarning) + + if not self.targeted_module_names and not self.targeted_parameter_names and not uses_dummy_target_modules: + if excluded_modules and not unmatched_modules: + # All targeted modules were excluded + raise ValueError( + "All modules were excluded. This is likely unintended. " + "Check your `target_modules`, `exclude_modules` and `modules_to_save` configuration." + ) + elif not excluded_modules and unmatched_modules and not peft_config.target_modules: + raise ValueError( + "No `target_modules` passed but also no `target_parameters` found. Please check the values for " + "these arguments." + ) + elif not excluded_modules and unmatched_modules: + # None of the targeted modules matched + error_msg = ( + f"Target modules {peft_config.target_modules} not found in the base model. " + f"Please check the target modules and try again." + ) + if getattr(peft_config, "layers_to_transform", None) is not None: + error_msg += f" Note: You specified 'layers_to_transform': {peft_config.layers_to_transform}." + if getattr(peft_config, "layers_pattern", None) is not None: + error_msg += f" You also specified 'layers_pattern': {peft_config.layers_pattern}." + raise ValueError(error_msg) + else: + # Some modules did not match and some matched but were excluded + error_msg = ( + "No modules were targeted for adaptation. " + "This might be caused by a combination of mismatched target modules and excluded modules. " + "Please check your `target_modules` and `exclude_modules` configuration. You may also have " + "only targeted modules that are marked to be saved (`modules_to_save`)." + ) + if getattr(peft_config, "layers_to_transform", None) is not None: + error_msg += f" Note: You specified 'layers_to_transform': {peft_config.layers_to_transform}." + if getattr(peft_config, "layers_pattern", None) is not None: + error_msg += f" You also specified 'layers_pattern': {peft_config.layers_pattern}." + raise ValueError(error_msg) + + elif hasattr(peft_config, "exclude_modules") and peft_config.exclude_modules and not excluded_modules: + # exclude_modules was passed but was not used + warnings.warn( + f"You have passed exclude_modules={peft_config.exclude_modules} but no modules were excluded. " + "Please check that exclude_modules was set correctly." + ) + + elif not uses_dummy_target_modules: + # If we landed here, it means that at least one module or parameter was adapted, so let's not raise an + # error. However, let's warn the user if it seems like + # - they wanted to match a module but there was no match + # - they wanted to match a parameter but there was no match + if peft_config.target_modules and not self.targeted_module_names: + warnings.warn( + f"target_modules={peft_config.target_modules} were set but no module was matched.", RuntimeWarning + ) + elif getattr(peft_config, "target_parameters", []) and not self.targeted_parameter_names: + warnings.warn( + f"target_parameters={peft_config.target_parameters} were set but no parameter was matched.", + RuntimeWarning, + ) + + ################ + # HOUSEKEEPING # + ################ + + # It's important to set the adapter here (again), because otherwise it can happen that if a 2nd adapter is + # added, and it targets different layer(s) than the first adapter (which is active), then those different + # layers will be activated, which we don't want. + self.set_adapter(self.active_adapters, inference_mode=peft_config.inference_mode) + self._mark_only_adapters_as_trainable(model) + + if self.peft_config[adapter_name].inference_mode: + for n, p in model.named_parameters(): + if adapter_name in n: + p.requires_grad = False + + set_additional_trainable_modules( + model=model, + peft_config=peft_config, + model_config=BaseTuner.get_model_config(self), + adapter_name=adapter_name, + activate_adapter=adapter_name in self.active_adapters, + ) + + def _inject_parameters( + self, peft_config: PeftConfig, model: nn.Module, adapter_name: str, low_cpu_mem_usage: bool + ) -> None: + """Inject layers based on peft_config.target_modules""" + + def strip_base_layer_from_name(module_name): + # It is possible that the layer is already a PEFT layer and needs updating with a new adapter. In this case, + # the name of parameter would be something like `model.layers.0.experts.base_layer.weight`, i.e. there is a + # "base_layer" inserted in the name. We need to remove that, otherwise we won't be able to match correctly + # (in this case, "experts.weight" would not match). + name = ".base_layer" + while name in module_name: + prefix, _, suffix = module_name.rpartition(name) + module_name = prefix + suffix + return module_name + + def create_and_replace_param(module_name, key, param_name): + # helper function to avoid duplication + parent, target, target_name = _get_submodules(model, module_name) + unwrapped_module_name = strip_base_layer_from_name(module_name) + unwrapped_module = model.get_submodule(unwrapped_module_name) + # use the class name for checking to avoid circular import + if isinstance(unwrapped_module, BaseTunerLayer) and unwrapped_module.__class__.__name__ != "ParamWrapper": + raise ValueError( + f"Trying to wrap an `nn.Parameter` of layer '{unwrapped_module_name}' of type " + f"{type(target).__name__}, which is not a valid target. Make sure that this layer is not " + "also targeted with `target_modules`. For some models, PEFT will do this automatically, " + "try setting `target_modules=[]` to prevent it." + ) + + self._check_target_module_compatiblity(peft_config, model, target_name) + ctx = init_empty_weights if low_cpu_mem_usage else nullcontext + with ctx(): + self._create_and_replace( + peft_config, + adapter_name, + target, + target_name, + parent, + current_key=key, + parameter_name=param_name.rpartition(".")[-1], + ) + + # TODO very simple matching, might not cover all use cases + unsorted_target_names = set(peft_config.target_parameters) + # As the order of matching can influence the nesting of multiple params on the same module, ensure determinism + # by sorting. + target_names = sorted(unsorted_target_names) + for module_name, module in model.named_modules(): + if hasattr(module, "parametrizations"): + # Deal with the case that the parameter is already parametrized. The issue is that we would not be able + # to match `f"{module_name}.{param_name}"`, as the parameter is now something like + # `module.parametrization.weight`. + for key in target_names: + target_module_name, _, param_name = key.rpartition(".") + if target_module_name != module_name: + continue + if getattr(module, param_name, None) is None: + continue + create_and_replace_param(module_name, key, param_name) + self.targeted_parameter_names.append(key) + else: + # Standard case: the parameter is not already parametrized. Note, however, that the model could already + # be nested with lora.ParamWrapper, as this is how we allow targeting multiple Parameters on the same + # module. + unwrapped_module_name = strip_base_layer_from_name(module_name) + # we're interested in finding the "lowest" module that contains the parameter, hence recurse=False + for param_name, param in module.named_parameters(recurse=False): + key = f"{unwrapped_module_name}.{param_name}" + if (key in target_names) or any(key.endswith(f".{target_key}") for target_key in target_names): + # Note: We use the unwrapped_module_name to check if the key matches, but we use the module_name for + # replacement, since we want to replace the wrapped module. + create_and_replace_param(module_name, key, param_name) + self.targeted_parameter_names.append(key) + + def _replace_module(self, parent, child_name, new_module, child) -> None: + """ + Replace the sub-module of a given moduel with a new PEFT module. + + This also deals with device placement of the new module to be in line with the child module. + + Args: + parent (`nn.Module`): + The parent module on which the replacement should take place. + child_name (`str`): + The name of the child module to be replaced. + new_module (`nn.Module`): + The new PEFT module. + child (`nn.Module`): + The original child module that is being replaced. + + """ + setattr(parent, child_name, new_module) + # It's not necessary to set requires_grad here, as that is handled by + # _mark_only_adapters_as_trainable + + # child layer wraps the original module, unpack it + if hasattr(child, "base_layer"): + child = child.base_layer + + if not hasattr(new_module, "base_layer"): + new_module.weight = child.weight + if hasattr(child, "bias"): + new_module.bias = child.bias + + if getattr(child, "state", None) is not None: + if hasattr(new_module, "base_layer"): + new_module.base_layer.state = child.state + else: + new_module.state = child.state + new_module.to(child.weight.device) + + meta = torch.device("meta") + # dispatch to correct device + for name, module in new_module.named_modules(): + if self.prefix in name: + if hasattr(child, "qweight"): + weight = child.qweight + elif hasattr(child, "W_q"): + weight = child.W_q + elif hasattr(child, "weight"): + weight = child.weight + elif getattr(child, "in_proj_weight", None) is not None: # MHA + weight = child.in_proj_weight + else: + weight = next(child.parameters()) + + if not any(p.device == meta for p in module.parameters()): + module.to(weight.device) + + def merge_adapter(self, adapter_names: Optional[list[str]] = None, safe_merge: bool = False) -> None: + """ + This method merges the adapter layers into the base model. + + Merging adapters can lead to a speed up of the forward pass. A copy of the adapter weights is still kept in + memory, which is required to unmerge the adapters. In order to merge the adapter weights without keeping them + in memory, please call `merge_and_unload`. + + Args: + 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`. + 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`. + """ + # Note: The order of arguments here is: + # adapter_names, safe_merge + # For layer.merge, the order is: + # safe_merge, adapter_names + # This is not so nice but this method here started with only adapter_names, thus putting safe_merge first would + # be a backwards incompatible change. + self._check_merge_allowed() + for module in self.model.modules(): + if isinstance(module, BaseTunerLayer): + with onload_layer(module): + module.merge(adapter_names=adapter_names, safe_merge=safe_merge) + + def unmerge_adapter(self): + """ + This method unmerges all merged adapter layers from the base model. + """ + for module in self.model.modules(): + if isinstance(module, BaseTunerLayer): + with onload_layer(module): + module.unmerge() + + def set_adapter(self, adapter_name: str | list[str], inference_mode: bool = False) -> None: + """Set the active adapter(s). + + Args: + adapter_name (str, list[str]): + The name(s) of the adapter(s) to set as active + inference_mode (bool, optional): + Whether the activated adapter should be frozen (i.e. `requires_grad=False`). Default is False. + """ + set_adapter( + self.model, adapter_name=adapter_name, inference_mode=inference_mode, layer_cls=self.tuner_layer_cls + ) + self.active_adapter = adapter_name + + @staticmethod + def get_model_config(model: nn.Module) -> dict: + """ + This method gets the config from a model in dictionary form. If model has not attribute config, then this + method returns a default config. + + Args: + model (`nn.Module`): + Model to get the config from. + default (`dict|None`, *optional*):: + What to return if model does not have a config attribute. + """ + model_config = getattr(model, "config", DUMMY_MODEL_CONFIG) + if hasattr(model_config, "to_dict"): + model_config = model_config.to_dict() + elif dataclasses.is_dataclass(model_config): + model_config = dataclasses.asdict(model_config) + return model_config + + def _get_tied_target_modules(self, model: nn.Module) -> list[str]: + tied_target_modules = [] + model_config = self.get_model_config(model) + if model_config.get("tie_word_embeddings"): + for target_module in self.targeted_module_names: + # This potentially yields false positives since we're just looking at the layer names. So if we use a + # model that uses weight-tying of lm_head and embed_tokens, a third, unrelated, layer which is + # unfortunately named so that it is in EMBEDDING_LAYER_NAMES will be falsely reported here as well. + if target_module.split(".")[-1] in EMBEDDING_LAYER_NAMES: + tied_target_modules.append(target_module) + return tied_target_modules + + def _get_module_names_tied_with_embedding(self) -> list[str]: + return _get_module_names_tied_with_embedding(self) + + def _add_modules_to_save_to_tie(self, peft_config, tied_weight_keys): + """ + This method adds modules to tie to `peft_config` so that those modules can be tied downstream. By default this + method raises a warning, and each tuner class extending `BaseTuner` can choose to implement this. + + Check `peft.tuners.lora.LoraModel._add_modules_to_save_to_tie` for an example. + """ + warnings.warn(warn_msg_weight_tying) + + def _add_targets_to_tie(self, peft_config, tied_weight_keys): + """ + This method adds targets to tie to `peft_config` so that those modules can be tied downstream. By default this + method raises a warning, and each tuner class extending `BaseTuner` can choose to implement this. + + Check `peft.tuners.lora.LoraModel._add_targets_to_tie` for an example. + """ + warnings.warn(warn_msg_weight_tying) + + def _check_tied_modules(self, model: nn.Module, peft_config): + """ + Checks if any of the tied layers are targetted via `modules_to_save` or `target_modules`. Updates the + `peft_config` in place with any layers/adapters that needs to be tied + """ + modules_to_save = set(getattr(peft_config, "modules_to_save", []) or []) + # `EMBEDDING_LAYER_NAMES` contains only the stripped name of the module + # eg: To get a match for model.embed_tokens, we need to extract `embed_tokens` + is_embedding_to_save = any(m.split(".")[-1] in EMBEDDING_LAYER_NAMES for m in modules_to_save) + + raw_target_modules = getattr(peft_config, "target_modules", None) + if isinstance(raw_target_modules, str): + is_embedding_in_target = any( + match_target_against_key(raw_target_modules, m) for m in EMBEDDING_LAYER_NAMES + ) + else: + target_modules = set(raw_target_modules or []) + # `EMBEDDING_LAYER_NAMES` contains only the stripped name of the module + # eg: To get a match for model.embed_tokens, we need to extract `embed_tokens` + is_embedding_in_target = any(m.split(".")[-1] in EMBEDDING_LAYER_NAMES for m in target_modules) + + tied_weight_keys = self._get_module_names_tied_with_embedding() + + if getattr(peft_config, "ensure_weight_tying", False): + if tied_weight_keys: + if is_embedding_to_save: + self._add_modules_to_save_to_tie(peft_config, tied_weight_keys) + elif is_embedding_in_target: + self._add_targets_to_tie(peft_config, tied_weight_keys) + else: + warnings.warn( + "You have requested `ensure_weight_tying`, but no tied modules are added in either " + "`modules_to_save` or `target_modules`" + ) + else: + warnings.warn("You have requested `ensure_weight_tying`, but no tied modules were found in the model") + + elif (is_embedding_to_save or is_embedding_in_target) and tied_weight_keys: + if hasattr(peft_config, "ensure_weight_tying"): + msg = ( + "Model has `tie_word_embeddings=True` and a tied layer is part of the adapter, " + "but `ensure_weight_tying` is not set to True. " + "This can lead to complications, for example when merging the adapter " + "or converting your model to formats other than safetensors. " + "Check the discussion here: https://github.com/huggingface/peft/issues/2777" + ) + warnings.warn(msg) + else: + msg = ( + "Model has `tie_word_embeddings=True` and a tied layer is part of the adapter, " + "but no implementation exists to tie the adapters. " + "This can lead to complications, for example when merging the adapter " + "or converting your model to formats other than safetensors. " + "Check the discussion here: https://github.com/huggingface/peft/issues/2777" + ) + warnings.warn(msg) + + def supports_lora_conversion(self, adapter_name: str = "default") -> bool: + """ + Whether it is possible for the adapter of this model to be converted to LoRA. + + Normally, this works if the PEFT method is additive, i.e. W' = W_base + delta_weight. + """ + return all( + module.supports_lora_conversion() for module in self.modules() if isinstance(module, BaseTunerLayer) + ) + + def __getattr__(self, name: str): + """Forward missing attributes to the wrapped module.""" + try: + return super().__getattr__(name) # defer to nn.Module's logic + except AttributeError: + if name == "model": # see #1892: prevent infinite recursion if class is not initialized + raise + return getattr(self.model, name) + + +class BaseTunerLayer(ABC): + r""" + A tuner layer mixin that provides the common methods and attributes for all tuners. + + Args: + is_pluggable (`bool`, *optional*): + Whether the adapter layer can be plugged to any pytorch module + active_adapters (Union[List[`str`], `str`], *optional*): + The name of the active adapter. + """ + + # All names of layers that may contain adapter (trainable) weights + adapter_layer_names: tuple[str, ...] = () + # All names of other parameters that may contain adapter-related parameters + other_param_names: tuple[str, ...] = () + + # indicates whether all adapters should be disabled + _disable_adapters: bool = False + + # the currently active adapter(s) + _active_adapter: str | list[str] = "default" + + # List all merged adapters + merged_adapters: list[str] = [] + + # the quantization backend used within this class, e.g. Bnb8bitBackend or None if no quantization + quantization_backend: QuantizationBackend | None = None + + def get_base_layer(self) -> nn.Module: + """ + (Recursively) get the base_layer. + + This is necessary for the case that the tuner layer wraps another tuner layer. + + """ + base_layer = self + while hasattr(base_layer, "base_layer"): + base_layer = base_layer.base_layer + return base_layer + + def get_base_weight(self) -> torch.Tensor: + """Return the weight of the base layer. + + This takes care of potentially dequantizing the weight if it is quantized. + """ + if self.quantization_backend is not None: + return self.quantization_backend.get_base_weight(self.get_base_layer()) + return self.get_base_layer().weight.data + + def set_base_weight(self, weight_data: torch.Tensor) -> None: + """Sets the base weight of the base layer to the new tensor + + This works also with quantized weights. + """ + if self.quantization_backend is not None: + self.quantization_backend.set_base_weight(self, weight_data) + else: + self.get_base_layer().weight.data = weight_data + + def _get_embed_scale(self): + """ + Extract embed_scale from base layer if present and valid. + + Some embedding layers (e.g., Gemma3TextScaledWordEmbedding) apply scaling to embeddings in their forward + method. This method checks for the presence of an `embed_scale` attribute. If it exists, it is assumed to be a + scalar. Its shape is validated accordingly. + + Returns: + torch.Tensor or None: The embed_scale tensor if found and valid, None otherwise. + """ + base_layer = self.get_base_layer() + if not hasattr(base_layer, "embed_scale"): + return None + + embed_scale = base_layer.embed_scale + + # Convert scalar values to tensors + if isinstance(embed_scale, (int, float)): + return torch.tensor(embed_scale, device=base_layer.weight.device, dtype=base_layer.weight.dtype) + + # Validate tensor shape - must be scalar (0-d) or 1-element tensor for proper broadcasting + if isinstance(embed_scale, torch.Tensor): + if embed_scale.numel() == 1: + return embed_scale + else: + # Log warning but don't fail - this maintains backward compatibility + warnings.warn( + f"Found embed_scale attribute with shape {embed_scale.shape}, expected scalar. " + "Embedding scaling will not be applied. If this is unexpected, please open an issue at " + "https://github.com/huggingface/peft/issues", + PeftWarning, + ) + return None + + return None + + @property + def weight(self) -> torch.Tensor: + # This is required for some transformers code, e.g. for T5, weight is accessed as: + # self.wo.weight + # where "wo" is the adapter layer. + # https://github.com/huggingface/transformers/blob/78f6ed6c70b29c1560780e3869a7ad4c6b3d2710/src/transformers + # /models/t5/modeling_t5.py#L292 + base_layer = self.get_base_layer() + if hasattr(base_layer, "qweight"): + # QuantLinear + weight = base_layer.qweight + else: + # Other layers + weight = base_layer.weight + return weight + + @property + def bias(self) -> torch.Tensor: + base_layer = self.get_base_layer() + return base_layer.bias + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + raise NotImplementedError + + def unmerge(self) -> None: + raise NotImplementedError + + @property + def merged(self) -> bool: + return bool(self.merged_adapters) + + @property + def disable_adapters(self) -> bool: + # use a property to ensure that disable_adapters is not set directly, instead use the enable_adapters method + return self._disable_adapters + + @property + def active_adapter(self) -> str | list[str]: + # use a property to ensure that active_adapter is not set directly, instead use the set_adapter method + return self._active_adapter + + def _get_available_adapters(self) -> set[str]: + """Return all adapter names that can be found on this module.""" + adapters = set() + for layer_name in self.adapter_layer_names: + module = getattr(self, layer_name) + if not isinstance(module, (nn.ModuleDict, nn.ParameterDict)): + continue + adapters.update(set(module.keys())) + return adapters + + @property + def active_adapters(self): + if isinstance(self.active_adapter, str): + return [self.active_adapter] + # is already a list of str + return self.active_adapter + + def enable_adapters(self, enabled: bool) -> None: + """Toggle the enabling and disabling of adapters + + Takes care of setting the requires_grad flag for the adapter weights. + + Args: + enabled (bool): True to enable adapters, False to disable adapters + """ + if enabled: + self.set_adapter(self.active_adapters) + self._disable_adapters = False + else: + # disable grads on all adapter layers + for layer_name in self.adapter_layer_names: + module_dict = getattr(self, layer_name) + for layer in module_dict.values(): + _set_layer_requires_grad(layer, False) + self._disable_adapters = True + + def set_adapter(self, adapter_names: str | list[str], inference_mode: bool = False) -> None: + """Set the active adapter(s). + + Additionally, this function will set the specified adapter to trainable (i.e., requires_grad=True) unless + inference_mode is True. + + Args: + adapter_name (`str` or `list[str]`): + The name(s) of the adapter(s) to set as active. + inference_mode (bool, optional): + Whether the activated adapter should be frozen (i.e. `requires_grad=False`). Default is False. + """ + if isinstance(adapter_names, str): + adapter_names = [adapter_names] + + # Deactivate grads on the inactive adapter and activate grads on the active adapter (if not in inference mode) + for layer_name in self.adapter_layer_names: + module_dict = getattr(self, layer_name) + for key, layer in module_dict.items(): + should_require_grad = (key in adapter_names) and (not inference_mode) + _set_layer_requires_grad(layer, should_require_grad) + + self._active_adapter = adapter_names + + def _all_available_adapter_names(self) -> list[str]: + """Return a sorted list of all available adapter names""" + adapter_names = set() + for name in self.adapter_layer_names + self.other_param_names: + # we check each possible attribute and if it's a dict or ModuleDict, we assume that the keys are the adapter + # names + attr = getattr(self, name) + if hasattr(attr, "keys"): + adapter_names.update(attr.keys()) + return sorted(adapter_names) + + def delete_adapter(self, adapter_name: str) -> None: + """ + Delete an adapter from the layer + + This should be called on all adapter layers, or else we will get an inconsistent state. + + This method will also set a new active adapter if the deleted adapter was an active adapter. It is important + that the new adapter is chosen in a deterministic way, so that the same adapter is chosen on all layers. + + Args: + adapter_name (`str`): The name of the adapter to delete + + """ + for attr in self.adapter_layer_names + self.other_param_names: + if adapter_name in getattr(self, attr): + del getattr(self, attr)[adapter_name] + + if adapter_name in self.active_adapters: + # choose a new active adapter + active_adapters = self.active_adapters[:] + active_adapters.remove(adapter_name) + if active_adapters: + self.set_adapter(active_adapters) + else: + # no active adapters left, set a new default adapter + # here we get the list of all adapters existing adapter names and choose the first one + remaining_adapters = self._all_available_adapter_names() + if not remaining_adapters: + self.set_adapter([]) + else: + new_active_adapter = remaining_adapters[0] + warnings.warn( + f"Adapter {adapter_name} was active which is now deleted. Setting active adapter to " + f"{new_active_adapter}." + ) + self.set_adapter(remaining_adapters[0]) + + def set_requires_grad(self, adapter_names: str | Sequence[str], requires_grad: bool = True) -> None: + """ + Enable or disable gradients on the given adapter(s). + + Args: + adapter_name (`str` or `Sequence[str]`): + The name of the adapter(s) whose gradients should be enabled/disabled. + requires_grad (`bool`, *optional*) + Whether to enable (`True`, default) or disable (`False`). + """ + if isinstance(adapter_names, str): + adapter_names_set = {adapter_names} + else: + adapter_names_set = set(adapter_names) + + for layer_name in self.adapter_layer_names: + module_dict = getattr(self, layer_name) + for key, layer in module_dict.items(): + if key in adapter_names_set: + _set_layer_requires_grad(layer, requires_grad) + + def _get_base_layer_device_and_dtype(self, base_layer): + """ + Helper function to determine the device and dtype of the base layer. If not possible to determine, return None. + """ + device, dtype = None, None + + # check weight and qweight (for GPTQ) + for weight_name in ("weight", "qweight"): + weight = getattr(base_layer, weight_name, None) + if weight is not None: + device = weight.device + dtype = weight.dtype + break + + if hasattr(base_layer, "compute_dtype"): # bnb Linear4bitLt + dtype = base_layer.compute_dtype + + return device, dtype + + def _move_adapter_to_device_of_base_layer(self, adapter_name: str, device: Optional[torch.device] = None) -> None: + """ + Move the adapter of the given name to the device, and possibly dtype, of the base layer. + """ + base_layer = self.get_base_layer() + if isinstance(base_layer, nn.MultiheadAttention): + base_layer = base_layer.out_proj + base_layer_device, base_layer_dtype = self._get_base_layer_device_and_dtype(base_layer) + + target_device = device if device is not None else base_layer_device + if target_device is None: + # could not determine device + return + + target_dtype = None + if base_layer_dtype is not None: + # don't cast to int dtype + if base_layer_dtype.is_floating_point or base_layer_dtype.is_complex: + target_dtype = base_layer_dtype + + meta = torch.device("meta") + + # loop through all potential adapter layers and move them to the device of the base layer; be careful to only + # move this specific adapter to the device, as the other adapters could be on different devices + # see #1639 + for adapter_layer_name in self.adapter_layer_names + self.other_param_names: + adapter_layer = getattr(self, adapter_layer_name, None) + if not isinstance(adapter_layer, (nn.ModuleDict, nn.ParameterDict, BufferDict)): + continue + if adapter_name not in adapter_layer: + continue + if any(p.device == meta for p in adapter_layer.parameters()): + continue + + if target_dtype is not None: + adapter_layer[adapter_name] = adapter_layer[adapter_name].to(target_device, dtype=target_dtype) + else: + adapter_layer[adapter_name] = adapter_layer[adapter_name].to(target_device) + + @overload + def _cast_input_dtype(self, x: None, dtype: torch.dtype) -> None: ... + + @overload + def _cast_input_dtype(self, x: torch.Tensor, dtype: torch.dtype) -> torch.Tensor: ... + + 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_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 supports_lora_conversion(self, adapter_name: str = "default") -> bool: + """ + Whether it is possible for this layer type to be converted to LoRA. + + Normally, this works if the PEFT method is additive, i.e. W' = W_base + delta_weight. + """ + return False + + +def _find_minimal_target_modules( + target_modules: list[str] | set[str], other_module_names: list[str] | set[str] +) -> set[str]: + """Find the minimal set of target modules that is sufficient to separate them from the other modules. + + Sometimes, a very large list of target_modules could be passed, which can slow down loading of adapters (e.g. when + loaded from diffusers). It may be possible to condense this list from hundreds of items to just a handful of + suffixes that are sufficient to distinguish the target modules from the other modules. + + Example: + ```py + >>> from peft.tuners.tuners_utils import _find_minimal_target_modules + + >>> target_modules = [f"model.decoder.layers.{i}.self_attn.q_proj" for i in range(100)] + >>> target_modules += [f"model.decoder.layers.{i}.self_attn.v_proj" for i in range(100)] + >>> other_module_names = [f"model.encoder.layers.{i}.self_attn.k_proj" for i in range(100)] + >>> _find_minimal_target_modules(target_modules, other_module_names) + {"q_proj", "v_proj"} + ``` + + Args: + target_modules (`list[str]` | `set[str]`): + The list of target modules. + other_module_names (`list[str]` | `set[str]`): + The list of other module names. They must not overlap with the target modules. + + Returns: + `set[str]`: + The minimal set of target modules that is sufficient to separate them from the other modules. + + Raises: + ValueError: + If `target_modules` is not a list or set of strings or if it contains an empty string. Also raises an error + if `target_modules` and `other_module_names` contain common elements. + """ + if isinstance(target_modules, str) or not target_modules: + raise ValueError("target_modules should be a list or set of strings.") + + target_modules = set(target_modules) + if "" in target_modules: + raise ValueError("target_modules should not contain an empty string.") + + other_module_names = set(other_module_names) + if not target_modules.isdisjoint(other_module_names): + msg = ( + "target_modules and other_module_names contain common elements, this should not happen, please " + "open a GitHub issue at https://github.com/huggingface/peft/issues with the code to reproduce this issue" + ) + raise ValueError(msg) + + # it is assumed that module name parts are separated by a "." + def generate_suffixes(s): + parts = s.split(".") + return [".".join(parts[i:]) for i in range(len(parts))][::-1] + + # Create a reverse lookup for other_module_names to quickly check suffix matches + other_module_suffixes = {suffix for item in other_module_names for suffix in generate_suffixes(item)} + + # Find all potential suffixes from target_modules + target_modules_suffix_map = {item: generate_suffixes(item) for item in target_modules} + + # Initialize a set for required suffixes + required_suffixes = set() + + # We sort the target_modules_suffix_map simply to get deterministic behavior, since sets have no order. In theory + # the order should not matter but in case there is a bug, it's better for the bug to be deterministic. + for item, suffixes in sorted(target_modules_suffix_map.items(), key=lambda tup: tup[1]): + # Go through target_modules items, shortest suffixes first + for suffix in suffixes: + # If the suffix is already in required_suffixes or matches other_module_names, skip it + if suffix in required_suffixes or suffix in other_module_suffixes: + continue + # Check if adding this suffix covers the item + if not any(item.endswith("." + req_suffix) for req_suffix in required_suffixes): + required_suffixes.add(suffix) + break + + if not required_suffixes: + return set(target_modules) + return required_suffixes + + +class _ExcludedModule: + """ + A private helper method used to represent excluded modules in the check_target_module_exists function. + """ + + def __bool__(self): + return False + + +def check_target_module_exists(config, key: str) -> bool | re.Match[str] | None: + """A helper method to check if the passed module's key name matches any of the target modules in the adapter_config. + + Args: + config (`PeftConfig`): + A config to match target modules from. + key (`str`): + A key to search any matches in config + + Returns: + `bool` | `re.Match[str]` | `None`: + True or re.Match object if key matches any target modules from config, False or None if no match found. + """ + if hasattr(config, "exclude_modules") and config.exclude_modules: + if isinstance(config.exclude_modules, str): + if re.fullmatch(config.exclude_modules, key): + return _ExcludedModule() + elif key in config.exclude_modules or any( + key.endswith(f".{exclude_key}") for exclude_key in config.exclude_modules + ): + return _ExcludedModule() + + # Adapters should never match on modules to save modules as it is a guarantee for conflicts of behavior + # between `ModulesToSaveWrapper` internals and the potential adapter. + modules_to_save = getattr(config, "modules_to_save", None) + if modules_to_save: + if any(re.match(rf"(^|.*\.){m}($|\..*)", key) for m in modules_to_save): + return _ExcludedModule() + + if (config.target_modules is None) and (config.target_parameters is not None): + # this is allowed if config.target_parameters are specified + return False + + if isinstance(config.target_modules, str): + target_module_found = match_target_against_key(config.target_modules, key) + elif key in config.target_modules: + # this module is specified directly in target_modules + target_module_found = True + else: + target_module_found = any(key.endswith(f".{target_key}") for target_key in config.target_modules) + + layer_indexes = getattr(config, "layers_to_transform", None) + layers_pattern = getattr(config, "layers_pattern", None) + + is_using_layer_indexes = layer_indexes is not None and ( + len(layer_indexes) != 0 if isinstance(layer_indexes, list) else True + ) + if is_using_layer_indexes and target_module_found: + layer_index = None + # TODO: It's still unclear how empty layers_pattern (None, [], or "") should behave + # For now, empty layers_pattern means any layer pattern is ok + if layers_pattern is None or len(layers_pattern) == 0: + layer_index = re.match(r".*\.[^.]*\.(\d+)\.", key) + else: + layers_pattern = [layers_pattern] if isinstance(layers_pattern, str) else layers_pattern + for pattern in layers_pattern: + layer_index = re.match(rf".*\.{pattern}\.(\d+)\.", key) + if layer_index is not None: + break + + if layer_index is None: + target_module_found = False + else: + layer_index = int(layer_index.group(1)) + if isinstance(layer_indexes, int): + target_module_found = layer_index == layer_indexes + else: + target_module_found = layer_index in layer_indexes + + return target_module_found + + +def inspect_matched_modules(tuner: BaseTuner, adapter_name: str = "default") -> dict: + """ + A helper function to inspect the set of matched and unmatched modules for a PEFT model and the given adapter. + """ + config = tuner.peft_config[adapter_name] + key_list = [key for key, _ in tuner.model.named_modules()] + module_dict = {"matched": [], "unmatched": []} + for key in key_list: + if tuner._check_target_module_exists(config, key): + module_dict["matched"].append(key) + else: + module_dict["unmatched"].append(key) + return module_dict + + +def _maybe_include_all_linear_layers(peft_config: PeftConfig, model: nn.Module) -> PeftConfig: + """ + Helper function to update `target_modules` to all linear/Conv1D layers if provided as 'all-linear'. Adapted from + the QLoRA repository: https://github.com/artidoro/qlora/blob/main/qlora.py + """ + if not hasattr(peft_config, "target_modules"): + return peft_config + + # if `target_modules` is a string, convert to lower case and check if it matches "all-linear" + if not ( + isinstance(peft_config.target_modules, str) + and peft_config.target_modules.lower() == INCLUDE_LINEAR_LAYERS_SHORTHAND + ): + return peft_config + + linear_classes = (torch.nn.Linear, Conv1D) + linear_names = ("Linear",) + linear_module_names = set() + for name, module in model.named_modules(): + # match with all linear classes. + if isinstance(module, linear_classes): + linear_module_names.add(name) + elif isinstance(module, BaseTunerLayer) and any(n in type(module).__name__ for n in linear_names): + # If the model already has adapter layers applied, then the "linear" layer is actually an adapter layer, + # e.g. lora.Linear, and not nn.Linear. To target this layer, we don't want to check the layer type, as there + # are many possible layer types (one for each PEFT method) and the list would quickly get out of date. Thus + # we rely on the name of the layer class, which by convention is something like "Linear", "Linear4bit", + # "HqqLoraLinear", ... in PEFT. It's not pretty but should generally work. + # See 2390 + linear_module_names.add(name) + + # Try to remove linear layers that should not be targeted as best as possible. We have to rely on convention as + # there are no hard rules to detect these modules. + module_names_to_exclude = set() + if isinstance(model, PreTrainedModel): + output_emb = model.get_output_embeddings() + if output_emb is not None: + # ignore the last classification head for text generation models + last_module_name = next(name for name, module in model.named_modules() if module is output_emb) + module_names_to_exclude.add(last_module_name) + elif peft_config.task_type == TaskType.SEQ_CLS: + # ignore classifier head for classification models (issue 2027) + # there is no fix name for the classifier head, so check the common ones + for name in SEQ_CLS_HEAD_NAMES: + cls_head = getattr(model, name, None) + if cls_head is not None: + last_module_name = next(name for name, module in model.named_modules() if module is cls_head) + module_names_to_exclude.add(last_module_name) + break + + # we don't want nested LoRA layers, i.e. LoRA being applied to possibly existing lora_A, lora_B, etc. + # see 2390 + for prefix, module in model.named_modules(): + if isinstance(module, BaseTunerLayer): + for suffix, child in module.named_modules(): + if suffix: + module_names_to_exclude.add(f"{prefix}.{suffix}") + + linear_module_names -= module_names_to_exclude + peft_config.target_modules = linear_module_names + return peft_config + + +def check_adapters_to_merge(module: BaseTunerLayer, adapter_names: Optional[list[str]] = None) -> list[str]: + """ + Helper function to check which adapters should be merged. + + Only return those adapters that are not already merged. Give a warning if some or all of the adapters are already + merged. + + """ + if adapter_names is None: + adapter_names = module.active_adapters + if isinstance(adapter_names, str): + raise TypeError(f"adapter_names should be a list of strings, got {adapter_names!r}.") + + if module.merged: + merged_adapters = set(module.merged_adapters) + adapter_names = [name for name in adapter_names if name not in merged_adapters] + + if adapter_names: + warnings.warn( + f"Already following adapters were merged {','.join(module.merged_adapters)}. " + f"You are now additionally merging {','.join(adapter_names)}." + ) + else: + warnings.warn("All adapters are already merged, nothing to do.") + + return adapter_names + + +def clone_module(module: nn.Module, share_weights=False): + """Clone a module in a pytorch model. + + Clones a module of a model, optionally sharing all the parameters between the original and the clone. Simplifies + reusing a module when manipulating the architecture of a model. + """ + clone = copy.deepcopy(module) + + def _share_weights(src: nn.Module, dst: nn.Module): + for name, param in src.named_parameters(recurse=False): + dst.register_parameter(name, param) + + if share_weights: + for name, submodule in module.named_modules(): + _share_weights(submodule, clone.get_submodule(name)) + + return clone + + +def replicate_layers(model: nn.Module, layer_map: list[tuple[int, int]]): + """Replicate layers in a transfomer model with weight sharing. + + This function looks for a module list attribute at model[(.model)*].layers and replicates the layers in the module + list according to the layer map. For example the map `[[0, 4], [2, 5]]` will take the set of layers `[0, 1, 2, 3, + 4]` and replace them with a module list containing `[0, 1, 2, 3, 2, 3, 4]`. + """ + while hasattr(model, "model"): + model = model.model + # Some variants of the bert model nest the main model under the bert attribute. + if hasattr(model, "bert"): + model = model.bert + + model_type = None + layers: nn.ModuleList = None + if hasattr(model, "layers"): + model_type = "llama" + layers = model.layers + elif hasattr(model, "encoder") and hasattr(model.encoder, "layer"): + model_type = "bert" + layers = model.encoder.layer + elif hasattr(model, "h"): + model_type = "falcon" + layers = model.h + if not model_type or not isinstance(layers, nn.ModuleList): + raise ValueError( + "Could not locate the layers attribute in the model. " + "Expected Llama, Bert or Falcon compatible architectures." + ) + + new_layers = [] + for start, end in layer_map: + for i in range(start, end): + current_idx = len(new_layers) + new_layers.append(clone_module(layers[i], share_weights=True)) + # This is a hack needed to work around the layer_idx introduced in HF transformers. + for submodule in new_layers[-1].modules(): + if hasattr(submodule, "layer_idx"): + submodule.layer_idx = current_idx + layers = nn.ModuleList(new_layers) + if model_type == "llama": + model.layers = layers + elif model_type == "bert": + model.encoder.layer = layers + elif model_type == "falcon": + model.h = layers + else: + raise ValueError("Unexpected model type, need to handle post-processing of layers.") + if hasattr(model.config, "num_hidden_layers"): # Common to Llama, Bert, Falcon. + model.config.num_hidden_layers = len(new_layers) + + +def find_parameter_name_by_module(model: nn.Module, reference_module: nn.Module) -> str: + """ + Find layer name from the model by matching the reference module to the model named modules + + Args: + model (nn.Module): The model with named modules + reference_module (nn.Module): The reference module to find + + Returns: + str: Name of the layer + """ + for n, m in model.named_modules(): + if m is reference_module: + return n + + return "" + + +############################### +# FUNCTIONS FOR functional.py # +############################### + + +def set_adapter( + model, + adapter_name: str | list[str], + inference_mode: bool = False, + layer_cls: type[BaseTunerLayer] = BaseTunerLayer, +) -> None: + """Set the active PEFT adapter(s) of the model. + + Active adapters are those adapters that participate in the forward pass. Use this function if you want to switch + between multiple PEFT adapters. + + Args: + model (`nn.Module`): + The model on which the adapter(s) should be set. + adapter_name (str, list[str]): + The name(s) of the adapter(s) to set as active + inference_mode (bool, optional): + Whether the activated adapter should be frozen (i.e. `requires_grad=False`). Default is False. + layer_cls (type, optional): + The class of the adapter layer. Defaults to `BaseTunerLayer`. + """ + _set_adapter(model, adapter_name, inference_mode=inference_mode) # auxiliary modules + for module in model.modules(): + if isinstance(module, layer_cls): + if module.merged: + warnings.warn("Adapter cannot be set when the model is merged. Unmerging the model first.") + module.unmerge() + module.set_adapter(adapter_name, inference_mode=inference_mode) + + +def _delete_auxiliary_adapter(model, adapter_name: str, new_active_adapters: Optional[list[str]]) -> None: + for module in model.modules(): + if isinstance(module, AuxiliaryTrainingWrapper): + module.delete_adapter(adapter_name, new_active_adapters=new_active_adapters) + + +def delete_adapter( + model: nn.Module, adapter_name: str, prefix: str, layer_cls: type[BaseTunerLayer] = BaseTunerLayer +) -> list[str] | None: + """ + Delete an existing PEFT adapter. + + Note: This function does not delete the PEFT config on the model, if there is one. It will also not completely + purge the PEFT layers if the last PEFT adapter is deleted. For this, consider using `model.unload()` if using a + PEFT model instance, or just reloading the base model. + + Args: + model (`nn.Module`): + The model from which the adapter should be deleted. + adapter_name (str): + The name of the adapter to be deleted. + prefix (str): + The prefix of the PEFT method, e.g. "lora_" for LoRA. + layer_cls (type, optional): + The class of the adapter layer. Defaults to `BaseTunerLayer`. + + Returns: + new_adapter (list[str] | None): + The name of remaining adapter(s) after deletion, or `None` if there are no active adapters left. Use this + to set the new active adapter of the model if necessary. + """ + key_list = [key for key, _ in model.named_modules() if prefix not in key] + new_adapter = None + + for key in key_list: + _, target, _ = _get_submodules(model, key) + if isinstance(target, layer_cls): + target.delete_adapter(adapter_name) + if new_adapter is None: + new_adapter = target.active_adapters[:] + + _delete_auxiliary_adapter(model, adapter_name=adapter_name, new_active_adapters=new_adapter) + return new_adapter + + +def cast_adapter_dtype(model: nn.Module, adapter_name: str, autocast_adapter_dtype: bool = True) -> None: + """ + A helper method to cast the adapter weights to the correct dtype. + + Currently, this only upcasts float dtypes to float32. + + Args: + adapter_name (`str`): + The adapter name. + autocast_adapter_dtype (`bool`, *optional*): + Whether to autocast the adapter dtype. Defaults to `True`. + """ + if not autocast_adapter_dtype: + return + + dtypes_to_convert_to_fp32 = {torch.float16, torch.bfloat16} + # Upcast lower precision floats like float8_e4m3fn; defensively only include dtypes that are actually found, as this + # could depend on torch version and platform + for name in UPCAST_DTYPES: + if (torch_dtype := getattr(torch, name, None)) is not None: + dtypes_to_convert_to_fp32.add(torch_dtype) + + for module in model.modules(): + if not isinstance(module, BaseTunerLayer): + continue + + for submodule in module.modules(): + if not isinstance(submodule, (nn.ModuleDict, nn.ParameterDict, BufferDict)): + continue + + if adapter_name not in submodule: + continue + + if isinstance(submodule[adapter_name], nn.Parameter): + if submodule[adapter_name].dtype in dtypes_to_convert_to_fp32: + submodule[adapter_name].data = submodule[adapter_name].data.to(torch.float32) + continue + + if isinstance(submodule[adapter_name], torch.Tensor): # e.g. from a BufferDict + if submodule[adapter_name].dtype in dtypes_to_convert_to_fp32: + submodule[adapter_name] = submodule[adapter_name].to(torch.float32) + continue + + for param in submodule[adapter_name].parameters(): + if param.dtype in dtypes_to_convert_to_fp32: + param.data = param.data.to(torch.float32) + + +def set_requires_grad(model, adapter_names: str | Sequence[str], requires_grad: bool = True) -> None: + """ + Enable or disable gradients on the given adapter(s). + + Args: + model (`nn.Module`): + The model from which the adapter should be deleted. + adapter_name (`str` or `Sequence[str]`): + The name of the adapter(s) whose gradients should be enabled/disabled. + requires_grad (`bool`, *optional*) + Whether to enable (`True`, default) or disable (`False`). + """ + for module in model.modules(): + if isinstance(module, (BaseTunerLayer, AuxiliaryTrainingWrapper)): + module.set_requires_grad(adapter_names=adapter_names, requires_grad=requires_grad) + + +def get_device_map(model) -> dict: + if hasattr(model, "hf_device_map"): + # Multi-device case: accelerate dispatch is active and exposes hf_device_map + device_map = model.hf_device_map + else: + # Single-device case: + # Recent Transformers versions intentionally skip accelerate hooks when the + # device_map resolves to a single device (e.g. "cpu" or one GPU), so + # hf_device_map is not set. All parameters are guaranteed to be on the + # same device, which can be inferred from the first parameter. + device_map = {"": next(model.parameters()).device} + return device_map diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/vblora/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/vblora/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8e71a08461e8b7cb2fb5513a3bf908a4a98c0747 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/vblora/__init__.py @@ -0,0 +1,24 @@ +# 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 peft.utils import register_peft_method + +from .config import VBLoRAConfig +from .layer import Linear, VBLoRALayer +from .model import VBLoRAModel + + +__all__ = ["Linear", "VBLoRAConfig", "VBLoRALayer", "VBLoRAModel"] + +register_peft_method(name="vblora", config_cls=VBLoRAConfig, model_cls=VBLoRAModel) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/vblora/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/vblora/config.py new file mode 100644 index 0000000000000000000000000000000000000000..884a28729935c4c232e435e9bafc1578c9f8355c --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/vblora/config.py @@ -0,0 +1,196 @@ +# 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 + +from dataclasses import dataclass, field +from typing import Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class VBLoRAConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`VBLoRAModel`]. + + Paper: https://huggingface.co/papers/2405.15179 + + Args: + r (`int`): + The rank of incremental matrices. + num_vectors (`int`): + Number of vectors in the vector bank. Use higher values when the model size increases. + vector_length (`int`): + The length of the vectors in the vector bank. The length of the vectors should be divisible by the hidden + dimension of the model. + topk (`int`): + The K value for top-K selection. A larger value of K increases the size of the saved model. In practice, + setting K=2 typically provides the best performance and parameter efficiency. For more details, refer to + the discussion in the paper. + target_modules (`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/Conv1D 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. + 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. + save_only_topk_weights (`bool`): + Whether to only save the topk weights. Setting `save_only_topk_weights = True` significantly reduces + storage space. However, models saved in this mode can be used for merging or inference only, not for + resuming training. + vblora_dropout (`float`): + The dropout probability for VBLoRA layers. + 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 for VBLoRA. Can be 'none', 'all' or 'vblora_only'. If 'all' or 'vblora_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 VBLoRA layers to be set as trainable and saved in the final checkpoint. + init_vector_bank_bound (`float`): + The vector bank is initialized with a uniform distribution between -init_vector_bank_bound and + init_vector_bank_bound. Avoid initializing the vector bank with all zeros to prevent zero gradients. A + small value, such as 0.02, is typically effective. Initializing with a large value may cause training + instability. + init_logits_std (`float`): + The logits are initialized with a normal distribution with a standard deviation of init_logits_std. Default + is 0.1. + 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'`. + """ + + r: int = field(default=4, metadata={"help": "The rank of incremental matrices."}) + num_vectors: int = field( + default=256, + metadata={"help": "Number of vectors in the vector bank. Use higher values when the model size increases."}, + ) + vector_length: int = field( + default=256, + metadata={ + "help": "The length of the vectors in the vector bank. The length of the vectors should be divisible by " + "the hidden dimension of the model." + }, + ) + topk: int = field( + default=2, + metadata={ + "help": "The K value for top-K selection. A larger value of K increases the size of the saved model. " + "In practice, setting K=2 typically provides the best performance and parameter efficiency. " + "For more details, refer to the discussion in the paper." + }, + ) + 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 LoRA." + "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." + "If 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." + ) + }, + ) + 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 VBLoRA."}, + ) + save_only_topk_weights: bool = field( + default=False, + metadata={ + "help": ( + "Whether to only save the topk weights. Setting `save_only_topk_weights = True` significantly reduces " + "storage space. However, models saved in this mode can be used for merging or inference only, not for " + "resuming training." + ) + }, + ) + vblora_dropout: float = field(default=0.0, metadata={"help": "VBLoRA dropout"}) + 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: str = field(default="none", metadata={"help": "Bias type for VBLoRA. Can be 'none', 'all' or 'vblora_only'"}) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": ( + "List of modules apart from VBLoRA 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_vector_bank_bound: float = field( + default=0.02, + metadata={ + "help": ( + "The vector bank is initialized with a uniform distribution between -init_vector_bank_bound and" + " init_vector_bank_bound. Avoid initializing the vector bank with all zeros to prevent zero gradients." + " A small value, such as 0.02, is typically effective. Initializing with a large value may cause" + " training instability." + ), + }, + ) + init_logits_std: float = field( + default=0.1, + metadata={ + "help": ( + "The logits are initialized with a normal distribution with a standard deviation of init_logits_std. " + "Default value 0.1 typically works well." + ), + }, + ) + 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. " + "This only works when target_modules is a list of str. This should target the `nn.ModuleList` of the " + "model, which is often called `'layers'` or `'h'`." + }, + ) + 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 only works when target_modules is a list of str." + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.VBLORA + 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. ") diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/vblora/layer.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/vblora/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..ba9d90e7b3f1b5a557e1e07165d54fae2da74268 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/vblora/layer.py @@ -0,0 +1,255 @@ +# 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 typing import Optional + +import torch +import torch.nn.functional as F +from torch import nn +from transformers.pytorch_utils import Conv1D + +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge +from peft.utils.other import transpose + +from .config import VBLoRAConfig + + +class VBLoRALayer(BaseTunerLayer): + # List all names of layers that may contain adapter weights + adapter_layer_names = ("vblora_logits_A", "vblora_logits_B", "vblora_vector_bank") + + def __init__(self, base_layer: nn.Module, **kwargs): + self.base_layer = base_layer + self.r = {} + self.topk = {} + self.vblora_dropout = nn.ModuleDict({}) + + # For storing vector scale + self.vblora_logits_A = nn.ParameterDict({}) + self.vblora_logits_B = nn.ParameterDict({}) + + # 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 + 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: str, + vblora_vector_bank, + r: int, + config: VBLoRAConfig, + inference_mode: bool = False, + **kwargs, + ): + topk = config.topk + num_vectors = config.num_vectors + vector_length = config.vector_length + vblora_dropout = config.vblora_dropout + init_logits_std = config.init_logits_std + + if r <= 0: + raise ValueError(f"`r` {r} should be a positive integer value") + if topk <= 0: + raise ValueError(f"`topk` {topk} should be a positive integer value") + + if self.in_features % vector_length != 0: + raise ValueError(f"`in_features` {self.in_features} must be divisible by `vector_length` {vector_length}") + if self.out_features % vector_length != 0: + raise ValueError( + f"`out_features` {self.out_features} must be divisible by `vector_length` {vector_length}" + ) + + self.r[adapter_name] = r + self.topk[adapter_name] = topk + if vblora_dropout > 0.0: + vblora_dropout_layer = nn.Dropout(p=vblora_dropout) + else: + vblora_dropout_layer = nn.Identity() + self.vblora_dropout.update(nn.ModuleDict({adapter_name: vblora_dropout_layer})) + self.vblora_logits_A[adapter_name] = nn.Parameter( + torch.zeros(r, self.in_features // vector_length, num_vectors), requires_grad=True + ) + self.vblora_logits_B[adapter_name] = nn.Parameter( + torch.zeros(self.out_features // vector_length, r, num_vectors), requires_grad=True + ) + self.vblora_vector_bank = vblora_vector_bank + self.reset_vblora_logits(adapter_name, init_logits_std) + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def reset_vblora_logits(self, adapter_name, init_logits_std): + if adapter_name in self.vblora_logits_A.keys(): + with torch.no_grad(): + nn.init.normal_(self.vblora_logits_A[adapter_name], 0, init_logits_std) + nn.init.normal_(self.vblora_logits_B[adapter_name], 0, init_logits_std) + + +class Linear(nn.Linear, VBLoRALayer): + # VBLoRA implemented in a dense layer + def __init__( + self, + base_layer, + vblora_vector_bank, + adapter_name: str, + config: VBLoRAConfig, + r: int, + is_target_conv_1d_layer: bool = False, + **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__() + VBLoRALayer.__init__(self, base_layer, **kwargs) + self.fan_in_fan_out = config.fan_in_fan_out + self._active_adapter = adapter_name + self.update_layer(adapter_name, vblora_vector_bank, r, config=config) + 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.vblora_logits_A.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.vblora_logits_A.keys(): + self.get_base_layer().weight.data -= self.get_delta_weight(active_adapter) + + def _get_low_rank_matrix(self, logits: torch.tensor, vblora_vector_bank, topk) -> torch.Tensor: + top_k_logits, indices = logits.topk(topk, dim=-1) + topk_weights = F.softmax(top_k_logits, dim=-1) + return (topk_weights.unsqueeze(-1) * vblora_vector_bank[indices]).sum(-2) + + def _get_lora_matrices(self, adapter, cast_to_fp32=False) -> tuple[torch.Tensor, torch.Tensor]: + vblora_logits_A = self.vblora_logits_A[adapter] + vblora_logits_B = self.vblora_logits_B[adapter] + + # Check for infinity values when training. If found, training was likely resumed from a `save_only_topk_weights` model. + if self.training and vblora_logits_A[0, 0].isinf().any(): + raise RuntimeError( + "Found infinity values in VB-LoRA logits. Ensure training was not resumed from a `save_only_topk_weights` model." + ) + + vblora_vector_bank = self.vblora_vector_bank[adapter].to(vblora_logits_A.device) + topk = self.topk[adapter] + # In case users wants to merge the adapter weights that are in + # float16 while being on CPU, we need to cast the weights to float32, perform the merge and then cast back to + # float16 because the `@` and matmul operation in general is not supported in torch + cpu + fp16. + if cast_to_fp32: + vblora_logits_A = vblora_logits_A.float() + vblora_logits_B = vblora_logits_B.float() + vblora_vector_bank = vblora_vector_bank.float() + + # A: (rank, in_tile, vector_length) -> (rank, in_tile x vector_length) + A = self._get_low_rank_matrix(vblora_logits_A, vblora_vector_bank, topk).reshape(vblora_logits_A.shape[0], -1) + # B: (out_tile, rank, vector_length) -> (out_tile, vector_length, rank) -> (out_tile x vector_length, rank) + B = ( + self._get_low_rank_matrix(vblora_logits_B, vblora_vector_bank, topk) + .transpose(1, 2) + .reshape(-1, vblora_logits_B.shape[1]) + ) + return A, B + + 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.vblora_logits_A[adapter].device + dtype = self.vblora_logits_A[adapter].dtype + cast_to_fp32 = device.type == "cpu" and dtype == torch.float16 + A, B = self._get_lora_matrices(adapter, cast_to_fp32) + output_tensor = transpose(B @ A, self.fan_in_fan_out) + return output_tensor + + 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.vblora_logits_A.keys(): + continue + A, B = self._get_lora_matrices(active_adapter) + x = x.to(self.vblora_vector_bank[active_adapter].dtype) + dropout = self.vblora_dropout[active_adapter] + result = result + F.linear(F.linear(dropout(x), A), B) + 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 "vblora." + rep diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/vblora/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/vblora/model.py new file mode 100644 index 0000000000000000000000000000000000000000..992e51b9ce8141208705f162d09f557a5e75acdd --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/vblora/model.py @@ -0,0 +1,201 @@ +# 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 warnings + +import torch +from torch import nn +from transformers.pytorch_utils import Conv1D + +from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer +from peft.utils import TRANSFORMERS_MODELS_TO_VBLORA_TARGET_MODULES_MAPPING + +from .config import VBLoRAConfig +from .layer import Linear, VBLoRALayer + + +class VBLoRAModel(BaseTuner): + """ + Creates VBLoRA model from a pretrained transformers model. + + The method is described in detail in https://huggingface.co/papers/2405.15179. + + Args: + model ([`~transformers.PreTrainedModel`]): The model to be adapted. + config ([`VBLoRAConfig`]): The configuration of the VBLoRA 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 VBLoRA model. + + Example: + + ```py + >>> from transformers import AutoModelForCausalLM + >>> from peft import VBLoRAConfig, get_peft_model + + >>> base_model = AutoModelForCausalLM.from_pretrained("facebook/opt-125m") + >>> config = VBLoRAConfig( + ... task_type="SEQ_CLS", + ... r=4, + ... target_modules=["fc1", "fc2", "k_proj", "out_proj", "q_proj", "v_proj"], + ... num_vectors=60, + ... vector_length=256, + ... save_only_topk_weights=True, + ... ) + >>> model = get_peft_model(base_model, config) + ``` + + **Attributes**: + - **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted. + - **peft_config** ([`VBLoRAConfig`]): The configuration of the VBLoRAConfig model. + """ + + prefix: str = "vblora_" + tuner_layer_cls = VBLoRALayer + target_module_mapping = TRANSFORMERS_MODELS_TO_VBLORA_TARGET_MODULES_MAPPING + + def _init_vblora_vector_bank(self, config: VBLoRAConfig, adapter_name: str) -> None: + vblora_vector_bank = torch.zeros(config.num_vectors, config.vector_length) + torch.nn.init.uniform_(vblora_vector_bank, -config.init_vector_bank_bound, config.init_vector_bank_bound) + self.vblora_vector_bank[adapter_name] = vblora_vector_bank + + def _pre_injection_hook(self, model: nn.Module, config: VBLoRAConfig, adapter_name: str) -> None: + self.vblora_vector_bank = nn.ParameterDict({}) + + def _create_and_replace( + self, + vblora_config, + adapter_name, + target, + target_name, + parent, + current_key, + ): + if current_key is None: + raise ValueError("Current Key shouldn't be `None`") + + bias = hasattr(target, "bias") and target.bias is not None + kwargs = { + "fan_in_fan_out": vblora_config.fan_in_fan_out, + "bias": bias, + } + self._init_vblora_vector_bank(vblora_config, adapter_name) + # TODO: add quantization support + + if isinstance(target, Linear): + target.update_layer( + adapter_name=adapter_name, + vblora_vector_bank=self.vblora_vector_bank, + r=vblora_config.r, + config=vblora_config, + ) + else: + new_module = self._create_new_module( + vblora_config=vblora_config, + vblora_vector_bank=self.vblora_vector_bank, + adapter_name=adapter_name, + target=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(vblora_config, vblora_vector_bank, 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): + if vblora_config.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." + ) + vblora_config.fan_in_fan_out = False + elif isinstance(target_base_layer, Conv1D): + kwargs["is_target_conv_1d_layer"] = True + if not vblora_config.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." + ) + vblora_config.fan_in_fan_out = True + else: + raise TypeError( + f"Target module {target} is not supported. Currently, only the following modules are supported: " + "`torch.nn.Linear`, `transformers.pytorch_utils.Conv1D`." + ) + new_module = Linear( + base_layer=target, + vblora_vector_bank=vblora_vector_bank, + adapter_name=adapter_name, + config=vblora_config, + r=vblora_config.r, + **kwargs, + ) + + return new_module + + def get_nb_savable_parameters(self, adapter="default") -> tuple[int, int]: + r""" + Returns the number of savable VB-LoRA parameters and other savable parameters. + """ + logits_params = 0 + vector_bank_params = 0 + other_params = 0 + for name, param in self.named_parameters(): + if "vblora_logits" in name: + logits_params += param.numel() + elif "vblora_vector_bank" in name: + vector_bank_params += param.numel() + elif param.requires_grad: + other_params += param.numel() + if self.peft_config[adapter].save_only_topk_weights: + num_vectors = self.peft_config[adapter].num_vectors + factor = 1 # factor to count float32-equivalent parameters + if num_vectors < 2**8: + factor = 0.25 + elif num_vectors < 2**15: + factor = 0.5 + elif num_vectors < 2**31: + factor = 1 + else: + factor = 2 + topk_weight_params = ( + logits_params / self.peft_config[adapter].num_vectors * (self.peft_config[adapter].topk - 1) + ) + topk_indices_params = ( + logits_params / self.peft_config[adapter].num_vectors * self.peft_config[adapter].topk * factor + ) + vblora_params = int(vector_bank_params + topk_weight_params + topk_indices_params) + else: + vblora_params = vector_bank_params + logits_params + return vblora_params, other_params + + def print_savable_parameters(self) -> None: + r""" + Prints the number of savable VB-LoRA parameters and total savable parameters. + """ + vblora_params, other_params = self.get_nb_savable_parameters() + print( + f"VB-LoRA params to-be-saved (float32-equivalent): {vblora_params:,d} " + f"|| total params to-be-saved: {(vblora_params + other_params):,d}" + ) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/vera/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/vera/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ba7b13705f3d5b5447a728edc541d4bc9d111950 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/vera/__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 VeraConfig +from .layer import Linear, VeraLayer +from .model import VeraModel + + +__all__ = ["Linear", "VeraConfig", "VeraLayer", "VeraModel"] + + +register_peft_method(name="vera", config_cls=VeraConfig, model_cls=VeraModel, prefix="vera_lambda_") diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/vera/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/vera/config.py new file mode 100644 index 0000000000000000000000000000000000000000..df880b7af0df6b92717e339f131474340e2ade3c --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/vera/config.py @@ -0,0 +1,162 @@ +# 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 Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class VeraConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`VeraModel`]. + + Paper: https://huggingface.co/papers/2310.11454. + + Args: + r (`int`, *optional*, defaults to `256`): + VeRA parameter dimension ("rank"). Choose higher values than LoRA ranks here, since VeRA uses far fewer + parameters than LoRA (see Table 1). + target_modules (`Union[List[str], str]`): + The names of the modules to apply Vera to. Only linear layers are supported. + projection_prng_key (`int`): + Vera PRNG init key. Used for initialising vera_A and vera_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 vera_A / vera_B projections in the state dict alongside per layer lambda_b / lambda_d + weights. This will increase the size of the checkpoint, but guarantee that we can reload the checkpoint on + all system configurations. Defaults to `True`. + vera_dropout (`float`): + The dropout probability for Vera layers. + d_initial (`float`, *optional*, defaults to `0.1`): + Initial init value for `vera_lambda_d` vector used when initializing the VeRA parameters. Small values + (<=0.1) are recommended (see Table 6c in the paper). + 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 for Vera. Can be 'none', 'all' or 'vera_only'. If 'all' or 'vera_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 Vera layers to be set as trainable and saved in the final checkpoint. + init_weights (`bool`): + Whether to initialize the weights of the Vera 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 Vera transformations on + the layer indexes that are specified in this list. If a single integer is passed, it will apply the Vera + 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'`. + """ + + r: int = field(default=256, metadata={"help": "Vera 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 Vera." + "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'. " + "Only linear layers are supported." + ) + }, + ) + projection_prng_key: int = field( + default=0, + metadata={ + "help": ( + "Vera PRNG init key. Used for initialising vera_A and vera_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 vera_A / vera_B projections in the state dict alongside per layer lambda_b / " + "lambda_d weights. This will increase the size of the checkpoint, but guarantee that we can reload " + "the checkpoint on all system configurations." + ) + }, + ) + vera_dropout: float = field(default=0.0, metadata={"help": "Vera dropout"}) + d_initial: float = field(default=0.1, metadata={"help": "Initial init value for d vector."}) + 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: str = field(default="none", metadata={"help": "Bias type for Vera. Can be 'none', 'all' or 'vera_only'"}) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": ( + "List of modules apart from Vera 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 Vera 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'`." + ) + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.VERA + self.target_modules = ( + set(self.target_modules) if isinstance(self.target_modules, list) else self.target_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 not self.save_projection: + warnings.warn( + "Specified to not save vera_A and vera_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/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/vera/layer.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/vera/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..ee17955b154efee3096d10f0171c202a3ce9cfc2 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/vera/layer.py @@ -0,0 +1,299 @@ +# 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 warnings +from typing import Optional + +import torch +import torch.nn.functional as F +from torch import nn + +from peft.tuners.tuners_utils import BaseTunerLayer, _get_in_out_features, check_adapters_to_merge +from peft.utils import quantization_extra_repr, resolve_quantization_backend +from peft.utils.other import transpose + +from .._buffer_dict import BufferDict +from .config import VeraConfig + + +class VeraLayer(BaseTunerLayer): + # List all names of layers that may contain adapter weights + adapter_layer_names = ("vera_lambda_b", "vera_lambda_d") + other_param_names = ("vera_A", "vera_B") + + def __init__(self, base_layer: nn.Module, **kwargs): + self.base_layer = base_layer + self.quantization_backend = resolve_quantization_backend( + self.get_base_layer(), get_apply_tensor_subclass=kwargs.get("get_apply_tensor_subclass") + ) + self.r = {} + self.vera_dropout = nn.ModuleDict({}) + + # For storing vector scale + self.vera_lambda_b = nn.ParameterDict({}) + self.vera_lambda_d = nn.ParameterDict({}) + + # Stores a reference to the vera_A/B BufferDict. + # Set to `None` otherwise to avoid computation with random weights + self.vera_A: Optional[BufferDict] = None + self.vera_B: Optional[BufferDict] = None + + # Mark the weight as unmerged + self._disable_adapters = False + self.merged_adapters = [] + + base_layer = self.get_base_layer() + in_features, out_features = _get_in_out_features(base_layer) + if (in_features is None) or (out_features is None): + raise TypeError(f"Unsupported layer type {type(base_layer)}") + + self.in_features = in_features + self.out_features = out_features + self.kwargs = kwargs + + def update_layer( + self, + adapter_name, + vera_A: BufferDict, + vera_B: BufferDict, + r, + config: VeraConfig, + inference_mode: bool = False, + **kwargs, + ): + vera_dropout = config.vera_dropout + init_weights = config.init_weights + d_initial = config.d_initial + + 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 vera_dropout > 0.0: + vera_dropout_layer = nn.Dropout(p=vera_dropout) + else: + vera_dropout_layer = nn.Identity() + + self.vera_dropout.update(nn.ModuleDict({adapter_name: vera_dropout_layer})) + # Actual trainable parameters + self.vera_lambda_b[adapter_name] = nn.Parameter(torch.ones(self.out_features), requires_grad=True) + self.vera_lambda_d[adapter_name] = nn.Parameter(torch.randn(r), requires_grad=True) + + # non trainable references to vera_A/B buffers + self.vera_A = vera_A + self.vera_B = vera_B + if adapter_name not in vera_A: + # This means that this is not the first VeRA adapter. We have to add an entry in the dict for this adapter. + if len(self.vera_A) < 1: + raise ValueError( + "The `vera_A` and `vera_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 + vera_A_param = next(iter(self.vera_A.values())) + vera_B_param = next(iter(self.vera_B.values())) + + error_tmpl = ( + "{} has a size of {} but {} or greater is required; this probably happened because an additional VeRA " + "adapter was added after the first one with incompatible shapes." + ) + # check input size + if vera_A_param.shape[1] < self.in_features: + raise ValueError(error_tmpl.format("vera_A", vera_A_param.shape[1], self.in_features)) + # check output size + if vera_B_param.shape[0] < self.out_features: + raise ValueError(error_tmpl.format("vera_B", vera_B_param.shape[0], self.out_features)) + # check r + error_tmpl = ( + "{} has a size of {} but {} or greater is required; this probably happened because an additional VeRA " + "adapter with a lower rank was added after the first one; loading the adapters " + "in reverse order may solve this." + ) + if vera_A_param.shape[0] < self.r[adapter_name]: + raise ValueError(error_tmpl.format("vera_A", vera_A_param.shape[0], self.r[adapter_name])) + if vera_B_param.shape[1] < self.r[adapter_name]: + raise ValueError(error_tmpl.format("vera_B", vera_B_param.shape[1], self.r[adapter_name])) + + self.vera_A[adapter_name] = vera_A_param + self.vera_B[adapter_name] = vera_B_param + + if init_weights: + self.reset_vera_parameters(adapter_name, d_initial=d_initial) + + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def reset_vera_parameters(self, adapter_name, d_initial: float = 0.1): + if adapter_name in self.vera_lambda_d.keys(): + with torch.no_grad(): + nn.init.zeros_(self.vera_lambda_d[adapter_name]).fill_(d_initial) + nn.init.zeros_(self.vera_lambda_b[adapter_name]) + + +class Linear(nn.Module, VeraLayer): + # Vera implemented in a dense layer + def __init__( + self, + base_layer, + vera_A: BufferDict, + vera_B: BufferDict, + adapter_name: str, + config: VeraConfig, + r: int = 0, + is_target_conv_1d_layer: bool = False, + **kwargs, + ) -> None: + # this gets the init from nn.Linear's super perspective, i.e. nn.Module.__init__, which should always be called + super().__init__() + VeraLayer.__init__(self, base_layer, **kwargs) + self.fan_in_fan_out = config.fan_in_fan_out + + self._active_adapter = adapter_name + self.update_layer(adapter_name, vera_A, vera_B, r, config=config) + 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.vera_lambda_d.keys(): + if safe_merge: + # Note that safe_merge will be slower than the normal merge + # because of the copy operation. + weight = self.get_base_weight().clone() + weight += self.get_delta_weight(active_adapter) + + if not torch.isfinite(weight).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + self.set_base_weight(weight) + else: + weight = self.get_base_weight() + weight += self.get_delta_weight(active_adapter) + self.set_base_weight(weight) + 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.vera_lambda_d.keys(): + weight = self.get_base_weight() + weight -= self.get_delta_weight(active_adapter) + self.set_base_weight(weight) + + 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. + """ + vera_A = self.vera_A[adapter] + vera_B = self.vera_B[adapter] + + device = vera_B.device + dtype = vera_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) + + lambda_d = self.vera_lambda_d[adapter] + lambda_b = self.vera_lambda_b[adapter] + + if cast_to_fp32: + vera_A = vera_A.float() + vera_B = vera_B.float() + lambda_d = lambda_d.float() + lambda_b = lambda_b.float() + + sliced_A = vera_A[:, : self.in_features].to(lambda_d.device) + sliced_B = vera_B[: self.out_features, :].to(lambda_d.device) + lambda_b = lambda_b.unsqueeze(-1) + lambda_d = lambda_d.unsqueeze(-1) + output_tensor = transpose((lambda_b * sliced_B) @ (lambda_d * sliced_A), self.fan_in_fan_out) + + if cast_to_fp32: + output_tensor = output_tensor.to(dtype=dtype) + + return output_tensor + + 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) + orig_dtype = result.dtype + if self.quantization_backend is not None: + result = self.quantization_backend.maybe_clone_base_result(result) + for active_adapter in self.active_adapters: + if active_adapter not in self.vera_lambda_d.keys(): + continue + + lambda_d = self.vera_lambda_d[active_adapter] + lambda_b = self.vera_lambda_b[active_adapter] + + vera_A = self.vera_A[active_adapter] + vera_B = self.vera_B[active_adapter] + + # As adapted layers may have different shapes and VeRA 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 vera_A and vera_B. + sliced_A = vera_A[:, : self.in_features].to(x.device) + sliced_B = vera_B[: self.out_features, :].to(x.device) + + dropout = self.vera_dropout[active_adapter] + x = self._cast_input_dtype(x, lambda_d.dtype) + result = result + lambda_b * F.linear(lambda_d * F.linear(dropout(x), sliced_A), sliced_B) + result = result.to(orig_dtype) + + 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 "vera." + rep + + def extra_repr(self) -> str: + return quantization_extra_repr(self) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/vera/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/vera/model.py new file mode 100644 index 0000000000000000000000000000000000000000..d502a6465fc48d2691218f7a65aab34e5d2f26e4 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/vera/model.py @@ -0,0 +1,267 @@ +# 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 math +import warnings +from typing import Union + +import torch +from torch import nn +from torch.nn.init import _calculate_correct_fan +from transformers.pytorch_utils import Conv1D + +from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer, _get_in_out_features +from peft.utils import ( + TRANSFORMERS_MODELS_TO_VERA_TARGET_MODULES_MAPPING, + get_quantization_kwargs, + resolve_quantization_backend, +) + +from .._buffer_dict import BufferDict +from ..tuners_utils import _maybe_include_all_linear_layers +from .config import VeraConfig +from .layer import Linear, VeraLayer + + +def _get_tuner_layer_class(target_base_layer: torch.nn.Module) -> type[VeraLayer] | None: + layer_cls: type[VeraLayer] | None = None + if isinstance(target_base_layer, (torch.nn.Linear, Conv1D)): + layer_cls = Linear + elif (quant_backend := resolve_quantization_backend(target_base_layer)) is not None: + layer_cls = {"linear": Linear}.get(quant_backend.layer_type) + + return layer_cls + + +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) + else: + tensor = tensor_or_shape + fan = _calculate_correct_fan(tensor, "fan_in") + gain = math.sqrt(2) + std = gain / math.sqrt(fan) + bound = math.sqrt(3.0) * std + + with torch.no_grad(): + return tensor.uniform_(-bound, bound, generator=generator) + + +class VeraModel(BaseTuner): + """ + Creates Vector-based Random Matrix Adaptation (Vera) model from a pretrained transformers model. + + Args: + model ([`~transformers.PreTrainedModel`]): The model to be adapted. + config ([`VeraConfig`]): The configuration of the Vera 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 Vera model. + + Example: + + ```py + >>> from transformers import AutoModelForCausalLM + >>> from peft import VeraConfig, get_peft_model + + >>> base_model = AutoModelForCausalLM.from_pretrained("facebook/opt-125m") + >>> config = VeraConfig(r=128) + >>> model = get_peft_model(base_model, config) + ``` + + **Attributes**: + - **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted. + - **peft_config** ([`VeraConfig`]): The configuration of the Vera model. + """ + + prefix: str = "vera_lambda_" + tuner_layer_cls = VeraLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_VERA_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 VeRA. + + This will be used for determining the size of the shared vera_A and vera_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 _get_tuner_layer_class(module) is None: + continue + in_features, out_features = _get_in_out_features(module) + module_shape = (out_features, in_features) + + 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 VeRA were found. Please check `peft_config.target_modules`." + raise ValueError(msg) + + return largest_shape + + def _init_vera_A_vera_B(self, config: VeraConfig, adapter_name: str) -> None: + linear_out_dim, linear_in_dim = self._find_dim(config) + + # use of persistent to exclude vera_A and vera_B from the state dict if we choose not to save them. + self.vera_A = BufferDict({}, persistent=config.save_projection) + self.vera_B = BufferDict({}, persistent=config.save_projection) + + # deterministic init of vera_A and vera_B if we know the key + generator = torch.Generator(device="cpu").manual_seed(config.projection_prng_key) + vera_A = _kaiming_init((config.r, linear_in_dim), generator=generator) + vera_B = _kaiming_init((linear_out_dim, config.r), generator=generator) + + self.vera_A[adapter_name] = vera_A + self.vera_B[adapter_name] = vera_B + + def _pre_injection_hook(self, model: nn.Module, config: VeraConfig, adapter_name: str) -> None: + self._init_vera_A_vera_B(config, adapter_name) + + def _check_new_adapter_config(self, config: VeraConfig) -> 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"Vera 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( + "VeRA 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, + vera_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 = vera_config.r + bias = hasattr(target, "bias") and target.bias is not None + kwargs = { + "r": r, + "loaded_in_8bit": getattr(self.model, "is_loaded_in_8bit", False), + "loaded_in_4bit": getattr(self.model, "is_loaded_in_4bit", False), + "bias": bias, + } + kwargs.update(get_quantization_kwargs(self)) + + if isinstance(target, Linear): + target.update_layer( + adapter_name, + self.vera_A, + self.vera_B, + r, + config=vera_config, + ) + else: + new_module = self._create_new_module(vera_config, self.vera_A, self.vera_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(vera_config, vera_A, vera_B, adapter_name, target, **kwargs): + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + layer_cls = _get_tuner_layer_class(target_base_layer) + if layer_cls is None: + raise TypeError( + f"Target module {target} is not supported. Currently, only `torch.nn.Linear` (optionally quantized) " + "and `transformers.pytorch_utils.Conv1D` are supported." + ) + + if isinstance(target_base_layer, Conv1D): + kwargs["is_target_conv_1d_layer"] = True + if not vera_config.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." + ) + vera_config.fan_in_fan_out = True + elif vera_config.fan_in_fan_out: + # nn.Linear or a quantized linear layer + 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." + ) + vera_config.fan_in_fan_out = False + + new_module = layer_cls( + target, + vera_A, + vera_B, + adapter_name, + config=vera_config, + **kwargs, + ) + + return new_module diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/waveft/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/waveft/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f0e6fbc7e40eeccc393c662c09c81c032760dbfe --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/waveft/__init__.py @@ -0,0 +1,24 @@ +# 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 WaveFTConfig +from .layer import WaveFTLayer, WaveFTLinear +from .model import WaveFTModel + + +__all__ = ["WaveFTConfig", "WaveFTLayer", "WaveFTLinear", "WaveFTModel"] + +register_peft_method(name="waveft", model_cls=WaveFTModel, config_cls=WaveFTConfig) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/waveft/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/waveft/config.py new file mode 100644 index 0000000000000000000000000000000000000000..f2233c94e4ec583f52cb3cd4193e93de25f8ea3f --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/waveft/config.py @@ -0,0 +1,265 @@ +# 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 + +from .constants import WAVELET_REDUCTIONS + + +@dataclass +class WaveFTConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`WaveFTModel`]. It is used to define the + parameters for Wavelet-based Fine-Tuning (WaveFT), an approach that leverages the sparsity of wavelet transforms + for parameter-efficient fine-tuning of pretrained models. + + Args: + n_frequency (`int`): + Number of learnable wavelet coefficients for the Discrete Wavelet Transform (DWT). 'n_frequency' is an + integer that is greater than 0 and less than or equal to the total number of elements in the original + weight matrix (d_out * d_in). This parameter directly controls the number of trainable parameters for each + adapted layer. A higher 'n_frequency' generally leads to better performance but also increases GPU memory + usage, with a minor impact on training speed. + scaling (`float`): + The scaling factor applied to the reconstructed delta W matrix. This is a crucial hyperparameter, analogous + to `lora_alpha` in LoRA. It can be tuned during hyperparameter search. Our default value for SDXL + personalization is 25. + wavelet_family (`str`): + The wavelet family (e.g., 'db1', 'sym2', 'coif1') to use for the DWT and Inverse DWT (IDWT). Defaults to + 'db1' (Haar wavelet). Different wavelet families have varying filter lengths which affect the training time + substantially + use_idwt (`bool`): + Set to False for efficient adaptation. Whether to use the Inverse Discrete Wavelet Transform (IDWT) to + reconstruct the delta weights from the learned wavelet coefficients. If `True` (default), the IDWT is + applied. If `False`, the learned coefficients are directly used to form a sparse delta weight matrix, which + is faster but performs worse for the SDXL personalization task. + random_loc_seed (`int`): + Seed for determining the random locations of the `n_frequency` learnable wavelet coefficients within the + full wavelet coefficient matrix. + target_modules (`Union[list[str],str]`): + List of module names or a regex expression identifying the modules to be adapted with WaveFT. For example, + `['q_proj', 'v_proj']` or `'.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'`. Currently, only linear + layers (`torch.nn.Linear`) are supported. + exclude_modules (`Optional[Union[List[str], str]]`): + List of module names or a regex expression for modules to exclude from WaveFT adaptation. + fan_in_fan_out (`bool`): + Set to `True` if the weights of the layer to be replaced are stored in `(fan_in, fan_out)` format. Default + is `False`. + bias (`str`): + Bias type for WaveFT. Can be 'none', 'all', or 'waveft_only'. ('fourier_only' was likely a typo and has + been corrected to 'waveft_only' if it implies bias only on adapted parameters) If 'waveft_only', biases are + added only to the WaveFT components. If 'all', biases are added to both base and WaveFT components. If + 'none', no new biases are added. + modules_to_save (`list[str]`): + List of modules, in addition to WaveFT layers, that should be marked as trainable and saved in the final + checkpoint. Useful for layers like classifiers in sequence or token classification tasks that are randomly + initialized and need training. + layers_to_transform (`Union[list[int],int]`): + Specific layer indices to transform. If provided, PEFT will only adapt layers at these indices. If a single + integer is given, only that layer is transformed. + layers_pattern (`Optional[Union[List[str], str]]`): + Pattern for layer names, used if `layers_to_transform` is specified and the layer pattern is not standard + (e.g., not 'layers' or 'h'). This should target the `nn.ModuleList` attribute in the model. + n_frequency_pattern (`dict`): + A dictionary mapping layer names (or regex) to specific `n_frequency` values, overriding the global + `n_frequency`. Example: `{"model.decoder.layers.0.encoder_attn.k_proj": 1000}`. + init_weights (`bool`): + Initialization strategy for the learnable wavelet coefficients (spectrum). If `True` (default), + coefficients are initialized to zeros. If `False`, coefficients are initialized from a standard normal + distribution scaled by a small factor. + proportional_parameters (`bool`): + If `True`, `n_frequency` is allocated proportionally to each layer's `input_dim * output_dim`. Default is + `False`. Note: This option is included for experimental thoroughness to allow researchers to reproduce + paper results, rather than for practical utility, as no beneficial scenarios have been identified. + """ + + n_frequency: int = field( + default=2592, # Default value might need adjustment based on common use cases or paper findings + metadata={ + "help": ( + "Number of learnable wavelet coefficients for the Discrete Wavelet Transform (DWT). " + "'n_frequency' is an integer that is greater than 0 and less than or equal to the " + "total number of elements in the original weight matrix (d_out * d_in). " + "This parameter directly controls the number of trainable parameters for each adapted layer. " + "A higher 'n_frequency' generally leads to better performance but also increases " + "GPU memory usage, with a minor impact on training speed." + ) + }, + ) + scaling: float = field( + default=25.0, # Default value seems low based on typical examples, might need adjustment + metadata={ + "help": ( + "The scaling factor applied to the reconstructed delta W matrix. This is a crucial " + "hyperparameter, analogous to 'lora_alpha' in LoRA. It can be tuned during hyperparameter " + "search. Default value for SDXL personalization is 25. " + ) + }, + ) + wavelet_family: str = field( + default="db1", + metadata={ + "help": ( + "The wavelet family (e.g., 'db1', 'sym2', 'coif1') to use for the DWT and Inverse DWT (IDWT). " + "Defaults to 'db1' (Haar wavelet). Different wavelet families have varying filter lengths " + "which affect the training time substantially. Size differences are handled automatically " + "if use_idwt is True." + ) + }, + ) + use_idwt: bool = field( + default=True, + metadata={ + "help": ( + "Set to False for efficient adaptation. " + "Whether to use the Inverse Discrete Wavelet Transform (IDWT) to reconstruct the delta " + "weights from the learned wavelet coefficients. If True (default), the IDWT is applied. " + "If False, the learned coefficients are directly used to form a sparse delta weight matrix, " + "which is faster but performs worse for the SDXL personalization task." + ) + }, + ) + random_loc_seed: int = field( + default=777, + metadata={ + "help": ( + "Seed for determining the random locations of the 'n_frequency' learnable wavelet " + "coefficients within the full wavelet coefficient matrix." + ) + }, + ) + fan_in_fan_out: bool = field( + default=False, + metadata={ + "help": ( + "Set to True if the weights of the layer to be replaced are stored in (fan_in, fan_out) " + "format. Default is False." + ) + }, + ) + target_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": ( + "List of module names or a regex expression identifying the modules to be adapted with WaveFT. " + "For example, ['q_proj', 'v_proj'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'. " + "Currently, only linear layers (torch.nn.Linear) are supported." + ) + }, + ) + exclude_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={"help": "List of module names or regex for modules to exclude from WaveFT adaptation."}, + ) + bias: str = field( + default="none", + metadata={ + "help": ( + "Bias type for WaveFT. Can be 'none', 'all', or 'waveft_only'. " + "If 'waveft_only', biases are added only to the WaveFT components. " + "If 'all', biases are added to both base and WaveFT components. " + "If 'none', no new biases are added." + ) + }, + ) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": ( + "List of modules, in addition to WaveFT layers, that should be marked as trainable " + "and saved in the final checkpoint. Useful for layers like classifiers in sequence " + "or token classification tasks that are randomly initialized and need training." + ) + }, + ) + layers_to_transform: Optional[Union[list[int], int]] = field( + default=None, + metadata={ + "help": ( + "Specific layer indices to transform. If provided, PEFT will only adapt layers at these " + "indices. If a single integer is given, only that layer is transformed." + ) + }, + ) + layers_pattern: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": ( + "Pattern for layer names, used if `layers_to_transform` is specified and the layer " + "pattern is not standard (e.g., not 'layers' or 'h'). This should target the " + "`nn.ModuleList` attribute in the model." + ) + }, + ) + n_frequency_pattern: Optional[dict] = field( + default_factory=dict, + metadata={ + "help": ( + "A dictionary mapping layer names (or regex) to specific `n_frequency` values, " + 'overriding the global `n_frequency`. Example: {"model.decoder.layers.0.encoder_attn.k_proj": 1000}.' + ) + }, + ) + proportional_parameters: bool = field( + default=False, + metadata={ + "help": ( + "If True, 'n_frequency' is allocated proportionally to each layer's " + "input_dim * output_dim. Default is False. Note: This option is included " + "for experimental thoroughness to allow researchers to reproduce paper results, " + "rather than for practical utility, as no beneficial scenarios have been identified." + ) + }, + ) + init_weights: bool = field( + default=True, + metadata={ + "help": ( + "Initialization strategy for the learnable wavelet coefficients (spectrum). " + "If True (default), coefficients are initialized to zeros. " + "If False, coefficients are initialized from a standard normal distribution scaled by a small factor." + ) + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.WAVEFT + 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 + ) + # if target_modules is a regex expression, then layers_to_transform should be None + if isinstance(self.target_modules, str) and self.layers_to_transform is not None: + raise ValueError("`layers_to_transform` cannot be used when `target_modules` is a str.") + + # if target_modules is a regex expression, then layers_pattern should be None + if isinstance(self.target_modules, str) and self.layers_pattern is not None: + raise ValueError("`layers_pattern` cannot be used when `target_modules` is a str.") + # 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.wavelet_family not in WAVELET_REDUCTIONS: + raise ValueError( + f"Wavelet family {self.wavelet_family} not supported. Supported wavelet families are: {list(WAVELET_REDUCTIONS.keys())}" + ) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/waveft/constants.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/waveft/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..b1559f4fa5bb13039ab9687b643690d988513eb9 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/waveft/constants.py @@ -0,0 +1,96 @@ +# 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. +""" +Dimensional reduction amounts for different wavelet families during wavelet transforms Each tuple (rows, cols) +represents the reduction in matrix dimensions that occurs when applying wavelet decomposition/reconstruction due to +boundary effects and filter sizes. These values are used to pre-pad matrices before wavelet processing to ensure the +reconstructed matrix maintains the original target dimensions. +""" + +WAVELET_REDUCTIONS = { + "db1": (0, 0), + "db2": (2, 2), + "db3": (4, 4), + "db4": (6, 6), + "db5": (8, 8), + "db6": (10, 10), + "db7": (12, 12), + "db8": (14, 14), + "db9": (16, 16), + "db10": (18, 18), + "db11": (20, 20), + "db12": (22, 22), + "db13": (24, 24), + "db14": (26, 26), + "db15": (28, 28), + "db16": (30, 30), + "db17": (32, 32), + "db18": (34, 34), + "db19": (36, 36), + "db20": (38, 38), + "db21": (40, 40), + "db22": (42, 42), + "db23": (44, 44), + "db24": (46, 46), + "db25": (48, 48), + "db26": (50, 50), + "db27": (52, 52), + "db28": (54, 54), + "db29": (56, 56), + "db30": (58, 58), + "db31": (60, 60), + "db32": (62, 62), + "db33": (64, 64), + "db34": (66, 66), + "db35": (68, 68), + "db36": (70, 70), + "db37": (72, 72), + "db38": (74, 74), + "sym2": (2, 2), + "sym3": (4, 4), + "sym4": (6, 6), + "sym5": (8, 8), + "sym6": (10, 10), + "sym7": (12, 12), + "sym8": (14, 14), + "sym9": (16, 16), + "sym10": (18, 18), + "sym11": (20, 20), + "sym12": (22, 22), + "sym13": (24, 24), + "sym14": (26, 26), + "sym15": (28, 28), + "sym16": (30, 30), + "sym17": (32, 32), + "sym18": (34, 34), + "sym19": (36, 36), + "sym20": (38, 38), + "coif1": (4, 4), + "coif2": (10, 10), + "coif3": (16, 16), + "coif4": (22, 22), + "coif5": (28, 28), + "coif6": (34, 34), + "coif7": (40, 40), + "coif8": (46, 46), + "coif9": (52, 52), + "coif10": (58, 58), + "coif11": (64, 64), + "coif12": (70, 70), + "coif13": (76, 76), + "coif14": (82, 82), + "coif15": (88, 88), + "coif16": (94, 94), + "coif17": (100, 100), +} diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/waveft/layer.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/waveft/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..49ac752754e2f4498031fc37853fb6304b6ed674 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/waveft/layer.py @@ -0,0 +1,298 @@ +# 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 Any, Optional + +import torch +import torch.nn.functional as F +from torch import nn +from transformers.pytorch_utils import Conv1D + +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge +from peft.utils.other import transpose + +from .config import WaveFTConfig +from .constants import WAVELET_REDUCTIONS +from .waverec2d import waverec2d + + +class WaveFTLayer(BaseTunerLayer): + # All names of layers that may contain (trainable) adapter weights + adapter_layer_names = ("waveft_spectrum",) + # All names of other parameters that may contain adapter-related parameters + other_param_names = ( + "waveft_n_frequency", + "waveft_scaling", + "waveft_random_loc_seed", + "waveft_wavelet_family", + "waveft_indices", + "waveft_use_idwt", + ) + + def __init__(self, base_layer: nn.Module, **kwargs) -> None: + self.base_layer = base_layer + self.waveft_n_frequency = {} + self.waveft_scaling = {} + self.waveft_spectrum = nn.ParameterDict({}) + self.waveft_wavelet_family = {} + self.waveft_indices = {} + self.waveft_random_loc_seed = {} + self.waveft_use_idwt = {} + # Mark the weight as unmerged + self._disable_adapters = False + self.merged_adapters = [] + self.kwargs = kwargs + + base_layer = self.get_base_layer() + if isinstance(base_layer, nn.Linear): + self.in_features, self.out_features = base_layer.in_features, base_layer.out_features + elif isinstance(base_layer, Conv1D): + self.in_features, self.out_features = ( + base_layer.weight.ds_shape if hasattr(base_layer.weight, "ds_shape") else base_layer.weight.shape + ) + else: + raise TypeError(f"Unsupported layer type {type(base_layer)}") + + def update_layer( + self, + adapter_name: str, + n_frequency: int, + config: WaveFTConfig, + ): + wavelet_family = config.wavelet_family + scaling = config.scaling + init_weights = config.init_weights + random_loc_seed = config.random_loc_seed + use_idwt = config.use_idwt + + if n_frequency <= 0: + raise ValueError(f"`n_frequency` should be a positive integer value but the value passed is {n_frequency}") + if n_frequency > self.in_features * self.out_features: + raise ValueError( + f"`n_frequency` should be less than or equal to the product of the input and output dimensions " + f"but the value passed is {n_frequency} and the product is {self.in_features * self.out_features}" + ) + + self.waveft_n_frequency[adapter_name] = n_frequency + self.waveft_random_loc_seed[adapter_name] = random_loc_seed + self.waveft_wavelet_family[adapter_name] = wavelet_family + self.waveft_use_idwt[adapter_name] = use_idwt + + # Generate random indices within the original dimensions + # We handle padding separately in get_delta_weight + generator = torch.Generator().manual_seed(self.waveft_random_loc_seed[adapter_name]) + indices = torch.randperm(self.out_features * self.in_features, generator=generator)[:n_frequency] + + # Convert to row, col format for the original dimensions + self.waveft_indices[adapter_name] = torch.stack( + [indices // self.in_features, indices % self.in_features], dim=0 + ) + + self.waveft_scaling[adapter_name] = scaling + + # Actual trainable parameters + # Initialize based on init_weights + if init_weights: + # Initialize with zeros later using reset_wave_parameters + self.waveft_spectrum[adapter_name] = nn.Parameter(torch.empty(n_frequency), requires_grad=True) + self.reset_wave_parameters(adapter_name) # Initialize to zeros now + else: + # Initialize with randn scaled by a small std dev to prevent explosion + std_dev = 0.01 # Using a small std dev for initial random weights + self.waveft_spectrum[adapter_name] = nn.Parameter(torch.randn(n_frequency) * std_dev, requires_grad=True) + + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=config.inference_mode) + + @torch.no_grad() + def reset_wave_parameters(self, adapter_name): + if adapter_name in self.waveft_spectrum.keys(): + nn.init.zeros_(self.waveft_spectrum[adapter_name]) + + def get_delta_weight(self, adapter) -> torch.Tensor: + spectrum = self.waveft_spectrum[adapter] + indices = self.waveft_indices[adapter].to(spectrum.device) + wavelet_family = self.waveft_wavelet_family[adapter] + + # Choose whether to use IDWT or direct spectrum based on adapter setting + if self.waveft_use_idwt[adapter]: + reduction_rows, reduction_cols = WAVELET_REDUCTIONS[wavelet_family] + + # Create a padded spectrum matrix with additional rows and columns + # to account for the reduction during wavelet reconstruction + padded_out_features = self.out_features + reduction_rows + padded_in_features = self.in_features + reduction_cols + + # Make dimensions even if needed for wavelet processing + if padded_out_features % 2 != 0: + padded_out_features += 1 + if padded_in_features % 2 != 0: + padded_in_features += 1 + + # Create the padded dense spectrum matrix + dense_spectrum = torch.zeros( + padded_out_features, padded_in_features, device=spectrum.device, dtype=spectrum.dtype + ) + + # Calculate padding offsets to center the original data in the padded matrix + row_offset = (padded_out_features - self.out_features) // 2 + col_offset = (padded_in_features - self.in_features) // 2 + + # Adjust indices to account for padding offsets + padded_indices = indices.clone() + padded_indices[0, :] += row_offset + padded_indices[1, :] += col_offset + + # Place spectrum values in the padded matrix + # Filter out any indices that would be out of bounds + valid_mask = (padded_indices[0, :] < padded_out_features) & (padded_indices[1, :] < padded_in_features) + valid_indices = padded_indices[:, valid_mask] + valid_spectrum = spectrum[valid_mask] + + # Set the spectrum values in the padded matrix + dense_spectrum[valid_indices[0, :], valid_indices[1, :]] = valid_spectrum + + # Split into four sub-bands + H, W = dense_spectrum.shape + H2, W2 = H // 2, W // 2 + cA = dense_spectrum[:H2, :W2] # top-left + cH = dense_spectrum[:H2, W2:] # top-right + cV = dense_spectrum[H2:, :W2] # bottom-left + cD = dense_spectrum[H2:, W2:] # bottom-right + + # Construct wavelet-coefficient tuple + coeffs = (cA, (cH, cV, cD)) + + # Reconstruct with the specified wavelet family + delta_weight = waverec2d(coeffs, wavelet_family) * self.waveft_scaling[adapter] + + # Ensure the delta weight has exactly the correct dimensions + if delta_weight.shape[0] != self.out_features or delta_weight.shape[1] != self.in_features: + # Calculate where to start slicing to get a centered crop + start_row = (delta_weight.shape[0] - self.out_features) // 2 + start_col = (delta_weight.shape[1] - self.in_features) // 2 + + # Slice to the exact output size needed + delta_weight = delta_weight[ + start_row : start_row + self.out_features, start_col : start_col + self.in_features + ] + else: + # Simple direct use of spectrum without IDWT + dense_spectrum = torch.zeros( + self.out_features, self.in_features, device=spectrum.device, dtype=spectrum.dtype + ) + dense_spectrum[indices[0, :], indices[1, :]] = spectrum + delta_weight = dense_spectrum * self.waveft_scaling[adapter] + + return delta_weight + + +class WaveFTLinear(nn.Module, WaveFTLayer): + # WaveFT implemented in a dense layer + def __init__( + self, + base_layer, + adapter_name: str, + config: WaveFTConfig, + n_frequency: int = 1000, + **kwargs, + ) -> None: + super().__init__() + WaveFTLayer.__init__(self, base_layer, **kwargs) + self.fan_in_fan_out = config.fan_in_fan_out + self._active_adapter = adapter_name + self.update_layer(adapter_name, n_frequency, config=config) + + 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.waveft_spectrum.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 += transpose(self.get_delta_weight(active_adapter), self.fan_in_fan_out) + + 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 += transpose(self.get_delta_weight(active_adapter), self.fan_in_fan_out) + 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 in self.waveft_spectrum.keys(): + self.get_base_layer().weight.data -= transpose( + self.get_delta_weight(active_adapter), self.fan_in_fan_out + ) + + 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: + result = self.base_layer(x, *args, **kwargs) + for active_adapter in self.active_adapters: + if active_adapter not in self.waveft_spectrum.keys(): + continue + + delta_w = self.get_delta_weight(active_adapter) + x = self._cast_input_dtype(x, delta_w.dtype) + result = result + F.linear(x, delta_w) + + result = result.to(previous_dtype) + return result + + def supports_lora_conversion(self, adapter_name: str = "default") -> bool: + # get_delta_weight does not transpose Conv1D because it is used in forward, therefore, it has the wrong + # shape for conversion + return not isinstance(self.get_base_layer(), Conv1D) + + def __repr__(self) -> str: + rep = super().__repr__() + return "waveft." + rep diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/waveft/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/waveft/model.py new file mode 100644 index 0000000000000000000000000000000000000000..f1d325c8e520feabffdb27eaf0ecce83cb8d6049 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/waveft/model.py @@ -0,0 +1,175 @@ +# 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 transformers.pytorch_utils import Conv1D + +from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer, check_target_module_exists +from peft.utils import ( + TRANSFORMERS_MODELS_TO_WAVEFT_TARGET_MODULES_MAPPING, +) +from peft.utils.other import get_pattern_key + +from .layer import WaveFTLayer, WaveFTLinear + + +class WaveFTModel(BaseTuner): + prefix: str = "waveft_" + tuner_layer_cls: type[BaseTunerLayer] = WaveFTLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_WAVEFT_TARGET_MODULES_MAPPING + + def _calculate_proportional_parameters(self, model: torch.nn.Module, waveft_config): + """Calculate proportional parameter allocation for all target modules.""" + target_modules_info = [] + for name, module in model.named_modules(): + if check_target_module_exists(waveft_config, name): + # Handle case where module is already wrapped with WaveFT + if isinstance(module, WaveFTLayer): + # Use the base layer for dimension calculations + base_module = module.base_layer + if isinstance(base_module, torch.nn.Linear): + input_dim, output_dim = base_module.in_features, base_module.out_features + elif isinstance(base_module, Conv1D): + input_dim, output_dim = base_module.weight.shape[1], base_module.weight.shape[0] + else: + continue + elif isinstance(module, torch.nn.Linear): + input_dim, output_dim = module.in_features, module.out_features + elif isinstance(module, Conv1D): + input_dim, output_dim = module.weight.shape[1], module.weight.shape[0] + else: + continue + target_modules_info.append((name, input_dim, output_dim)) + + if not target_modules_info: + raise ValueError("No target modules found for proportional parameter allocation.") + + total_sum = sum(input_dim * output_dim for (_, input_dim, output_dim) in target_modules_info) + num_layers = len(target_modules_info) + total_budget = waveft_config.n_frequency * num_layers + + n_frequency_dict = {} + for name, input_dim, output_dim in target_modules_info: + layer_ratio = (input_dim * output_dim) / total_sum + n_freq = round(layer_ratio * total_budget) + n_frequency_dict[name] = n_freq + + return n_frequency_dict + + def _create_and_replace( + self, + waveft_config, + adapter_name, + target, + target_name, + parent, + current_key, + **optional_kwargs, + ): + if current_key is None: + raise ValueError("Current Key shouldn't be `None`") + + # Calculate proportional parameters if needed (only once per adapter) + if waveft_config.proportional_parameters: + if not hasattr(self, "_proportional_params_cache"): + self._proportional_params_cache = {} + if adapter_name not in self._proportional_params_cache: + n_frequency_dict = self._calculate_proportional_parameters(self.model, waveft_config) + self._proportional_params_cache[adapter_name] = n_frequency_dict + + # Determine n_frequency: Priority order: + # 1. From proportional parameter cache (if proportional_parameters=True) + # 2. From optional_kwargs (if passed directly) + # 3. From n_frequency_pattern in config + # 4. From default n_frequency in config + n_frequency = None + if ( + waveft_config.proportional_parameters + and hasattr(self, "_proportional_params_cache") + and adapter_name in self._proportional_params_cache + ): + n_frequency = self._proportional_params_cache[adapter_name].get(current_key) + + if n_frequency is None and "n_frequency" in optional_kwargs: + n_frequency = optional_kwargs["n_frequency"] + + if n_frequency is None: + pattern_keys = list(waveft_config.n_frequency_pattern.keys()) + target_name_key = get_pattern_key(pattern_keys, current_key) + n_frequency = waveft_config.n_frequency_pattern.get(target_name_key, waveft_config.n_frequency) + + bias = hasattr(target, "bias") and target.bias is not None + # Prepare kwargs for module creation/update + kwargs = { + "n_frequency": n_frequency, + "bias": bias, + } + + if isinstance(target, WaveFTLayer): + target.update_layer( + adapter_name, + n_frequency, + config=waveft_config, + ) + else: + new_module = self._create_new_module(waveft_config, adapter_name, target, **kwargs) + if adapter_name != self.active_adapter: + new_module.requires_grad_(False) + self._replace_module(parent, target_name, new_module, target) + + @staticmethod + def _create_new_module(waveft_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): + if waveft_config.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." + ) + waveft_config.fan_in_fan_out = False + elif isinstance(target_base_layer, Conv1D): + kwargs["is_target_conv_1d_layer"] = True + if not waveft_config.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." + ) + waveft_config.fan_in_fan_out = True + else: + raise TypeError( + f"Target module {target} is not supported. Currently, only the following modules are supported: " + "`torch.nn.Linear`." + ) + + new_module = WaveFTLinear(target, adapter_name, config=waveft_config, **kwargs) + + return new_module + + def delete_adapter(self, adapter_name: str) -> None: + """ + Deletes an existing adapter. + + Args: + adapter_name (str): Name of the adapter to be deleted. + """ + super().delete_adapter(adapter_name) + # Clean up proportional parameters cache + if hasattr(self, "_proportional_params_cache") and adapter_name in self._proportional_params_cache: + del self._proportional_params_cache[adapter_name] diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/waveft/wavelet.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/waveft/wavelet.py new file mode 100644 index 0000000000000000000000000000000000000000..c66acd85f65570652f18d47d5bed12eb3a174ea5 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/waveft/wavelet.py @@ -0,0 +1,513 @@ +# 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. + +""" +Minimal wavelet implementation extracted from PyWavelets + +This code contains portions derived from PyWavelets: Copyright (c) 2006-2012 Filip Wasilewski +Copyright (c) 2012- The PyWavelets Developers + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the +Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Original source: https://github.com/PyWavelets/pywt +""" + +import math +from collections.abc import Sequence + + +class Wavelet: + """ + Minimal wavelet class that implements the most commonly used wavelets. + + Supports: + - Daubechies wavelets: db1-db10, haar + - Symlets: sym2-sym10 + - Coiflets: coif1-coif5 + """ + + def __init__(self, name: str): + """ + Initialize a wavelet by name. + + Args: + name: Wavelet name (e.g., 'db4', 'haar', 'sym5', 'coif2') + """ + self.name = name.lower() + self._compute_filters() + + def _compute_filters(self): + """Compute the four filter banks from the base coefficients.""" + if self.name == "haar": + # Haar is the same as db1 + base_coeffs = _WAVELET_COEFFS["db1"] + elif self.name in _WAVELET_COEFFS: + base_coeffs = _WAVELET_COEFFS[self.name] + else: + raise ValueError(f"Unknown wavelet name '{self.name}'. Available wavelets: {list(_WAVELET_COEFFS.keys())}") + + # Determine if this is a coiflet (needs sqrt(2) scaling) + scale_factor = math.sqrt(2) if self.name.startswith("coif") else 1.0 + + # Apply scaling to base coefficients + scaled_coeffs = [c * scale_factor for c in base_coeffs] + + # Compute the four filter banks following PyWavelets convention + # rec_lo = scaled base coefficients + self._rec_lo = scaled_coeffs[:] + + # dec_lo = rec_lo reversed + self._dec_lo = scaled_coeffs[::-1] + + # rec_hi = alternating signs of dec_lo + self._rec_hi = [(-1) ** i * scaled_coeffs[len(scaled_coeffs) - 1 - i] for i in range(len(scaled_coeffs))] + + # dec_hi = alternating signs of rec_lo + self._dec_hi = [(-1) ** (len(scaled_coeffs) - 1 - i) * scaled_coeffs[i] for i in range(len(scaled_coeffs))] + + @property + def dec_lo(self) -> Sequence[float]: + """Lowpass decomposition filter.""" + return self._dec_lo + + @property + def dec_hi(self) -> Sequence[float]: + """Highpass decomposition filter.""" + return self._dec_hi + + @property + def rec_lo(self) -> Sequence[float]: + """Lowpass reconstruction filter.""" + return self._rec_lo + + @property + def rec_hi(self) -> Sequence[float]: + """Highpass reconstruction filter.""" + return self._rec_hi + + @property + def dec_len(self) -> int: + """Decomposition filters length.""" + return len(self._dec_lo) + + @property + def rec_len(self) -> int: + """Reconstruction filters length.""" + return len(self._rec_lo) + + @property + def filter_bank(self) -> tuple[Sequence[float], Sequence[float], Sequence[float], Sequence[float]]: + """Tuple of all four filter banks (dec_lo, dec_hi, rec_lo, rec_hi).""" + return (self.dec_lo, self.dec_hi, self.rec_lo, self.rec_hi) + + def __len__(self) -> int: + """Return the length of the decomposition filters.""" + return self.dec_len + + def __repr__(self) -> str: + return f"Wavelet(name='{self.name}')" + + +# Wavelet coefficients extracted from PyWavelets +# These are the reconstruction lowpass filter coefficients +_WAVELET_COEFFS = { + # Daubechies wavelets + "db1": [ + 0.7071067811865475244008443621048490392848359376884740365883398, + 0.7071067811865475244008443621048490392848359376884740365883398, + ], + "db2": [ + 0.4829629131445341433748715998644486838169524195042022752011715, + 0.8365163037378079055752937809168732034593703883484392934953414, + 0.2241438680420133810259727622404003554678835181842717613871683, + -0.1294095225512603811744494188120241641745344506599652569070016, + ], + "db3": [ + 0.3326705529500826159985115891390056300129233992450683597084705, + 0.80689150931333875, + 0.45987750211933132, + -0.13501102001039084, + -0.085441273882241486, + 0.035226291882100656, + ], + "db4": [ + 0.2303778133088965008632911830440708500016152482483092977910968, + 0.7148465705529156470899219552739926037076084010993081758450110, + 0.6308807679298589078817163383006152202032229226771951174057473, + -0.02798376941685985421141374718007538541198732022449175284003358, + -0.1870348117190930840795706727890814195845441743745800912057770, + 0.03084138183556076362721936253495905017031482172003403341821219, + 0.03288301166688519973540751354924438866454194113754971259727278, + -0.01059740178506903210488320852402722918109996490637641983484974, + ], + "db5": [ + 0.1601023979741929144807237480204207336505441246250578327725699, + 0.6038292697971896705401193065250621075074221631016986987969283, + 0.7243085284377729277280712441022186407687562182320073725767335, + 0.1384281459013207315053971463390246973141057911739561022694652, + -0.2422948870663820318625713794746163619914908080626185983913726, + -0.03224486958463837464847975506213492831356498416379847225434268, + 0.07757149384004571352313048938860181980623099452012527983210146, + -0.006241490212798274274190519112920192970763557165687607323417435, + -0.01258075199908199946850973993177579294920459162609785020169232, + 0.003335725285473771277998183415817355747636524742305315099706428, + ], + "db6": [ + 0.1115407433501094636213239172409234390425395919844216759082360, + 0.4946238903984530856772041768778555886377863828962743623531834, + 0.7511339080210953506789344984397316855802547833382612009730420, + 0.3152503517091976290859896548109263966495199235172945244404163, + -0.2262646939654398200763145006609034656705401539728969940143487, + -0.1297668675672619355622896058765854608452337492235814701599310, + 0.09750160558732304910234355253812534233983074749525514279893193, + 0.02752286553030572862554083950419321365738758783043454321494202, + -0.03158203931748602956507908069984866905747953237314842337511464, + 0.0005538422011614961392519183980465012206110262773864964295476524, + 0.004777257510945510639635975246820707050230501216581434297593254, + -0.001077301085308479564852621609587200035235233609334419689818580, + ], + "db7": [ + 0.07785205408500917901996352195789374837918305292795568438702937, + 0.3965393194819173065390003909368428563587151149333287401110499, + 0.7291320908462351199169430703392820517179660611901363782697715, + 0.4697822874051931224715911609744517386817913056787359532392529, + -0.1439060039285649754050683622130460017952735705499084834401753, + -0.2240361849938749826381404202332509644757830896773246552665095, + 0.07130921926683026475087657050112904822711327451412314659575113, + 0.08061260915108307191292248035938190585823820965629489058139218, + -0.03802993693501441357959206160185803585446196938467869898283122, + -0.01657454163066688065410767489170265479204504394820713705239272, + 0.01255099855609984061298988603418777957289474046048710038411818, + 0.0004295779729213665211321291228197322228235350396942409742946366, + -0.001801640704047490915268262912739550962585651469641090625323864, + 0.0003537137999745202484462958363064254310959060059520040012524275, + ], + "db8": [ + 0.05441584224310400995500940520299935503599554294733050397729280, + 0.3128715909142999706591623755057177219497319740370229185698712, + 0.6756307362972898068078007670471831499869115906336364227766759, + 0.5853546836542067127712655200450981944303266678053369055707175, + -0.01582910525634930566738054787646630415774471154502826559735335, + -0.2840155429615469265162031323741647324684350124871451793599204, + 0.0004724845739132827703605900098258949861948011288770074644084096, + 0.1287474266204784588570292875097083843022601575556488795577000, + -0.01736930100180754616961614886809598311413086529488394316977315, + -0.04408825393079475150676372323896350189751839190110996472750391, + 0.01398102791739828164872293057263345144239559532934347169146368, + 0.008746094047405776716382743246475640180402147081140676742686747, + -0.004870352993451574310422181557109824016634978512157003764736208, + -0.0003917403733769470462980803573237762675229350073890493724492694, + 0.0006754494064505693663695475738792991218489630013558432103617077, + -0.0001174767841247695337306282316988909444086693950311503927620013, + ], + "db9": [ + 0.03807794736387834658869765887955118448771714496278417476647192, + 0.2438346746125903537320415816492844155263611085609231361429088, + 0.6048231236901111119030768674342361708959562711896117565333713, + 0.6572880780513005380782126390451732140305858669245918854436034, + 0.1331973858250075761909549458997955536921780768433661136154346, + -0.2932737832791749088064031952421987310438961628589906825725112, + -0.09684078322297646051350813353769660224825458104599099679471267, + 0.1485407493381063801350727175060423024791258577280603060771649, + 0.03072568147933337921231740072037882714105805024670744781503060, + -0.06763282906132997367564227482971901592578790871353739900748331, + 0.0002509471148314519575871897499885543315176271993709633321834164, + 0.02236166212367909720537378270269095241855646688308853754721816, + -0.004723204757751397277925707848242465405729514912627938018758526, + -0.004281503682463429834496795002314531876481181811463288374860455, + 0.001847646883056226476619129491125677051121081359600318160732515, + 0.0002303857635231959672052163928245421692940662052463711972260006, + -0.0002519631889427101369749886842878606607282181543478028214134265, + 0.00003934732031627159948068988306589150707782477055517013507359938, + ], + "db10": [ + 0.02667005790055555358661744877130858277192498290851289932779975, + 0.1881768000776914890208929736790939942702546758640393484348595, + 0.5272011889317255864817448279595081924981402680840223445318549, + 0.6884590394536035657418717825492358539771364042407339537279681, + 0.2811723436605774607487269984455892876243888859026150413831543, + -0.2498464243273153794161018979207791000564669737132073715013121, + -0.1959462743773770435042992543190981318766776476382778474396781, + 0.1273693403357932600826772332014009770786177480422245995563097, + 0.09305736460357235116035228983545273226942917998946925868063974, + -0.07139414716639708714533609307605064767292611983702150917523756, + -0.02945753682187581285828323760141839199388200516064948779769654, + 0.03321267405934100173976365318215912897978337413267096043323351, + 0.003606553566956169655423291417133403299517350518618994762730612, + -0.01073317548333057504431811410651364448111548781143923213370333, + 0.001395351747052901165789318447957707567660542855688552426721117, + 0.001992405295185056117158742242640643211762555365514105280067936, + -0.0006858566949597116265613709819265714196625043336786920516211903, + -0.0001164668551292854509514809710258991891527461854347597362819235, + 0.00009358867032006959133405013034222854399688456215297276443521873, + -0.00001326420289452124481243667531226683305749240960605829756400674, + ], + # Symlets + "sym2": [0.48296291314469025, 0.83651630373746899, 0.22414386804185735, -0.12940952255092145], + "sym3": [ + 0.33267055295095688, + 0.80689150931333875, + 0.45987750211933132, + -0.13501102001039084, + -0.085441273882241486, + 0.035226291882100656, + ], + "sym4": [ + 0.032223100604042702, + -0.012603967262037833, + -0.099219543576847216, + 0.29785779560527736, + 0.80373875180591614, + 0.49761866763201545, + -0.02963552764599851, + -0.075765714789273325, + ], + "sym5": [ + 0.019538882735286728, + -0.021101834024758855, + -0.17532808990845047, + 0.016602105764522319, + 0.63397896345821192, + 0.72340769040242059, + 0.1993975339773936, + -0.039134249302383094, + 0.029519490925774643, + 0.027333068345077982, + ], + "sym6": [ + -0.007800708325034148, + 0.0017677118642428036, + 0.044724901770665779, + -0.021060292512300564, + -0.072637522786462516, + 0.3379294217276218, + 0.787641141030194, + 0.49105594192674662, + -0.048311742585632998, + -0.11799011114819057, + 0.0034907120842174702, + 0.015404109327027373, + ], + "sym7": [ + 0.010268176708511255, + 0.0040102448715336634, + -0.10780823770381774, + -0.14004724044296152, + 0.28862963175151463, + 0.76776431700316405, + 0.5361019170917628, + 0.017441255086855827, + -0.049552834937127255, + 0.067892693501372697, + 0.03051551316596357, + -0.01263630340325193, + -0.0010473848886829163, + 0.0026818145682578781, + ], + "sym8": [ + 0.0018899503327594609, + -0.0003029205147213668, + -0.014952258337048231, + 0.0038087520138906151, + 0.049137179673607506, + -0.027219029917056003, + -0.051945838107709037, + 0.3644418948353314, + 0.77718575170052351, + 0.48135965125837221, + -0.061273359067658524, + -0.14329423835080971, + 0.0076074873249176054, + 0.031695087811492981, + -0.00054213233179114812, + -0.0033824159510061256, + ], + "sym9": [ + 0.0010694900329086053, + -0.00047315449868008311, + -0.010264064027633142, + 0.0088592674934004842, + 0.06207778930288603, + -0.018233770779395985, + -0.19155083129728512, + 0.035272488035271894, + 0.61733844914093583, + 0.717897082764412, + 0.238760914607303, + -0.054568958430834071, + 0.00058346274612580684, + 0.03022487885827568, + -0.01152821020767923, + -0.013271967781817119, + 0.00061978088898558676, + 0.0014009155259146807, + ], + "sym10": [ + -0.00045932942100465878, + 0.000057036083618494284, + 0.0045931735853118284, + -0.00080435893201654491, + -0.02035493981231129, + 0.0057649120335819086, + 0.049994972077376687, + -0.0319900568824278, + -0.035536740473817552, + 0.38382676106708546, + 0.7695100370211071, + 0.47169066693843925, + -0.070880535783243853, + -0.15949427888491757, + 0.011609893903711381, + 0.045927239231092203, + -0.0014653825813050513, + -0.0086412992770224222, + 0.000095632670722894754, + 0.00077015980911449011, + ], + # Coiflets (note: these will be multiplied by sqrt(2) in the class) + "coif1": [ + -0.05142972847076845595317549230122688830344559947132656813651045, + 0.2389297284707684559531754923012268883034455994713265681365104, + 0.6028594569415369119063509846024537766068911989426531362730209, + 0.2721405430584630880936490153975462233931088010573468637269790, + -0.05142972847076845595317549230122688830344559947132656813651045, + -0.01107027152923154404682450769877311169655440052867343186348954, + ], + "coif2": [ + 0.01158759673871686817889714882853120395708315073355502818875931, + -0.02932013798346856448679594524397843054053420947418409889774786, + -0.04763959031100813225872995081511549408622753909592460525840745, + 0.2730210465347666137982239328923516270034828327990699588033501, + 0.5746823938568638472459483149751499367740786490481481391460366, + 0.2948671936956191896750637208703777973914107635455611537640778, + -0.05408560709171142997443672832006888537570221990444706777525838, + -0.04202648046077160694657530752545884878978719268926222513485613, + 0.01674441016327950635146257083249391698866289538037299820224006, + 0.003967883612962012109043447090269950094081810916481648252817197, + -0.001289203356140659543141355500990678257894936161704492503370186, + -0.0005095053991076441489598480835620951586540050976664367876412655, + ], + "coif3": [ + -0.002682418670922068664584689955153722375535836177157637134187840, + 0.005503126707831385107969640263617469178794666057252906037981936, + 0.01658356047917034608134280439996549525220639437145367606178002, + -0.04650776447872697640390293095170192691113917841041002855534619, + -0.04322076356021191118175840907244577856782537221435748296465882, + 0.2865033352736474630249006862976158896891076238443844211133873, + 0.5612852568703300445990941995240077241406247774064453800050914, + 0.3029835717728241602862575774374668529867757043461413348549577, + -0.05077014075488886159516471867138370972545857441670871832472707, + -0.05819625076158553022607041679522801089624825903982541419721721, + 0.02443409432116695639462954438418928805487699080947974989338820, + 0.01122924096203786563399489540091488781245346096838814728167341, + -0.006369601011048822977293753932627342482077585617391852852955559, + -0.001820458915566242322836631665832145136570132777862391313328351, + 0.0007902051009575939937150950543290226440287715441826917281929124, + 0.0003296651737931830308416338897758022998655744276957481989605186, + -0.00005019277455327664998007173088097694083956570594580641192332170, + -0.00002446573425530813115445387662881902303945941576472342106918209, + ], + "coif4": [ + 0.0006309612114309468490753696608619526520153127603444406835368201, + -0.001152225143769973488683007937016166047881572156705066038094891, + -0.005194525163470323267558201363327294331811309729430512113592118, + 0.011360930899781950641704454327495718441159520023894304805142070, + 0.018945061045616642675204041814669158097013442370604397885045773, + -0.051719843705815280952009072709014825996085808127950893370164031, + -0.034486140470944806827159094088779177962124655341862998060866093, + 0.30227251053656843537076103037201073987915654650542997843779746, + 0.55454790624088107896085831311334062609863843227892842936901802, + 0.30791766802517503548651698686002846493302655084140026096325632, + -0.04352500928126570063143077306027663648139777048547894956715080, + -0.06488795097143100103160862688937301504802507374726020928892066, + 0.01988077364815951966984001670075537628468542316950829728327598, + 0.01763894787126169746077061344050946967036166456074020965866088, + -0.007366054847173363935072651649653007115003169492027095040477055, + -0.002312432307658842282830374733100847689924654369899030169556169, + 0.0014260063442333715226509754100697734398974715092509045804651032, + 0.0004666984635537353670445650012678936080062341977092967649055398, + -0.0001270007842387334077388950072420113055088253899932456267893098, + -0.0001130536369789104919020013936507623832962772709844179610938550, + 0.00003048364879677801030096883509693508426509710688913073244616617, + 0.00001266744808933008194725929652978169473830765616675686100903086, + -0.000001584926580756893754069651095690142946796090146306140001598, + -0.000001123948088281542889088159169056968300680087779667334879506, + ], + "coif5": [ + -0.0001444992186438190986841213894961515720877049723502928655308158, + 0.0002541649492011946935899015644804259825374993423205648946709984, + 0.0015016192805175522217354963668928299350735326077949346507003370, + -0.0029411108712655515426850089360913424188662278991737055486839309, + -0.0071777671514877191801104649507158618871157411936681659380839993, + 0.016680426640070654149267486742006854522334094142598667043628439, + 0.019433238433489604119639447772308536988043628308900006988094899, + -0.064934946567212502582522008002547701764467194128935170823607736, + -0.036249793089132571825087765037251085892962369926089901862924065, + 0.29804266217809436069693444260411251439893892734398765007426945, + 0.55749162970920071628061190166750547398568080072951806509736879, + 0.30731644529206781686031633026138686170779831068030092889493625, + -0.047088034719761145117688715152051398948700623993077406913889346, + -0.068890522508050074805015336128652797797076949077503388892816063, + 0.020697343297747766068568936830651656003659188170019885439659031, + 0.021640668655956855043817421090949779825140639715020046717736369, + -0.0081089373078953680936950024508066654697766705721301481097854397, + -0.0049881737671041853808073796089816945023009226058734090095808033, + 0.0024486914321021269742893936892468103370072825113159100554056433, + 0.0014095103899593442621166984842002926701899968616244946547893994, + -0.0005637801876093825733169550088901318936072015721509885859509815, + -0.0002859004477225750899655442618734663056802618537327806113618985, + 0.00012739637513815208006169426577159456832051015616166327985688948, + 0.00005416263410701044073894700796327336007788688985721449717765655, + -0.00001736867944346280636144226913926838103159698473080996002509476, + -0.00001392656190060010871169838885327726938969652863554900825705905, + 0.000003582065515946048838215026334503092089635988710863959063568069, + 0.000001914022895847318655772885654240700542388103264097264264779554, + -0.00000031262488377016899432194683906058825900951892071223097080609, + -0.00000034030635502511647536690616071863203084936306302829968850306, + 0.000000059816065238516936893488966688516710847096926983547983503726, + 0.000000047001427849456491830476615736016736014244615701046223529866, + -0.000000006158615709678364180659098549671046676203853020063205641804, + -0.000000009225635096344935080070901936862847863830913641424076095562, + 0.000000001028486074518821265015830073593127726988903862842106883701, + 0.000000001168734175186263778695686067593866982925127816327529890618, + -0.00000000009468626176069127302554946536142654377756003084491946024, + -0.00000000016230233142152041788509334089966065953985768924968863072, + 0.000000000015076656859346950325398899897135970089618140503825462985, + 0.000000000015770990416421915106306877550025550097686639869166742016, + -0.000000000001084900468648598127623517893686893316653633996513097476, + -0.000000000001968659779411804788815966829825641065085077654946686012, + 0.000000000000098745634639726633264577838416327095717894829823436076, + 0.000000000000196734781460508097097473336847436635654948853090962606, + -0.000000000000008021080145299890797556481653726965016924825037889883, + -0.000000000000021030408801651651406095853493993966926736862877194669, + 0.000000000000000723888697830915633925166893301949334507697669655816, + 0.000000000000001943208515072761516084547140065815027641765976721267, + ], +} + + +def wavelist() -> list[str]: + """Return a list of available wavelet names.""" + return list(_WAVELET_COEFFS.keys()) + ["haar"] diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/waveft/waverec2d.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/waveft/waverec2d.py new file mode 100644 index 0000000000000000000000000000000000000000..7148c7ccf630379cb10dfd0d7bc8c6a29386be25 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/waveft/waverec2d.py @@ -0,0 +1,316 @@ +# Copyright 2021 Moritz Wolter +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the EUPL v1.2 +# +# This file contains code derived from PyTorch-Wavelet-Toolbox: +# https://github.com/v0lta/PyTorch-Wavelet-Toolbox +# +# Original work by Moritz Wolter, licensed under EUPL v1.2 +# Modifications and integration by HuggingFace Inc. team + +from collections.abc import Callable, Sequence +from functools import partial +from typing import Any, NamedTuple, Protocol, TypeAlias, Union, cast, overload + +import numpy as np +import torch +from typing_extensions import Unpack + +from .wavelet import Wavelet as minimal_wavelet + + +class WaveletDetailTuple2d(NamedTuple): + horizontal: torch.Tensor + vertical: torch.Tensor + diagonal: torch.Tensor + + +WaveletCoeff2d: TypeAlias = tuple[torch.Tensor, Unpack[tuple[WaveletDetailTuple2d, ...]]] +WaveletDetailDict: TypeAlias = dict[str, torch.Tensor] +WaveletCoeffNd: TypeAlias = tuple[torch.Tensor, Unpack[tuple[WaveletDetailDict, ...]]] + + +class Wavelet(Protocol): + name: str + dec_lo: Sequence[float] + dec_hi: Sequence[float] + rec_lo: Sequence[float] + rec_hi: Sequence[float] + dec_len: int + rec_len: int + filter_bank: tuple[Sequence[float], Sequence[float], Sequence[float], Sequence[float]] + + def __len__(self) -> int: + return len(self.dec_lo) + + +class WaveletTensorTuple(NamedTuple): + dec_lo: torch.Tensor + dec_hi: torch.Tensor + rec_lo: torch.Tensor + rec_hi: torch.Tensor + + @classmethod + def from_wavelet(cls, wavelet: Wavelet, dtype: torch.dtype) -> "WaveletTensorTuple": + return cls( + torch.tensor(wavelet.dec_lo, dtype=dtype), + torch.tensor(wavelet.dec_hi, dtype=dtype), + torch.tensor(wavelet.rec_lo, dtype=dtype), + torch.tensor(wavelet.rec_hi, dtype=dtype), + ) + + +def _as_wavelet(wavelet: Union[Wavelet, str]) -> Wavelet: + if isinstance(wavelet, str): + return minimal_wavelet(wavelet) + else: + return wavelet + + +def _is_dtype_supported(dtype: torch.dtype) -> bool: + return dtype in [torch.float16, torch.bfloat16, torch.float32, torch.float64] + + +def _outer(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor: + a_flat = torch.reshape(a, [-1]) + b_flat = torch.reshape(b, [-1]) + a_mul = torch.unsqueeze(a_flat, dim=-1) + b_mul = torch.unsqueeze(b_flat, dim=0) + return a_mul * b_mul + + +def _check_if_tensor(array: Any) -> torch.Tensor: + if not isinstance(array, torch.Tensor): + raise TypeError("First element of coeffs must be the approximation coefficient tensor.") + return array + + +def _check_axes_argument(axes: Sequence[int]) -> None: + if len(set(axes)) != len(axes): + raise ValueError("Cant transform the same axis twice.") + + +def _check_same_device(tensor: torch.Tensor, torch_device: torch.device) -> torch.Tensor: + if torch_device != tensor.device: + raise ValueError("coefficients must be on the same device") + return tensor + + +def _check_same_dtype(tensor: torch.Tensor, torch_dtype: torch.dtype) -> torch.Tensor: + if torch_dtype != tensor.dtype: + raise ValueError("coefficients must have the same dtype") + return tensor + + +@overload +def _coeff_tree_map( + coeffs: list[torch.Tensor], function: Callable[[torch.Tensor], torch.Tensor] +) -> list[torch.Tensor]: ... +@overload +def _coeff_tree_map(coeffs: WaveletCoeff2d, function: Callable[[torch.Tensor], torch.Tensor]) -> WaveletCoeff2d: ... +@overload +def _coeff_tree_map(coeffs: WaveletCoeffNd, function: Callable[[torch.Tensor], torch.Tensor]) -> WaveletCoeffNd: ... +def _coeff_tree_map(coeffs, function): + approx = function(coeffs[0]) + result_lst: list[Any] = [] + for element in coeffs[1:]: + if isinstance(element, tuple): + result_lst.append(WaveletDetailTuple2d(function(element[0]), function(element[1]), function(element[2]))) + elif isinstance(element, dict): + new_dict = {key: function(value) for key, value in element.items()} + result_lst.append(new_dict) + elif isinstance(element, torch.Tensor): + result_lst.append(function(element)) + else: + raise TypeError(f"Unexpected input type {type(element)}") + if not result_lst: + return [approx] if isinstance(coeffs, list) else (approx,) + elif isinstance(result_lst[0], torch.Tensor): + return [approx] + cast(list[torch.Tensor], result_lst) + else: + cast_result_lst = cast(Union[list[WaveletDetailDict], list[WaveletDetailTuple2d]], result_lst) + return (approx, *cast_result_lst) + + +def _check_same_device_dtype( + coeffs: Union[list[torch.Tensor], WaveletCoeff2d, WaveletCoeffNd], +) -> tuple[torch.device, torch.dtype]: + c = _check_if_tensor(coeffs[0]) + torch_device, torch_dtype = c.device, c.dtype + _coeff_tree_map(coeffs, partial(_check_same_device, torch_device=torch_device)) + _coeff_tree_map(coeffs, partial(_check_same_dtype, torch_dtype=torch_dtype)) + return torch_device, torch_dtype + + +def _get_transpose_order(axes: Sequence[int], data_shape: Sequence[int]) -> tuple[list[int], list[int]]: + axes = [a + len(data_shape) if a < 0 else a for a in axes] + all_axes = list(range(len(data_shape))) + remove_transformed = list(filter(lambda a: a not in axes, all_axes)) + return remove_transformed, axes + + +def _swap_axes(data: torch.Tensor, axes: Sequence[int]) -> torch.Tensor: + _check_axes_argument(axes) + front, back = _get_transpose_order(axes, list(data.shape)) + return torch.permute(data, front + back) + + +def _undo_swap_axes(data: torch.Tensor, axes: Sequence[int]) -> torch.Tensor: + _check_axes_argument(axes) + front, back = _get_transpose_order(axes, list(data.shape)) + restore_sorted = torch.argsort(torch.tensor(front + back)).tolist() + return torch.permute(data, restore_sorted) + + +def _fold_axes(data: torch.Tensor, keep_no: int) -> tuple[torch.Tensor, list[int]]: + dshape = list(data.shape) + return (torch.reshape(data, [int(np.prod(dshape[:-keep_no]))] + dshape[-keep_no:]), dshape) + + +def _unfold_axes(data: torch.Tensor, ds: list[int], keep_no: int) -> torch.Tensor: + return torch.reshape(data, ds[:-keep_no] + list(data.shape[-keep_no:])) + + +def _preprocess_coeffs(coeffs, ndim: int, axes, add_channel_dim: bool = False): + if isinstance(axes, int): + axes = (axes,) + torch_dtype = _check_if_tensor(coeffs[0]).dtype + if not _is_dtype_supported(torch_dtype): + raise ValueError(f"Input dtype {torch_dtype} not supported") + if ndim <= 0: + raise ValueError("Number of dimensions must be positive") + if tuple(axes) != tuple(range(-ndim, 0)): + if len(axes) != ndim: + raise ValueError(f"{ndim}D transforms work with {ndim} axes.") + else: + swap_fn = partial(_swap_axes, axes=axes) + coeffs = _coeff_tree_map(coeffs, swap_fn) + ds = list(coeffs[0].shape) + if len(ds) < ndim: + raise ValueError(f"At least {ndim} input dimensions required.") + elif len(ds) == ndim: + coeffs = _coeff_tree_map(coeffs, lambda x: x.unsqueeze(0)) + elif len(ds) > ndim + 1: + coeffs = _coeff_tree_map(coeffs, lambda t: _fold_axes(t, ndim)[0]) + if add_channel_dim: + coeffs = _coeff_tree_map(coeffs, lambda x: x.unsqueeze(1)) + return coeffs, ds + + +def _postprocess_coeffs(coeffs, ndim: int, ds: list[int], axes): + if isinstance(axes, int): + axes = (axes,) + if ndim <= 0: + raise ValueError("Number of dimensions must be positive") + if len(ds) < ndim: + raise ValueError(f"At least {ndim} input dimensions required.") + elif len(ds) == ndim: + coeffs = _coeff_tree_map(coeffs, lambda x: x.squeeze(0)) + elif len(ds) > ndim + 1: + unfold_axes_fn = partial(_unfold_axes, ds=ds, keep_no=ndim) + coeffs = _coeff_tree_map(coeffs, unfold_axes_fn) + if tuple(axes) != tuple(range(-ndim, 0)): + if len(axes) != ndim: + raise ValueError(f"{ndim}D transforms work with {ndim} axes.") + else: + undo_swap_fn = partial(_undo_swap_axes, axes=axes) + coeffs = _coeff_tree_map(coeffs, undo_swap_fn) + return coeffs + + +def _postprocess_tensor( + data: torch.Tensor, ndim: int, ds: list[int], axes: Union[tuple[int, ...], int] +) -> torch.Tensor: + return _postprocess_coeffs(coeffs=[data], ndim=ndim, ds=ds, axes=axes)[0] + + +def _get_filter_tensors( + wavelet: Union[Wavelet, str], flip: bool, device: torch.device, dtype: torch.dtype +) -> WaveletTensorTuple: + wavelet = _as_wavelet(wavelet) + if flip: + filters = WaveletTensorTuple( + torch.tensor(wavelet.rec_lo, device=device, dtype=dtype), + torch.tensor(wavelet.rec_hi, device=device, dtype=dtype), + torch.tensor(wavelet.dec_lo, device=device, dtype=dtype), + torch.tensor(wavelet.dec_hi, device=device, dtype=dtype), + ) + else: + filters = WaveletTensorTuple.from_wavelet(wavelet, dtype=dtype) + filters = WaveletTensorTuple( + filters.dec_lo.to(device), + filters.dec_hi.to(device), + filters.rec_lo.to(device), + filters.rec_hi.to(device), + ) + return filters + + +def _adjust_padding_at_reconstruction(tensor_len: int, coeff_len: int, padr: int, padl: int) -> tuple[int, int]: + if 2 * coeff_len - tensor_len == 1: + padr += 1 + elif 2 * coeff_len - tensor_len != 0: + raise ValueError("incorrect padding") + return padr, padl + + +def _construct_2d_filt(lo: torch.Tensor, hi: torch.Tensor) -> torch.Tensor: + ll = _outer(lo, lo) + lh = _outer(hi, lo) + hl = _outer(lo, hi) + hh = _outer(hi, hi) + filt = torch.stack([ll, lh, hl, hh], 0) + filt = filt.unsqueeze(1) + return filt + + +def waverec2d( + coeffs: WaveletCoeff2d, + wavelet: Union[Wavelet, str], + axes: tuple[int, int] = (-2, -1), +) -> torch.Tensor: + coeffs, ds = _preprocess_coeffs(coeffs, ndim=2, axes=axes) + torch_device, torch_dtype = _check_same_device_dtype(coeffs) + + _, _, rec_lo, rec_hi = _get_filter_tensors(wavelet, flip=False, device=torch_device, dtype=torch_dtype) + filt_len = rec_lo.shape[-1] + rec_filt = _construct_2d_filt(lo=rec_lo, hi=rec_hi) + + res_ll = coeffs[0] + for c_pos, coeff_tuple in enumerate(coeffs[1:]): + if not isinstance(coeff_tuple, tuple) or len(coeff_tuple) != 3: + raise ValueError(f"Unexpected detail coefficient type: {type(coeff_tuple)}. Must be a 3-tuple.") + + curr_shape = res_ll.shape + for coeff in coeff_tuple: + if coeff.shape != curr_shape: + raise ValueError("All coefficients on each level must have the same shape") + + res_lh, res_hl, res_hh = coeff_tuple + res_ll = torch.stack([res_ll, res_lh, res_hl, res_hh], 1) + res_ll = torch.nn.functional.conv_transpose2d(res_ll, rec_filt, stride=2).squeeze(1) + + padl = (2 * filt_len - 3) // 2 + padr = (2 * filt_len - 3) // 2 + padt = (2 * filt_len - 3) // 2 + padb = (2 * filt_len - 3) // 2 + if c_pos < len(coeffs) - 2: + padr, padl = _adjust_padding_at_reconstruction( + res_ll.shape[-1], coeffs[c_pos + 2][0].shape[-1], padr, padl + ) + padb, padt = _adjust_padding_at_reconstruction( + res_ll.shape[-2], coeffs[c_pos + 2][0].shape[-2], padb, padt + ) + + if padt > 0: + res_ll = res_ll[..., padt:, :] + if padb > 0: + res_ll = res_ll[..., :-padb, :] + if padl > 0: + res_ll = res_ll[..., padl:] + if padr > 0: + res_ll = res_ll[..., :-padr] + + res_ll = _postprocess_tensor(res_ll, ndim=2, ds=ds, axes=axes) + return res_ll diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/xlora/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/xlora/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6eae1f779b81e883f1dd64e3a4fca859391836c5 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/xlora/__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 XLoraConfig +from .model import XLoraModel + + +__all__ = ["XLoraConfig", "XLoraModel"] + +register_peft_method(name="xlora", config_cls=XLoraConfig, model_cls=XLoraModel) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/xlora/classifier.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/xlora/classifier.py new file mode 100644 index 0000000000000000000000000000000000000000..cdfca77d78105124c8cf5c6fe6d23ae1d586e9f3 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/xlora/classifier.py @@ -0,0 +1,195 @@ +# 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 builtins +from typing import Optional, Union + +import torch +from torch import nn + +from .config import XLoraConfig + + +Number = Union[builtins.int, builtins.float, builtins.bool] + + +class TemperatureScaledSoftmax(nn.Module): + def __init__(self, temperature=1.0): + super().__init__() + self.temperature = temperature + self.softmax = nn.Softmax(dim=-1) + + def forward(self, logits): + # Scale logits by the temperature + scaled_logits = logits / self.temperature + # Apply softmax to the scaled logits + return self.softmax(scaled_logits) + + +class XLoraClassifier(nn.Module): + """ + A classifier to select LoRA layers for XLora. + """ + + def __init__( + self, + model: nn.Module, # PeftModel + config: XLoraConfig, + n_classes: int, + n_layers: int, + device: torch.device, + ): + """ + Construct an X-LoRA classifier from a model, config and some metadata. Note that n_layers is the number of LoRA + adapter layers, not the number of model layers. + """ + super().__init__() + + self.n_classes = n_classes + self.n_layers = n_layers + self.config = config + self.log_scalings = [] + self.softmax = TemperatureScaledSoftmax(temperature=self.config.softmax_temperature) + self.override_scaling_pass_value: Number = config.scaling_pass_value + + self.scalings_logging = False + + self.dtype = next(model.parameters()).dtype + add_dropout = config.xlora_dropout_p > 0.0 + + layers = [] + if self.config.xlora_depth == 1: + if config.layerwise_scalings: # bias=False if we have just one layer + last = nn.Linear(config.hidden_size, n_classes * n_layers, bias=True).to(device).to(self.dtype) + else: + last = nn.Linear(config.hidden_size, n_classes, bias=True).to(device).to(self.dtype) + else: + if self.config.xlora_depth <= 0: + raise ValueError("X-LoRA depth must be strictly positive.") + + layers.append(nn.Linear(config.hidden_size, config.xlora_size, bias=True).to(device).to(self.dtype)) + + layers.append(nn.ReLU()) + if add_dropout: + layers.append(nn.Dropout(p=config.xlora_dropout_p)) + + for _ in range(config.xlora_depth - 2): + layers.append(nn.Linear(config.xlora_size, config.xlora_size, bias=True).to(device).to(self.dtype)) + + layers.append(nn.ReLU()) + if add_dropout: + layers.append(nn.Dropout(p=config.xlora_dropout_p)) + + if config.layerwise_scalings: + last = nn.Linear(config.xlora_size, n_classes * n_layers, bias=True).to(device).to(self.dtype) + else: + last = nn.Linear(config.xlora_size, n_classes, bias=True).to(device).to(self.dtype) + self.layers = nn.Sequential(*layers, last) + + def make_dummy_scalings( + self, + input_ids: Optional[torch.LongTensor] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + *args, + **kwargs, + ) -> torch.Tensor: + """ + Make some dummy scalings for the scalings pass (the one to get the logits for the X-LoRA classifier). These are + of shape (batch_size, seq_len, n_layers, n_classes) and filled with the override scalings pass value. Note that + n_layers is the number of LoRA adapter layers, not the number of model layers. + """ + if input_ids is not None: + batch_size = input_ids.shape[0] + device = input_ids.device + seq_len = input_ids.shape[1] + else: + batch_size = inputs_embeds.shape[0] + device = inputs_embeds.device + seq_len = inputs_embeds.shape[1] + + return torch.full( # type: ignore + (batch_size, seq_len, self.n_layers, self.n_classes), + self.override_scaling_pass_value, + ).to(device=device, dtype=self.dtype) + + def forward( + self, + result, + input_ids: Optional[torch.LongTensor] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + *args, + **kwargs, + ) -> torch.Tensor: + """ + Using the hidden states of the model, predict `n_classes` LoRA alpha values. Returns the scalings. + """ + if input_ids is not None: + batch_size = input_ids.shape[0] + seq_len = input_ids.shape[1] + else: + batch_size = inputs_embeds.shape[0] + seq_len = inputs_embeds.shape[1] + + hidden_states = result.hidden_states # type: ignore + + hidden_state = hidden_states[-1] # Get the last hidden state + + ### Classifier run + # hidden_state=[batch_size, seq_len, hidden_size] + logits = self.layers.forward(hidden_state) + + ### Repeat to make layerwise scalings + ### If layerwise_scalings=False, then the classifier only outputs logits which are not layer-wise. + ### So, we expand them to the correct shape. + if not self.config.layerwise_scalings: + logits = logits.unsqueeze(2) + logits = logits.expand(-1, -1, self.n_layers, -1) + + ### Classifier run + + scalings = logits.reshape(batch_size, seq_len, self.n_layers, self.n_classes) + # scalings = [batch_size, seq_len, n_layers, n_classes] + + if self.config.enable_softmax: + scalings = self.softmax(scalings) + + if self.scalings_logging: + self.log_scalings.append(scalings) + + return scalings + + def _get_bucketed_scalings(self) -> dict[int, tuple[list[int], list[torch.Tensor]]]: + """ + Returns bucketed scalings, bucketed by seq_len. Each value consists of the positions (the first) and the + associated tensors. The positions are paired with the associated tensors and give the position in the scaling + log. Each scaling is a tensor of shape (batch_size, seq_len, n_layers, n_classes)). + """ + seqlens_map: dict[int, tuple[list[int], list[torch.Tensor]]] = {} + for i, scaling in enumerate(self.log_scalings): + seq_len = scaling.shape[1] + if seq_len not in seqlens_map: + seqlens_map[seq_len] = ([i], [scaling]) + else: + seqlens_map[seq_len][0].append(i) + seqlens_map[seq_len][1].append(scaling) + + return seqlens_map + + def _set_override_scaling_pass_value(self, value: Union[Number, None]): + if value is None: + self.override_scaling_pass_value = 1 / self.n_classes + else: + self.override_scaling_pass_value = value + self.config.scaling_pass_value = self.override_scaling_pass_value diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/xlora/config.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/xlora/config.py new file mode 100644 index 0000000000000000000000000000000000000000..4a2a53fd83c48885b64ec9fc0d4c26c9b00d5d13 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/xlora/config.py @@ -0,0 +1,102 @@ +# 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 +from typing import Optional + +from peft.config import PeftConfig +from peft.utils.peft_types import PeftType + + +@dataclass +class XLoraConfig(PeftConfig): + r""" + This is the configuration class to store the configuration of a `XLoraModel`. When the config is reloaded, the + paths of the `adapters` field is disregarded in favor of the saved adapters. As such, only the keys matter during + loading. + + Args: + hidden_size (`int`): + Hidden size of the base model. + adapters (`dict`): + Mapping of adapter names to the LoRA adapter id, as per PeftModel.load_adapter. *They will be automatically + loaded*, to use as LoRA experts. When using from_pretrained, pass the new adapters dict as a keyword + argument. + enable_softmax (`bool`, *optional*, defaults to `True`): + Enable softmax application for the X-LoRA classifier. + enable_softmax_topk (`bool`, *optional*, defaults to `False`): + Enable softmax application for the top-k LoRA adapters. Mutually exclusive to `enable_softmax` and must + only be set if `top_k_lora` is. + softmax_temperature (`float`, *optional*, defaults to 1.0): + Softmax temperature, lower yields sharper predictions + layerwise_scalings (`bool`, *optional*, defaults to `False`): + If True, generate scalings for each LoRA adapter (each layer). If this is False, then scalings will be + broadcasted, the same, to each layer. + top_k_lora (`int`, *optional*, defaults to None): + Sparsely select the top_k LoRA experts instead of the default dense method. + xlora_depth (`int`, *optional*, defaults to 1): + Depth of the X-LoRA classifier. + xlora_size (`int`, *optional*, defaults to 2048): + Hidden size of the X-LoRA classifier, irrelevant if `xlora_depth=1`. + xlora_dropout_p (`float`, *optional*, defaults to 0.2): + Dropout probability of the X-LoRA classifier, irrelevant if `xlora_depth=1`. + use_trainable_adapters (`bool`, *optional*, defaults to False): + Make the adapters trainable. + scaling_pass_value (`float`, *optional*, defaults to 0): + Scaling pass value. + global_scaling_weight (`float`, *optional*, defaults to 1): + Weight to multiply output of each LoRA adapter by. + """ + + hidden_size: int = None # type: ignore + adapters: dict[str, str] = None # type: ignore + enable_softmax: bool = True + enable_softmax_topk: bool = False + layerwise_scalings: bool = False + xlora_depth: int = 1 + xlora_size: int = 2048 + xlora_dropout_p: float = 0.2 + use_trainable_adapters: bool = False + softmax_temperature: float = 1.0 + top_k_lora: Optional[int] = None + scaling_pass_value: float = 0.0 + global_scaling_weight: float = 1.0 + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.XLORA + + if self.hidden_size is None: + warnings.warn( + "No value was provided for `hidden_size`. This will be set to 4096 by default, please ensure that this is correct." + ) + self.hidden_size = 4096 + if self.adapters is None: + warnings.warn( + "No value was provided for `adapters`. This will be set to empty, please ensure that this is correct." + ) + self.adapters = {} + + if self.enable_softmax_topk and self.top_k_lora is None: + warnings.warn("`enable_softmax_topk` enabled `top_k_lora` is not set") + + if self.enable_softmax_topk and self.enable_softmax: + warnings.warn( + "`enable_softmax_topk` and `enable_softmax` are both enabled. This will result in worse performance." + ) + + if self.top_k_lora is not None and self.top_k_lora < 1: + warnings.warn("`top_k_lora` value must be at least 1.") diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/xlora/layer.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/xlora/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..e0eeac1aca3b600c8e7da3cc9584397a41061e88 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/xlora/layer.py @@ -0,0 +1,236 @@ +# 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 + +from collections.abc import Callable +from typing import Any, Optional + +import torch +from torch import Tensor, nn + +from peft.tuners import lora + +from .config import XLoraConfig + + +class XLoraLayer: + """ + A XLoraLayer wraps any LoraLayer and performs the XLora operation on the LoRA adaptors specified. Its primary API + is the forward method, which uses the scalings to execute the XLora algorithm. + """ + + def __init__( + self, + model: nn.Module, # XLoraModel + target: lora.LoraLayer, + target_forward: Callable[..., Any], + layer_number: int, + config: XLoraConfig, + ) -> None: + self.model = model + self.target_forward = target_forward + self.target = target + self.layer_number = layer_number + self.config = config + + """ + Apply the scalings for the adapter. + """ + + @staticmethod + def apply_scalings_to_x(x: torch.Tensor, scalings_layer: torch.Tensor, adapter: int) -> torch.Tensor: + # scalings_layer = [batch_size, seq_len, n_classes] + scalings = scalings_layer[:, :, adapter].unsqueeze(-1) + # scalings_layer = [batch_size, seq_len, 1] + return x * scalings + + """ + Get the scalings for this layer, potentially applying topk and topk+softmax. This is called before + `apply_scalings_to_x` + """ + + def get_maybe_topk_scalings(self, scalings) -> torch.Tensor: + # xlora_scalings = [batch_size, seq_len, n_classes] + xlora_scalings: Tensor = scalings[:, :, self.layer_number, :] # type: ignore + + if self.config.top_k_lora is not None: + _, topk_indices = torch.topk(xlora_scalings, k=self.config.top_k_lora, dim=-1) + + # Mask the topk to True, the rest to False + mask = torch.zeros_like(xlora_scalings, dtype=torch.bool) + mask.scatter_(-1, topk_indices, True) + + xlora_scalings = xlora_scalings * mask.to(xlora_scalings.dtype) + + # Apply per-token normalization to the xLoRA scaling factors using a softmax + if self.config.enable_softmax_topk: + nonzero_mask = xlora_scalings != 0 + full = xlora_scalings.masked_fill(~nonzero_mask, float("-inf")) + new_scalings = torch.softmax(full, dim=-1) + xlora_scalings = new_scalings.masked_fill(~nonzero_mask, 0.0) + + return xlora_scalings + + +class XLoraLinearLayer(XLoraLayer): + def __init__( + self, + model: nn.Module, + target: lora.Linear, + target_forward: Callable[..., Any], + layer_number: int, + config: XLoraConfig, + ) -> None: + super().__init__(model, target, target_forward, layer_number, config) + + def forward(self, x: Tensor, *args: Any, scalings: Optional[Tensor] = None, **kwargs: Any) -> Tensor: + """ + This method is designed to be a drop-in-replacement for the LoRA layers' .forward method. To use it, a bound + method must be created (bound to an instance of the XLoraLayer class). + """ + + previous_dtype = x.dtype + if scalings is not None: + xlora_scalings = self.get_maybe_topk_scalings(scalings) + + result = self.target.base_layer(x, *args, **kwargs) + + # Ignore if disabled. We want to make sure this is always run. + if not self.target.merged: + for adapter_n, active_adapter in enumerate(self.target.active_adapters): + if active_adapter not in self.target.lora_A.keys(): + continue + # TODO: implement X-LoRA with Lora+Dora layers + if self.target.use_dora[active_adapter]: + raise ValueError("X-LoRA currently does not support LoRA layers with DoRA") + lora_A = self.target.lora_A[active_adapter] + lora_B = self.target.lora_B[active_adapter] + dropout = self.target.lora_dropout[active_adapter] + scaling = self.target.scaling[active_adapter] + x = x.to(lora_A.weight.dtype) # type: ignore + if scalings is not None: + x_mod = self.apply_scalings_to_x(x, xlora_scalings, adapter_n) + scaling_weight = self.config.global_scaling_weight + else: + x_mod = x + scaling_weight = 1 + result += lora_B(lora_A(dropout(x_mod))) * scaling * scaling_weight + + result = result.to(previous_dtype) + return result + + +class XLoraEmbeddingLayer(XLoraLayer): + def __init__( + self, + model: nn.Module, + target: lora.Embedding, + target_forward: Callable[..., Any], + layer_number: int, + config: XLoraConfig, + ) -> None: + super().__init__(model, target, target_forward, layer_number, config) + + def forward(self, x: Tensor, *args: Any, scalings: Optional[Tensor] = None, **kwargs: Any) -> Tensor: + """ + This method is designed to be a drop-in-replacement for the LoRA layers' .forward method. To use it, a bound + method must be created (bound to an instance of the XLoraLayer class). + """ + + if scalings is not None: + xlora_scalings = self.get_maybe_topk_scalings(scalings) + + result = self.target.base_layer(x, *args, **kwargs) + + # Some embedding layers (e.g., Gemma3TextScaledWordEmbedding) apply scaling in their forward method. + # Since base_layer(x) already includes this scaling, we need to apply it to X-LoRA contributions too. + embed_scale = self.target._get_embed_scale() + + # Ignore if disabled. We want to make sure this is always run. + if not self.target.merged: + for adapter_n, active_adapter in enumerate(self.target.active_adapters): + if active_adapter not in self.target.lora_embedding_A: + continue + # TODO: implement X-LoRA with Lora+Dora layers + if self.target.use_dora.get(active_adapter, False): + raise ValueError("X-LoRA currently does not support LoRA layers with DoRA") + embedding_A = self.target.lora_embedding_A[active_adapter].T + embedding_B = self.target.lora_embedding_B[active_adapter].T + scaling = self.target.scaling[active_adapter] + after_A = self.target._embed(x, embedding_A) # type: ignore + if scalings is not None: + after_A_mod = self.apply_scalings_to_x(after_A, xlora_scalings, adapter_n) + scaling_weight = self.config.global_scaling_weight + else: + after_A_mod = after_A + scaling_weight = 1 + + adapter_output = (after_A_mod @ embedding_B) * scaling * scaling_weight + + # Apply embed_scale to match the base layer's scaling + if embed_scale is not None: + adapter_output = adapter_output * embed_scale.to(adapter_output.dtype) + + result += adapter_output + + return result + + +class XLoraConv2dLayer(XLoraLayer): + def __init__( + self, + model: nn.Module, + target: lora.Conv2d, + target_forward: Callable[..., Any], + layer_number: int, + config: XLoraConfig, + ) -> None: + super().__init__(model, target, target_forward, layer_number, config) + + def forward(self, x: Tensor, *args: Any, scalings: Optional[Tensor] = None, **kwargs: Any) -> Tensor: + """ + This method is designed to be a drop-in-replacement for the LoRA layers' .forward method. To use it, a bound + method must be created (bound to an instance of the XLoraLayer class). + """ + + previous_dtype = x.dtype + + if scalings is not None: + xlora_scalings = self.get_maybe_topk_scalings(scalings) + + result = self.target.base_layer(x, *args, **kwargs) + + # Ignore if disabled. We want to make sure this is always run. + if not self.target.merged: + for adapter_n, active_adapter in enumerate(self.target.active_adapters): + if active_adapter not in self.target.lora_A.keys(): + continue + # TODO: implement X-LoRA with Lora+Dora layers + if self.target.use_dora[active_adapter]: + raise ValueError("X-LoRA currently does not support LoRA layers with DoRA") + lora_A = self.target.lora_A[active_adapter] + lora_B = self.target.lora_B[active_adapter] + dropout = self.target.lora_dropout[active_adapter] + scaling = self.target.scaling[active_adapter] + x = x.to(lora_A.weight.dtype) # type: ignore + if scalings is not None: + x_mod = self.apply_scalings_to_x(x, xlora_scalings, adapter_n) + scaling_weight = self.config.global_scaling_weight + else: + x_mod = x + scaling_weight = 1 + result += lora_B(lora_A(dropout(x_mod))) * scaling * scaling_weight + + result = result.to(previous_dtype) + return result diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/xlora/model.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/xlora/model.py new file mode 100644 index 0000000000000000000000000000000000000000..08a22f0aca534a17935d2fb486931a7e8d41316e --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/xlora/model.py @@ -0,0 +1,525 @@ +# 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 copy +from contextlib import contextmanager +from functools import partial +from typing import Optional, Union + +import torch +from torch import nn + +from peft.tuners.lora.layer import LoraLayer +from peft.tuners.lora.model import LoraModel +from peft.tuners.tuners_utils import BaseTuner +from peft.utils.constants import DUMMY_TARGET_MODULES +from peft.utils.save_and_load import set_peft_model_state_dict + +from .. import lora +from .classifier import XLoraClassifier +from .config import XLoraConfig +from .layer import XLoraConv2dLayer, XLoraEmbeddingLayer, XLoraLinearLayer + + +def convert_layers_to_xlora( + base: nn.Module, # PeftModel + xloramodel: nn.Module, # XLoraModel + config: XLoraConfig, +) -> tuple[int, torch.device | None]: + """ + Returns the number of swapped layers. + """ + total_swapped = 0 + all_layers = [] + + device = None + for module in base.modules(): + # Check the exact type because classes like OPTLearnedPositionalEmbedding inherit from nn.Embedding + if isinstance(module, lora.Linear): + device = module.lora_A[next(iter(module.lora_A))].weight.device + new_layer = XLoraLinearLayer( + model=xloramodel, + target=module, + target_forward=module.forward, + layer_number=total_swapped, + config=config, + ) + all_layers.append(new_layer) + module.forward = new_layer.forward # type: ignore[method-assign] + total_swapped += 1 + elif isinstance(module, lora.Embedding): + device = module.lora_embedding_A[next(iter(module.lora_embedding_A))].device + new_layer = XLoraEmbeddingLayer( + model=xloramodel, + target=module, + target_forward=module.forward, + layer_number=total_swapped, + config=config, + ) + all_layers.append(new_layer) + module.forward = new_layer.forward # type: ignore[method-assign] + total_swapped += 1 + elif isinstance(module, lora.Conv2d): + device = module.lora_A[next(iter(module.lora_A))].weight.device + new_layer = XLoraConv2dLayer( + model=xloramodel, + target=module, + target_forward=module.forward, + layer_number=total_swapped, + config=config, + ) + all_layers.append(new_layer) + module.forward = new_layer.forward # type: ignore[method-assign] + total_swapped += 1 + + return (total_swapped, device) + + +def _load_adapter_into_lora_model( + lora_model: LoraModel, + adapter_name: str, + model_id: str, + torch_device: Optional[str] = None, + ephemeral_gpu_offload: bool = False, + autocast_adapter_dtype: bool = True, + subfolder: Optional[str] = None, + **kwargs, +): + """ + This method emulates the behavior of `PeftModel.from_pretrained`. Updates to `PeftModel.from_pretrained` may need + to be reflected here. + + All params pertain to the adapter (adapter name, model id, `i` is the adapter number in 0 indexing). + """ + from peft.peft_model import PeftModel + from peft.tuners.lora.config import LoraConfig + from peft.utils.other import infer_device + from peft.utils.save_and_load import load_peft_weights + + hf_hub_download_kwargs, kwargs = PeftModel._split_kwargs(kwargs) + if torch_device is None: + torch_device = infer_device() + + if adapter_name not in lora_model.peft_config: + # load the config + lora_peft_config = LoraConfig.from_pretrained( + model_id, + ephemeral_gpu_offload=ephemeral_gpu_offload, + subfolder=subfolder, + **hf_hub_download_kwargs, + ) + lora_peft_config.inference_mode = False + lora_model.peft_config[adapter_name] = lora_peft_config + lora_model.inject_adapter(lora_model.model, adapter_name) + + adapter_weights = load_peft_weights(model_id, device=torch_device, subfolder=subfolder, **hf_hub_download_kwargs) + new_adapter_weights = {} + # Rework the keys to contain the adapter numbers + for old_key in adapter_weights.keys(): + key: str = old_key + # Remove all the prefixes until we have model.<...> + while not (key.startswith("model.") and not key.startswith("model.model.")): + key = key[key.find(".") + 1 :] + # We always want model.model + key = "model." + key + new_adapter_weights[key] = adapter_weights[old_key] + + # load the weights into the model + ignore_mismatched_sizes = kwargs.get("ignore_mismatched_sizes", False) + load_result = set_peft_model_state_dict( + lora_model, + new_adapter_weights, + adapter_name=adapter_name, + ignore_mismatched_sizes=ignore_mismatched_sizes, + ) + if len(load_result.unexpected_keys) > 0: + raise ValueError( + f"Got unexpected keys! Please raise an issue and tag @EricLBuehler.\n\nunexpected_keys={load_result.unexpected_keys}" + ) + + if hasattr(lora_model, "_cast_adapter_dtype"): + lora_model._cast_adapter_dtype(adapter_name=adapter_name, autocast_adapter_dtype=autocast_adapter_dtype) + + +class XLoraModel(BaseTuner): + """ + Creates an X-LoRA (Mixture of LoRA experts), model from a pretrained transformers model. Currently, this X-LoRA + implementation only works with models with a transformer architecture. + + The method is described in detail in https://huggingface.co/papers/2402.07148. + + Args: + model ([`torch.nn.Module`]): The model to be adapted. + config ([`XLoraConfig`]): The configuration of the Lora model. + adapter_name (`str`): The name of the adapter, does not affect the LoRA adapter names. + + Returns: + `torch.nn.Module`: The X-LoRA model. + + Example: + ```py + >>> import torch + >>> from transformers import AutoModelForCausalLM, AutoConfig, BitsAndBytesConfig + >>> from peft import XLoraConfig, get_peft_model, prepare_model_for_kbit_training + + >>> model_config = AutoConfig.from_pretrained("mistralai/Mistral-7B-Instruct-v0.1") + >>> config = XLoraConfig( + ... task_type="CAUSAL_LM", + ... hidden_size=model_config.hidden_size, + ... xlora_depth=4, + ... adapters={ + ... "adapter_1": "./path/to/the/checkpoint/", + ... "adapter_2": "./path/to/the/checkpoint/", + ... "adapter_n": "./path/to/the/checkpoint/", + ... }, + ... ) + >>> int8_config = BitsAndBytesConfig(load_in_8bit=True) + >>> model = AutoModelForCausalLM.from_pretrained( + ... "mistralai/Mistral-7B-Instruct-v0.1", + ... trust_remote_code=True, + ... attn_implementation="flash_attention_2", + ... device_map="cuda:0", + ... torch_dtype=torch.bfloat16, + ... quantization_config=int8_config, + ... ) + >>> model = prepare_model_for_kbit_training(model) + >>> xlora_model = get_peft_model(model, config) + ``` + """ + + def __init__( + self, + model: nn.Module, + config: Union[dict[str, XLoraConfig], XLoraConfig], + adapter_name: str, + torch_device: Optional[str] = None, + ephemeral_gpu_offload: bool = False, + autocast_adapter_dtype: bool = True, + **kwargs, + ) -> None: + """ + Create a new X-LoRA model + + Args: + model (`nn.Module`): + Base model to apply X-LoRA to. + config: ([`XLoraConfig`]): + X-LoRA configuration object. + adapter_name: (`str`): + Adapter name for the X-LoRA adapter. + torch_device (`str`, *optional*, defaults to None): + (For loading the LoRA adapters) The device to load the adapter on. If `None`, the device will be + inferred. + ephemeral_gpu_offload (`bool`, *optional*, defaults to `False`): + (For loading the LoRA adapters) Whether to use ephemeral GPU offloading for partially loaded modules. + Defaults to `False`. + autocast_adapter_dtype (`bool`, *optional*, defaults to `True`): + (For loading the LoRA adapters) Whether to autocast the adapter dtype. Defaults to `True`. Right now, + this will only cast adapter weights using float16 and bfloat16 to float32, as this is typically + required for stable training, and only affect select PEFT tuners. + kwargs: (`optional`): + (For loading the LoRA adapters) Additional arguments to modify the way the adapter is loaded, e.g. the + token for Hugging Face Hub. + """ + + nn.Module.__init__(self) + + if isinstance(config, dict): + conf = config[adapter_name] + else: + conf = config + + # Create an empty LoraModel + base_lora_config = copy.copy(conf) + base_lora_config.target_modules = DUMMY_TARGET_MODULES + # Imitate a LoraConfig, fields might need to be updated if LoraConfig is updated + base_lora_config.layer_replication = None + base_lora_config.bias = "none" + lora_model = LoraModel(model, base_lora_config, adapter_name) + + self.xlora_config = conf + self.lora_model = lora_model + + peft_config = conf + + if hasattr(model.config, "use_cache") and model.config.use_cache: + raise ValueError("`use_cache` must be False") + + adapters_items = peft_config.adapters.items() + if hasattr(self.xlora_config, "_subfolders"): + adapters_items = zip(peft_config.adapters.items(), self.xlora_config._subfolders) + else: + adapters_items = peft_config.adapters.items() + + if hasattr(self.xlora_config, "_subfolders"): + for i, (_adapter_name, model_id), subfolder in enumerate(adapters_items): + _load_adapter_into_lora_model( + lora_model=self.lora_model, + adapter_name=str(i), + model_id=model_id, + torch_device=torch_device, + ephemeral_gpu_offload=ephemeral_gpu_offload, + autocast_adapter_dtype=autocast_adapter_dtype, + subfolder=subfolder, + **kwargs, + ) + else: + for i, (_adapter_name, model_id) in enumerate(adapters_items): + _load_adapter_into_lora_model( + lora_model=self.lora_model, + adapter_name=str(i), + model_id=model_id, + torch_device=torch_device, + ephemeral_gpu_offload=ephemeral_gpu_offload, + autocast_adapter_dtype=autocast_adapter_dtype, + subfolder=None, + **kwargs, + ) + + self.lora_model.set_adapter(list(peft_config.adapters.keys())) + + self._maybe_freeze_all_adapters() + + total_swapped, device = convert_layers_to_xlora( + model, + self, + peft_config, + ) + + n_classes = len(peft_config.adapters) + xlora_classifier = XLoraClassifier(model, peft_config, n_classes, total_swapped, device) + + # Setup the model internal state + self.internal_xlora_classifier = xlora_classifier + self.internal_xlora_scalings = None # type: ignore + # Controlled by enable_adapter_layers or disable_adapter_layers + self.disabled = False + + def _maybe_freeze_all_adapters(self): + self.eval() + if not self.xlora_config.use_trainable_adapters: + for name, param in self.named_parameters(): + if "lora_" in name: + param.requires_grad = False + + def generate(self, *args, **kwargs): + kwargs["use_cache"] = False + res = self.lora_model.generate(*args, **kwargs) # type: ignore + # This is necessary because we use PeftModel.disable_adapter() which reenables the adapters + self._maybe_freeze_all_adapters() + return res + + @contextmanager + def _enable_peft_forward_hooks(self, *generate_args, **generate_kwargs): + def scalings_injection_hook(target, args, kwargs, scalings): + # pre-forward hook to inject the adapter_names argument when using mixed adapter batches inference + kwargs["scalings"] = scalings + return args, kwargs + + hook_handles = [] + + def _pre_forward(module, *args, **kwargs): + # =========================== Forward pass with "dummy" scalings ================== + nonlocal hook_handles + + args_real = args[0] + kwargs_real = args[1] + kwargs_real.update(kwargs) + + dummy_scalings = self.internal_xlora_classifier.make_dummy_scalings(*args_real, **kwargs_real) + + for xlora_module in self.modules(): + if isinstance(xlora_module, LoraLayer): + pre_forward = partial(scalings_injection_hook, scalings=dummy_scalings) + existing_hooks = getattr(xlora_module, "_forward_pre_hooks", {}) + if any(val is scalings_injection_hook for val in existing_hooks.values()): + # When calling generate, module.forward is called multiple times inside the forward hook + # context, resulting in multiple hooks being registered. Therefore, we check if the hooks is + # already present and skip it in that case. + continue + handle = xlora_module.register_forward_pre_hook(pre_forward, with_kwargs=True) + hook_handles.append(handle) + + with torch.no_grad(): + self.lora_model.disable_adapter_layers() + + try: + scaling_pass_kwargs = kwargs_real.copy() + scaling_pass_kwargs["output_hidden_states"] = True + scaling_pass_kwargs["return_dict"] = True + try: + base_output = self.lora_model.model.forward(*args_real, **scaling_pass_kwargs) + finally: + # Clean everything up + for handle in hook_handles: + handle.remove() + finally: + self.lora_model.enable_adapter_layers() + + xlora_scalings = self.internal_xlora_classifier(*args_real, result=base_output, **kwargs_real) + # Store computed scalings to fix get_latest_scalings() returning None + self.internal_xlora_scalings = xlora_scalings + + # =========================== Real forward pass with calculated scalings ================== + + hook_handles = [] + for xlora_module in self.modules(): + if isinstance(xlora_module, LoraLayer): + pre_forward = partial(scalings_injection_hook, scalings=xlora_scalings) + handle = xlora_module.register_forward_pre_hook(pre_forward, with_kwargs=True) + hook_handles.append(handle) + + if not self.disabled: + forward_handle = self.lora_model.model.register_forward_pre_hook(_pre_forward, with_kwargs=True) + + # Run the forward pass: first the scaling pass in the hook, and then with the base model + try: + yield + finally: + if not self.disabled: + for handle in hook_handles: + handle.remove() + forward_handle.remove() + + def __getattr__(self, name: str): + """Forward missing attributes to the wrapped module.""" + try: + return super().__getattr__(name) # defer to nn.Module's logic + except AttributeError: + if name == "lora_model": # see #1892: prevent infinite recursion if class is not initialized + raise + return getattr(self.lora_model, name) + + @staticmethod + def _prepare_adapter_config(peft_config, _model_config): + # Handle X-LoRA case + return peft_config + + """ + Does nothing. X-LoRA needs adapters to be frozen. + """ + + def _mark_only_adapters_as_trainable(self) -> None: ... + + """ + This enables the X-LoRA adapter. + """ + + def enable_adapter_layers(self) -> None: + self.disabled = False + + """ + This diasables the X-LoRA adapter. + """ + + def disable_adapter_layers(self) -> None: + self.disabled = True + + def _create_and_replace( + self, + lora_config, + adapter_name, + target, + target_name, + parent, + current_key, + ): + # Does nothing because XLoraModel has no target modules + pass + + @staticmethod + def _check_target_module_exists(lora_config, key): + # Does nothing because XLoraModel has no target modules + return False + + def forward(self, *args, **kwargs): + return self.lora_model.model(*args, **kwargs) + + def set_topk_lora(self, value: Optional[int]): + """ + Sparsely select the specified top_k LoRA experts instead of the default dense method. Set to None to use dense. + This is reflected in the config. + """ + classifier: XLoraClassifier = self.internal_xlora_classifier # type: ignore + classifier.config.top_k_lora = value + + def set_global_scaling_weight(self, weight: float): + """ + Set the global LoRA weight, a scalar to multiply the output of each LoRA adapter by. This is by default 1. This + is reflected in the config. + """ + classifier: XLoraClassifier = self.internal_xlora_classifier # type: ignore + classifier.config.global_scaling_weight = weight + + def set_scaling_pass_value(self, value: float | None): + """ + Set the scaling pass value, the value to set the scalings to during the scaling pass. If the value is None, the + scaling pass value will be 1/n where n is the number of adapters. + """ + classifier: XLoraClassifier = self.internal_xlora_classifier # type: ignore + classifier._set_override_scaling_pass_value(value) + + def get_global_scaling_weight(self) -> float: + """ + Get the global LoRA weight. + """ + classifier: XLoraClassifier = self.internal_xlora_classifier # type: ignore + return classifier.config.global_scaling_weight + + def get_latest_scalings(self) -> Optional[torch.Tensor]: + """ + Returns the latest scalings prediction, or None if no scalings have been predicted. The tensor is of shape + (batch_size, seq_len, n_layers, n_classes). + """ + return self.internal_xlora_scalings + + def get_scalings_log(self) -> list[torch.Tensor]: + """ + Returns a shallow (only copying the list itself not the tensors) copy of the list containing the scalings log. + Editing the list does not change the underlying log. The tensors are of shape (batch_size, seq_len, n_layers, + n_classes). The seq_len dim may vary with input dimension. + """ + classifier: XLoraClassifier = self.internal_xlora_classifier # type: ignore + return classifier.log_scalings.copy() + + def enable_scalings_logging(self): + """ + Enable scalings logging. + """ + classifier: XLoraClassifier = self.internal_xlora_classifier # type: ignore + classifier.scalings_logging = True + + def disable_scalings_logging(self): + """ + Disable scalings logging, without clearing the log. + """ + classifier: XLoraClassifier = self.internal_xlora_classifier # type: ignore + classifier.scalings_logging = False + + def clear_scalings_log(self): + """ + Clear the scalings log. + """ + classifier: XLoraClassifier = self.internal_xlora_classifier # type: ignore + classifier.log_scalings.clear() + + def get_bucketed_scalings_log(self) -> dict[int, tuple[list[int], list[torch.Tensor]]]: + """ + Returns bucketed scalings, bucketed by seq_len. Each value consists of the positions (the first) and the + associated tensors. The positions are paired with the associated tensors and give the position in the scaling + log. + """ + classifier: XLoraClassifier = self.internal_xlora_classifier # type: ignore + return classifier._get_bucketed_scalings() diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/utils/__init__.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ba78c43ccb1e11dd5fd3152dcf533e22b5b64e7b --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/utils/__init__.py @@ -0,0 +1,151 @@ +# 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 .constants import ALLOWED_COMPUTE_DTYPES, UPCAST_DTYPES +from .integrations import map_cache_to_layer_device_map +from .loftq_utils import replace_lora_weights_loftq +from .other import ( + CONFIG_NAME, + INCLUDE_LINEAR_LAYERS_SHORTHAND, + SAFETENSORS_WEIGHTS_NAME, + TRANSFORMERS_MODELS_TO_ADALORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_ADAMSS_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_BEFT_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_BOFT_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_C3A_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_DELORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_FOURIERFT_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_GRALORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_HRA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_IA3_FEEDFORWARD_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_IA3_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_LILY_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_LNTUNING_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_LOHA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_LOKR_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_MISS_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_OFT_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_PEANUT_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_POLY_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING, + TRANSFORMERS_MODELS_TO_PSOFT_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_PVERA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_RANDLORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_ROAD_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_SHIRA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_TINYLORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_VBLORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_VERA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_WAVEFT_TARGET_MODULES_MAPPING, + WEIGHTS_NAME, + AuxiliaryTrainingWrapper, + ModulesToSaveWrapper, + TrainableTokensWrapper, + _freeze_adapter, + _get_batch_size, + _get_input_embeddings_name, + _get_submodules, + _is_valid_match, + _prepare_prompt_learning_config, + _set_adapter, + _set_trainable, + bloom_model_postprocess_past_key_value, + cast_mixed_precision_params, + get_gptqmodel_quant_linear, + get_quantization_config, + id_tensor_storage, + infer_device, + prepare_model_for_kbit_training, + set_additional_trainable_modules, + shift_tokens_right, + transpose, +) +from .peft_types import PeftType, TaskType, register_peft_method +from .quantization_utils import get_quantization_kwargs, quantization_extra_repr, resolve_quantization_backend +from .save_and_load import get_peft_model_state_dict, load_peft_weights, set_peft_model_state_dict +from .warning import PeftWarning + + +__all__ = [ + "ALLOWED_COMPUTE_DTYPES", + "CONFIG_NAME", + "INCLUDE_LINEAR_LAYERS_SHORTHAND", + "SAFETENSORS_WEIGHTS_NAME", + "TRANSFORMERS_MODELS_TO_ADALORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_ADAMSS_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_BEFT_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_BOFT_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_C3A_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_DELORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_FOURIERFT_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_GRALORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_HRA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_IA3_FEEDFORWARD_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_IA3_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_LILY_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_LNTUNING_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_LOHA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_LOKR_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_MISS_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_OFT_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_PEANUT_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_POLY_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING", + "TRANSFORMERS_MODELS_TO_PSOFT_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_PVERA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_RANDLORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_ROAD_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_SHIRA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_TINYLORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_VBLORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_VERA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_WAVEFT_TARGET_MODULES_MAPPING", + "UPCAST_DTYPES", + "WEIGHTS_NAME", + "AuxiliaryTrainingWrapper", + "ModulesToSaveWrapper", + "PeftType", + "PeftWarning", + "TaskType", + "TrainableTokensWrapper", + "_freeze_adapter", + "_get_batch_size", + "_get_input_embeddings_name", + "_get_submodules", + "_is_valid_match", + "_prepare_prompt_learning_config", + "_set_adapter", + "_set_trainable", + "bloom_model_postprocess_past_key_value", + "cast_mixed_precision_params", + "get_gptqmodel_quant_linear", + "get_peft_model_state_dict", + "get_quantization_config", + "get_quantization_kwargs", + "id_tensor_storage", + "infer_device", + "load_peft_weights", + "map_cache_to_layer_device_map", + "prepare_model_for_kbit_training", + "quantization_extra_repr", + "register_peft_method", + "replace_lora_weights_loftq", + "resolve_quantization_backend", + "set_additional_trainable_modules", + "set_peft_model_state_dict", + "shift_tokens_right", + "transpose", +] diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/utils/constants.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/utils/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..94aa475f0dbb36809c8d42577b063df86beb4b18 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/utils/constants.py @@ -0,0 +1,403 @@ +# 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 transformers import BloomPreTrainedModel + +from ..import_utils import is_transformers_le_4_53 + + +# needed for prefix-tuning of bloom model +def bloom_model_postprocess_past_key_value(past_key_values): + past_key_values = torch.cat(past_key_values) + total_layers, batch_size, num_attention_heads, num_virtual_tokens, head_dim = past_key_values.shape + keys = past_key_values[: total_layers // 2] + keys = keys.transpose(2, 3).reshape( + total_layers // 2, batch_size * num_attention_heads, head_dim, num_virtual_tokens + ) + values = past_key_values[total_layers // 2 :] + values = values.reshape(total_layers // 2, batch_size * num_attention_heads, num_virtual_tokens, head_dim) + + return tuple(zip(keys, values)) + + +# needed for prefix-tuning of StarCoder models +def starcoder_model_postprocess_past_key_value(past_key_values): + result = [] + for k in past_key_values: + k = k[:, :, 0] + k = k.permute([1, 2, 0, 3]) + k = k.reshape(*k.shape[:-2], -1) + result.append(k) + return tuple(result) + + +# TODO: remove this once transformers 4.53 is no longer supported +TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING = {} +if is_transformers_le_4_53: + TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING["gpt_bigcode"] = ( + starcoder_model_postprocess_past_key_value + ) + + +if hasattr(BloomPreTrainedModel, "_convert_to_standard_cache"): + # special handling for bloom architecture was fixed in: + # https://github.com/huggingface/transformers/pull/31445 + # the _convert_to_standard_cache method is removed in the PR and thus serves as an indicator + TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING["bloom"] = bloom_model_postprocess_past_key_value + + +####################################### +# DEFAULT MAPPINGS FOR TARGET_MODULES # +####################################### + +TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING = { + "t5": ["q", "v"], + "mt5": ["q", "v"], + "bart": ["q_proj", "v_proj"], + "gpt2": ["c_attn"], + "bloom": ["query_key_value"], + "blip-2": ["q", "v", "q_proj", "v_proj"], + "opt": ["q_proj", "v_proj"], + "gptj": ["q_proj", "v_proj"], + "gpt_neox": ["query_key_value"], + "gpt_neo": ["q_proj", "v_proj"], + "bert": ["query", "value"], + "roberta": ["query", "value"], + "xlm-roberta": ["query", "value"], + "electra": ["query", "value"], + "deberta-v2": ["query_proj", "value_proj"], + "deberta": ["in_proj"], + "layoutlm": ["query", "value"], + "llama": ["q_proj", "v_proj"], + "llama4": ["q_proj", "v_proj"], + "chatglm": ["query_key_value"], + "gpt_bigcode": ["c_attn"], + "mpt": ["Wqkv"], + "RefinedWebModel": ["query_key_value"], + "RefinedWeb": ["query_key_value"], + "falcon": ["query_key_value"], + "btlm": ["c_proj", "c_attn"], + "codegen": ["qkv_proj"], + "mistral": ["q_proj", "v_proj"], + "mixtral": ["q_proj", "v_proj"], + "stablelm": ["q_proj", "v_proj"], + "phi": ["q_proj", "v_proj", "fc1", "fc2"], + "gemma": ["q_proj", "v_proj"], + "gemma2": ["q_proj", "v_proj"], + "gemma3_text": ["q_proj", "v_proj"], + "gemma4": r".*language_model\..*\.(q_proj|v_proj)", + "qwen2": ["q_proj", "v_proj"], + "qwen3": ["q_proj", "v_proj"], + "rwkv": ["key", "value", "receptance", "output"], + "rwkv7": ["r_proj", "k_proj", "v_proj", "o_proj", "key", "value"], +} + +# target module mappings that are identical to LORA +TRANSFORMERS_MODELS_TO_BOFT_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_C3A_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_DELORA_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_HRA_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_LOHA_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_LOKR_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_MISS_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_OFT_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_POLY_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_RANDLORA_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_ADAMSS_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_ADAMSS_TARGET_MODULES_MAPPING["vit"] = ["query", "value"] +TRANSFORMERS_MODELS_TO_ROAD_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_TINYLORA_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_PSOFT_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_LILY_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_GRALORA_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_PEANUT_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() + +# mappings that are similar to LORA with small changes +TRANSFORMERS_MODELS_TO_FOURIERFT_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_FOURIERFT_TARGET_MODULES_MAPPING["gpt_bigcode"] = ["mlp.c_proj"] +TRANSFORMERS_MODELS_TO_FOURIERFT_TARGET_MODULES_MAPPING["gpt2"] = ["mlp.c_proj"] + +TRANSFORMERS_MODELS_TO_SHIRA_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_SHIRA_TARGET_MODULES_MAPPING["phi"] = ["q_proj", "v_proj"] + +TRANSFORMERS_MODELS_TO_VERA_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_VERA_TARGET_MODULES_MAPPING["phi"] = ["q_proj", "v_proj"] + +TRANSFORMERS_MODELS_TO_PVERA_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_VERA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_PVERA_TARGET_MODULES_MAPPING["dinov2"] = ["query", "value"] + +TRANSFORMERS_MODELS_TO_C3A_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_C3A_TARGET_MODULES_MAPPING["gpt_bigcode"] = ["mlp.c_proj"] +TRANSFORMERS_MODELS_TO_C3A_TARGET_MODULES_MAPPING["gpt2"] = ["mlp.c_proj"] + +# target module mappings that differ from LORA +TRANSFORMERS_MODELS_TO_LNTUNING_TARGET_MODULES_MAPPING = { + "llama": ["input_layernorm", "post_attention_layernorm", "norm"], + "bloom": ["input_layernorm", "post_attention_layernorm", "ln_f"], + "llava": [ + "multi_modal_projector", + "input_layernorm", + "post_attention_layernorm", + "norm", + "embed_tokens", + "lm_head", + ], + "t5": ["layer_norm", "final_layer_norm"], + "mt5": ["layer_norm", "final_layer_norm"], + "bart": ["self_attn_layer_norm", "encoder_attn_layer_norm", "final_layer_norm"], + "gpt2": ["ln_1", "ln_2", "ln_f"], + "blip-2": ["layernorm", "LayerNorm", "final_layer_norm", "self_attn_layer_norm"], + "gptj": ["ln_1", "ln_f"], + "falcon": ["input_layernorm", "post_attention_layernorm", "ln_f"], + "mistral": ["input_layernorm", "post_attention_layernorm", "norm"], + "phi": ["input_layernorm", "final_layernorm"], + "gemma": ["input_layernorm", "post_attention_layernorm", "norm"], + "gemma2": [ + "input_layernorm", + "post_attention_layernorm", + "pre_feedforward_layernorm", + "post_feedforward_layernorm", + "norm", + ], + "gemma3_text": [ + "input_layernorm", + "post_attention_layernorm", + "pre_feedforward_layernorm", + "post_feedforward_layernorm", + "norm", + ], + "qwen2": ["post_attention_layernorm"], + "qwen3": ["post_attention_layernorm"], +} + +TRANSFORMERS_MODELS_TO_HIRA_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() + + +TRANSFORMERS_MODELS_TO_IA3_TARGET_MODULES_MAPPING = { + "t5": ["k", "v", "wo"], + "mt5": ["k", "v", "wi_1"], + "gpt2": ["c_attn", "mlp.c_proj"], + "bloom": ["query_key_value", "mlp.dense_4h_to_h"], + "roberta": ["key", "value", "output.dense"], + "opt": ["q_proj", "k_proj", "fc2"], + "gptj": ["q_proj", "v_proj", "fc_out"], + "gpt_neox": ["query_key_value", "dense_4h_to_h"], + "gpt_neo": ["q_proj", "v_proj", "c_proj"], + "bart": ["q_proj", "v_proj", "fc2"], + "gpt_bigcode": ["c_attn", "mlp.c_proj"], + "llama": ["k_proj", "v_proj", "down_proj"], + "llama4": ["q_proj", "v_proj", "down_proj"], + "mistral": ["k_proj", "v_proj", "down_proj"], + "mixtral": ["k_proj", "v_proj", "w2"], + "bert": ["key", "value", "output.dense"], + "deberta-v2": ["key_proj", "value_proj", "output.dense"], + "deberta": ["in_proj", "output.dense"], + "RefinedWebModel": ["query_key_value", "dense_4h_to_h"], + "RefinedWeb": ["query_key_value", "dense_4h_to_h"], + "falcon": ["query_key_value", "dense_4h_to_h"], + "phi": ["q_proj", "v_proj", "fc2"], + "gemma": ["q_proj", "v_proj", "down_proj"], + "gemma2": ["q_proj", "v_proj", "down_proj"], + "gemma3_text": ["q_proj", "v_proj", "down_proj"], + "qwen2": ["q_proj", "v_proj", "down_proj"], + "qwen3": ["q_proj", "v_proj", "down_proj"], +} + +TRANSFORMERS_MODELS_TO_BEFT_TARGET_MODULES_MAPPING = { + "t5": ["v"], + "mt5": ["v"], + "roberta": ["value"], + "opt": ["v_proj"], + "gptj": ["v_proj"], + "gpt_neo": ["v_proj"], + "bart": ["v_proj"], + "llama": ["v_proj"], + "llama4": ["v_proj"], + "mistral": ["v_proj"], + "mixtral": ["v_proj"], + "bert": ["value"], + "deberta-v2": ["value_proj"], + "phi": ["v_proj"], + "gemma": ["v_proj"], + "gemma2": ["v_proj"], + "gemma3_text": ["v_proj"], + "qwen2": ["v_proj"], + "qwen3": ["v_proj"], +} + +TRANSFORMERS_MODELS_TO_IA3_FEEDFORWARD_MODULES_MAPPING = { + "t5": ["wo"], + "mt5": [], + "gpt2": ["mlp.c_proj"], + "bloom": ["mlp.dense_4h_to_h"], + "roberta": ["output.dense"], + "opt": ["fc2"], + "gptj": ["fc_out"], + "gpt_neox": ["dense_4h_to_h"], + "gpt_neo": ["c_proj"], + "bart": ["fc2"], + "gpt_bigcode": ["mlp.c_proj"], + "llama": ["down_proj"], + "llama4": ["down_proj"], + "mistral": ["down_proj"], + "mixtral": ["w2"], + "bert": ["output.dense"], + "deberta-v2": ["output.dense"], + "deberta": ["output.dense"], + "RefinedWeb": ["dense_4h_to_h"], + "RefinedWebModel": ["dense_4h_to_h"], + "falcon": ["dense_4h_to_h"], + "phi": ["fc2"], + "gemma": ["down_proj"], + "gemma2": ["down_proj"], + "gemma3_text": ["down_proj"], + "qwen2": ["down_proj"], + "qwen3": ["down_proj"], +} + +TRANSFORMERS_MODELS_TO_ADALORA_TARGET_MODULES_MAPPING = { + "t5": ["q", "k", "v", "o", "wi", "wo"], + "mt5": ["q", "k", "v", "o", "wi_0", "wi_1", "wo"], + "bart": ["q_proj", "k_proj", "v_proj", "out_proj", "fc1", "fc2"], + "gpt2": ["c_attn"], + "bloom": ["query_key_value"], + "opt": ["q_proj", "k_proj", "v_proj", "out_proj", "fc1", "fc2"], + "gptj": ["q_proj", "v_proj"], + "gpt_neox": ["query_key_value"], + "gpt_neo": ["q_proj", "v_proj"], + "llama": ["q_proj", "v_proj"], + "llama4": ["q_proj", "v_proj"], + "bert": ["query", "value"], + "roberta": ["query", "key", "value", "dense"], + # "xlm-roberta": ["query", "value"], + # "electra": ["query", "value"], + "deberta-v2": ["query_proj", "key_proj", "value_proj", "dense"], + "gpt_bigcode": ["c_attn"], + "deberta": ["in_proj"], + # "layoutlm": ["query", "value"], + "gemma": ["q_proj", "v_proj"], + "gemma2": ["q_proj", "v_proj"], + "gemma3_text": ["q_proj", "v_proj"], + "gemma4": r".*language_model\..*\.(q_proj|v_proj)", + "qwen2": ["q_proj", "v_proj"], + "qwen3": ["q_proj", "v_proj"], +} + +TRANSFORMERS_MODELS_TO_VBLORA_TARGET_MODULES_MAPPING = { + "t5": ["q", "k", "v", "o", "wi", "wo"], + "mt5": ["q", "k", "v", "o", "wi_0", "wi_1", "wo"], + "bart": ["q_proj", "k_proj", "v_proj", "out_proj", "fc1", "fc2"], + "gpt2": ["c_attn"], + "bloom": ["query_key_value"], + "opt": ["q_proj", "k_proj", "v_proj", "out_proj", "fc1", "fc2"], + "gptj": ["q_proj", "v_proj"], + "gpt_neox": ["query_key_value"], + "gpt_neo": ["q_proj", "v_proj"], + "llama": ["q_proj", "v_proj"], + "llama4": ["q_proj", "v_proj"], + "bert": ["query", "value"], + "roberta": ["query", "value"], + "deberta-v2": ["query_proj", "key_proj", "value_proj", "dense"], + "gpt_bigcode": ["c_attn"], + "deberta": ["in_proj"], + "gemma": ["q_proj", "v_proj"], + "gemma2": ["q_proj", "v_proj"], + "gemma3_text": ["q_proj", "v_proj"], + "gemma4": r".*language_model\..*\.(q_proj|v_proj)", + "qwen2": ["q_proj", "v_proj"], + "qwen3": ["q_proj", "v_proj"], +} + +TRANSFORMERS_MODELS_TO_OSF_TARGET_MODULES_MAPPING = { + "llama": ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj"], + "llama4": ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj"], + "mistral": ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj"], + "mixtral": ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj"], + "gemma": ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj"], + "gemma2": ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj"], + "gemma3_text": ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj"], + "qwen2": ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj"], + "qwen3": ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj"], + "phi": ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj"], + "gpt2": ["c_attn", "c_proj"], + "bloom": ["query_key_value", "dense_4h_to_h"], + "opt": ["q_proj", "k_proj", "v_proj", "out_proj", "fc1", "fc2"], + "gptj": ["q_proj", "k_proj", "v_proj", "out_proj", "fc_in", "fc_out"], + "gpt_neox": ["query_key_value", "dense_4h_to_h"], + "falcon": ["query_key_value", "dense_4h_to_h"], + "gpt_bigcode": ["c_attn", "c_proj"], +} + +TRANSFORMERS_MODELS_TO_WAVEFT_TARGET_MODULES_MAPPING = { + "t5": ["q", "v"], + "mt5": ["q", "v"], + "bart": ["q_proj", "v_proj"], + "gpt2": ["mlp.c_proj"], + "bloom": ["query_key_value"], + "blip-2": ["q", "v", "q_proj", "v_proj"], + "opt": ["q_proj", "v_proj"], + "gptj": ["q_proj", "v_proj"], + "gpt_neox": ["query_key_value"], + "gpt_neo": ["q_proj", "v_proj"], + "bert": ["query", "value"], + "roberta": ["query", "value"], + "xlm-roberta": ["query", "value"], + "electra": ["query", "value"], + "deberta-v2": ["query_proj", "value_proj"], + "deberta": ["in_proj"], + "layoutlm": ["query", "value"], + "llama": ["q_proj", "v_proj"], + "llama4": ["q_proj", "v_proj"], + "chatglm": ["query_key_value"], + "gpt_bigcode": ["mlp.c_proj"], + "mpt": ["Wqkv"], + "RefinedWebModel": ["query_key_value"], + "RefinedWeb": ["query_key_value"], + "falcon": ["query_key_value"], + "codegen": ["qkv_proj"], + "mistral": ["q_proj", "v_proj"], + "mixtral": ["q_proj", "v_proj"], + "stablelm": ["q_proj", "v_proj"], + "phi": ["q_proj", "v_proj", "fc1", "fc2"], + "gemma": ["q_proj", "v_proj"], + "gemma2": ["q_proj", "v_proj"], + "gemma3_text": ["q_proj", "v_proj"], + "gemma4": r".*language_model\..*\.(q_proj|v_proj)", + "qwen2": ["q_proj", "v_proj"], + "qwen3": ["q_proj", "v_proj"], +} + +################## +# MISC CONSTANTS # +################## +WEIGHTS_NAME = "adapter_model.bin" +SAFETENSORS_WEIGHTS_NAME = "adapter_model.safetensors" +CONFIG_NAME = "adapter_config.json" +EMBEDDING_LAYER_NAMES = ["embed_tokens", "lm_head"] +SEQ_CLS_HEAD_NAMES = ["score", "classifier"] +INCLUDE_LINEAR_LAYERS_SHORTHAND = "all-linear" +TOKENIZER_CONFIG_NAME = "tokenizer_config.json" +DUMMY_TARGET_MODULES = "dummy-target-modules" +DUMMY_MODEL_CONFIG = {"model_type": "custom"} + +# If users specify more than this number of target modules, we apply an optimization to try to reduce the target modules +# to a minimal set of suffixes, which makes loading faster. We only apply this when exceeding a certain size since +# otherwise there is no point in optimizing and there is a small chance of bugs in the optimization algorithm, so no +# point in taking unnecessary risks. See #2045 for more context. +MIN_TARGET_MODULES_FOR_OPTIMIZATION = 20 +# dtypes that are allowed to be used for adapter computation +ALLOWED_COMPUTE_DTYPES = (torch.float16, torch.bfloat16, torch.float32) +# float dtypes that should be upcast in the adapter for computation +UPCAST_DTYPES = ("float8_e4m3fn", "float8_e4m3fnuz", "float8_e5m2", "float8_e5m2fnuz", "float8_e8m0fnu") diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/utils/hotswap.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/utils/hotswap.py new file mode 100644 index 0000000000000000000000000000000000000000..68e46c733ec51049899a1475c6ddf14576eb78cb --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/utils/hotswap.py @@ -0,0 +1,643 @@ +# 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 math +import warnings +from operator import attrgetter +from typing import Literal, Optional + +import torch + +from peft.config import PeftConfig +from peft.mapping import PEFT_TYPE_TO_CONFIG_MAPPING, PEFT_TYPE_TO_PREFIX_MAPPING +from peft.tuners.lora import Conv2d, Linear, LoraConfig, LoraLayer + +from .other import get_pattern_key, infer_device +from .peft_types import PeftType +from .save_and_load import _insert_adapter_name_into_state_dict, load_peft_weights + + +# so far only LoRA is supported +CONFIG_KEYS_TO_CHECK = {PeftType.LORA: ["use_rslora", "lora_dropout", "alpha_pattern", "use_dora"]} + + +def _update_scaling(lora_module, adapter_name, scaling=None): + """ + Update the value of the scalings of the LoRA module. + + Takes into consideration that scalings can be tensors from prepare_model_for_compiled_hotswap. + """ + if lora_module.scaling[adapter_name] == scaling: + return + + if isinstance(lora_module.scaling[adapter_name], torch.Tensor): + lora_module.scaling[adapter_name].fill_(scaling) + elif isinstance(lora_module.scaling[adapter_name], (float, int)): + lora_module.scaling[adapter_name] = scaling + else: + raise TypeError( + "Something went wrong when trying to set the new scale value, expected to find the old value to be of type " + f"float or torch.Tensor, got {type(lora_module.scaling[adapter_name])} instead." + ) + + +def _convert_scalings_to_tensor(model) -> bool: + """ + Convert the LoRA scaling values into torch.tensors to prevent recompilation if they change. + + Returns: + bool: + Returns `True` if an appropriate adapter was found, else `False`. + """ + found_adapter = False + for module in model.modules(): + if not isinstance(module, LoraLayer): + continue + + found_adapter = True + scaling = module.scaling + for key, val in scaling.items(): + if isinstance(val, float): + # no need to deal with dtype as scalars are coerced + scaling[key] = torch.tensor(val, device=module.weight.device) + elif not isinstance(val, torch.Tensor): + raise TypeError( + "Something went wrong while trying to convert the scalings, expected to find values of type float " + f"but found {type(val)} instead." + ) + return found_adapter + + +def _get_padded_linear(lora_module: torch.nn.Module, target_rank: int, is_lora_A: bool) -> torch.nn.Linear: + """ + Get a new Linear layer for LoRA with padded weights according to the target rank. + + Args: + lora_module (nn.Module): + The LoRA sub-module (e.g. module.lora_A[adapter_name]). + target_rank (int): + The desired rank to pad to. + is_lora_A (bool): + True if this is the LoRA A matrix, False if LoRA B. + + Returns: + nn.Linear: + A newly created and padded Linear layer. If the rank already fit, the original layer is returned. + """ + weight = lora_module.weight + # For LoRA A, the "rank dimension" is weight.size(0) (out_features). + # For LoRA B, it is weight.size(1) (in_features). + original_rank = weight.size(0) if is_lora_A else weight.size(1) + + # If no padding needed + if original_rank == target_rank: + return lora_module + + if original_rank > target_rank: + raise ValueError( + f"Trying to pad the adapter to the target rank {target_rank}, but the original rank is larger " + f"({original_rank}). This is not possible." + ) + + out_features, in_features = weight.shape + + # lora_A and lora_B are always nn.Linear + if is_lora_A: + # LoRA A affects out_features + padded = torch.zeros(target_rank, in_features, device=weight.device, dtype=weight.dtype) + padded[:original_rank, :] = weight + new_layer = torch.nn.Linear(in_features, target_rank, bias=lora_module.bias is not None) + else: + # LoRA B affects in_features + padded = torch.zeros(out_features, target_rank, device=weight.device, dtype=weight.dtype) + padded[:, :original_rank] = weight + new_layer = torch.nn.Linear(target_rank, out_features, bias=lora_module.bias is not None) + new_layer.weight.requires_grad_(lora_module.weight.requires_grad) + + # Sanity check + if new_layer.weight.shape != padded.shape: + raise ValueError( + "Something went wrong when trying to pad the LoRA Linear weights, the new shape should be " + f"{padded.shape} but {new_layer.weight.shape} was found. Please open an issue on PEFT " + "(https://github.com/huggingface/peft/issues) and report this error." + ) + if (lora_module.bias is not None) and (new_layer.bias.shape != lora_module.bias.shape): + raise ValueError( + "Something went wrong when trying to pad the LoRA Linear bias, the new shape should be " + f"{lora_module.bias.shape} but {new_layer.bias.shape} was found. Please open an issue on PEFT " + "(https://github.com/huggingface/peft/issues) and report this error." + ) + + new_layer.weight.data = padded + # Copy bias if present + if lora_module.bias is not None: + new_layer.bias.data = lora_module.bias.data + + return new_layer + + +def _get_padded_conv2d(lora_module: torch.nn.Module, target_rank: int, is_lora_A: bool) -> torch.nn.Conv2d: + """ + Get a new Conv2d layer for LoRA with padded weights according to the target rank. + + Args: + lora_module (nn.Module): + The LoRA sub-module (e.g. module.lora_A[adapter_name]). + target_rank (int): + The desired rank to pad to. + is_lora_A (bool): + True if this is the LoRA A matrix, False if LoRA B. + + Returns: + nn.Conv2d: + A newly created and padded Conv2d layer. If the rank already fit, the original layer is returned. + """ + weight = lora_module.weight + # For Conv2d: [out_channels, in_channels, kernel_height, kernel_width] + out_channels, in_channels, kh, kw = weight.shape + original_rank = out_channels if is_lora_A else in_channels + + if original_rank == target_rank: + return lora_module + + if original_rank > target_rank: + raise ValueError( + f"Trying to pad the adapter to the target rank {target_rank}, but the original rank is larger " + f"({original_rank}). This is not possible." + ) + + # lora_A and lora_B are always nn.Conv2d + if is_lora_A: + # LoRA A affects out_channels + padded = torch.zeros(target_rank, in_channels, kh, kw, device=weight.device, dtype=weight.dtype) + padded[:out_channels, :, :, :] = weight + new_layer = torch.nn.Conv2d( + in_channels, + target_rank, + kernel_size=lora_module.kernel_size, + stride=lora_module.stride, + padding=lora_module.padding, + bias=lora_module.bias is not None, + groups=lora_module.groups, + ) + else: + # LoRA B affects in_channels + padded = torch.zeros(out_channels, target_rank, kh, kw, device=weight.device, dtype=weight.dtype) + padded[:, :in_channels, :, :] = weight + new_layer = torch.nn.Conv2d( + target_rank, + out_channels, + kernel_size=lora_module.kernel_size, + stride=lora_module.stride, + padding=lora_module.padding, + bias=lora_module.bias is not None, + groups=lora_module.groups, + ) + new_layer.weight.requires_grad_(lora_module.weight.requires_grad) + + # Sanity check + if new_layer.weight.shape != padded.shape: + raise ValueError( + "Something went wrong when trying to pad the LoRA weights, the new shape should be " + f"{padded.shape} but {new_layer.weight.shape} was found. Please open an issue on PEFT " + "(https://github.com/huggingface/peft/issues) and report this error." + ) + if (lora_module.bias is not None) and (new_layer.bias.shape != lora_module.bias.shape): + raise ValueError( + "Something went wrong when trying to pad the LoRA Conv2d bias, the new shape should be " + f"{lora_module.bias.shape} but {new_layer.bias.shape} was found. Please open an issue on PEFT " + "(https://github.com/huggingface/peft/issues) and report this error." + ) + + new_layer.weight.data = padded + # Copy bias if present + if lora_module.bias is not None: + new_layer.bias.data = lora_module.bias.data + + return new_layer + + +def _pad_lora_weights(model: torch.nn.Module, target_rank: int) -> bool: + """ + Pad LoRA weights in a model to a target rank while preserving the original behavior. + + Args: + model (nn.Module): The model containing LoRA modules (with lora_A and lora_B). + target_rank (int): The target rank to pad to. + + Returns: + bool: + Returns `True` if an appropriate adapter was found, else `False`. + """ + found_adapter = False + + for module in model.modules(): + # Decide which pad function to call based on module type + if isinstance(module, Linear): + pad_fn = _get_padded_linear + elif isinstance(module, Conv2d): + pad_fn = _get_padded_conv2d + else: + # Skip any other module types + continue + + # Pad LoRA A + for adapter_name, lora_A_module in module.lora_A.items(): + new_layer = pad_fn(lora_A_module, target_rank=target_rank, is_lora_A=True) + module.lora_A[adapter_name] = new_layer + + # Pad LoRA B + for adapter_name, lora_B_module in module.lora_B.items(): + new_layer = pad_fn(lora_B_module, target_rank=target_rank, is_lora_A=False) + module.lora_B[adapter_name] = new_layer + + found_adapter = True + return found_adapter + + +def prepare_model_for_compiled_hotswap( + model: torch.nn.Module, + *, + target_rank: Optional[int] = None, + config: Optional[LoraConfig | dict[str, LoraConfig]] = None, + check_compiled: Literal["error", "warn", "ignore"] = "error", +) -> None: + """ + Helper function that prepares the model so that it can later be compiled and then used with hot-swapping. + + It is necessary to call this function on the model for hot-swapping to work if both of these are true: + + - the different LoRA adapters have different ranks and/or different alpha values (i.e. scalings) + - you plan to torch.compile the model and want to avoid re-compilation + + It is important to call this function *after* the first LoRA adapter has been loaded (i.e. the one that will be + swapped out) but *before* the model is compiled. + + Even with this function, hot-swapping LoRA adapters that target different layers is still not supported. + + Note: This function modifies the model in-place. If you want to restore the model to its initial state, you will + have to reload it. + + Args: + model (`nn.Module`): + The model with the loaded adapter, before compilation. + target_rank (`int`, *optional*): + The target rank to pad the LoRA weights to. Should be the maximum rank among all LoRA adapters that will be + hot-swapped. If not specified, the target ranks will not be changed. + config (`LoraConfig` or `dict[str, LoraConfig]`, *optional*): + Optionally pass the `LoraConfig`s of the LoRA adapters. If passed, the rank in the configs will be updated + to `target_rank`. + check_compiled (`str`, *optional*, defaults to `"error"`): + How to handle the case when the model is already compiled, which should generally be avoided. The options + are: + - "error" (default): raise an error + - "warn": issue a warning + - "ignore": do nothing + + Raises: + ValueError + If the model is already compiled or if no adpater layer was found, raise an error. + + Example: + + ```py + base_model = ... + model = PeftModel.from_pretrained(base_model, path_adapter_0) + # Prepare the model to allow hotswapping even if ranks/scalings of 2nd adapter differ. + # You can skip this step if all ranks and scalings are identical. + prepare_model_for_compiled_hotswap(model, target_rank=highest_lora_rank) + model = torch.compile(model) + # do inference with adapter 0 + # replace the "default" lora adapter with the new one + hotswap_adapter(model, path_adapter_1, adapter_name="default", torch_device=device) + # do inference with adapter 1 + ``` + + """ + is_compiled = hasattr(model, "_orig_mod") or getattr(model, "_compiled_call_impl", False) + if is_compiled: + if check_compiled == "error": + raise ValueError("Call prepare_model_for_compiled_hotswap *before* compiling the model") + elif check_compiled == "warn": + warnings.warn( + "prepare_model_for_compiled_hotswap was called with a model that is already compiled. This will likely " + "result in re-compilation, hurting performance. Call the function before compiling the model." + ) + elif check_compiled != "ignore": + raise ValueError( + f"check_compiles should be one of 'error', 'warn', or 'ignore', got '{check_compiled}' instead." + ) + + conversion_found_adapter = _convert_scalings_to_tensor(model) + if target_rank is not None: + padding_found_adapter = _pad_lora_weights(model, target_rank=target_rank) + else: + padding_found_adapter = False + + if not (conversion_found_adapter or padding_found_adapter): + raise ValueError( + "No adapter layers found on the model, make sure call `prepare_model_for_compiled_hotswap` after loading " + "the first adapter and before loading the second adapter." + ) + + if not config: + return + if target_rank is None: + return + + if not isinstance(config, dict): + # config can be either a PeftConfig, or a dict of PeftConfigs like PeftModel.peft_config + config = {"dummy": config} + + for lora_config in config.values(): + lora_config.r = target_rank + if lora_config.rank_pattern: + for key in lora_config.rank_pattern: + lora_config.rank_pattern[key] = target_rank + + +def hotswap_adapter_from_state_dict( + model: torch.nn.Module, + state_dict: dict[str, torch.Tensor], + adapter_name: str, + config: LoraConfig, + parameter_prefix: str = "lora_", +): + """ + Swap out the adapter weights from the model with the weights from state_dict. + + As of now, only LoRA is supported. + + This is a low-level function that assumes that the adapters have been checked for compatibility and that the + state_dict has been correctly mapped to work with PEFT. For a high level function that performs this work for you, + use `hotswap_adapter` instead. + + Args: + model (`nn.Module`): + The model with the loaded adapter. + state_dict (`dict[str, torch.Tensor]`): + The state dict of the new adapter, which needs to be compatible (targeting same modules etc.). + adapter_name (`str`): + The name of the adapter that should be hot-swapped, e.g. `"default"`. The name will remain the same after + swapping. + config (`LoraConfig`): + The config of the LoRA adapter. This is used to determine the scaling and rank of the adapter. + parameter_prefix (`str`, *optional*, defaults to `"lora_"`) + The prefix used to identify the adapter's keys in the state dict. For LoRA, this would be `"lora_"` (the + default). + + Raises: + RuntimeError + If the old and the new adapter are not compatible, a RuntimeError is raised. + + """ + # Ensure that all the keys of the new adapter correspond exactly to the keys of the old adapter, otherwise + # hot-swapping is not possible + + # _orig_mod is for torch.compile(model) + is_compiled_wrapper = hasattr(model, "_orig_mod") + # TODO: there is probably a more precise way to identify the adapter keys + missing_keys = {k for k in model.state_dict() if (parameter_prefix in k) and (adapter_name in k)} + unexpected_keys = [] + + # first: dry run, not swapping anything + for key, new_val in state_dict.items(): + try: + old_val = attrgetter(key)(model) + except AttributeError: + unexpected_keys.append(key) + continue + + if is_compiled_wrapper: + missing_keys.remove("_orig_mod." + key) + else: + missing_keys.remove(key) + + # Right now, we don't deal with unexpected keys, i.e. if the adapter being swapped in targeting new layers. We could + # probably add LoRA to these layers ad hoc, but that would not work with compiled models. + if unexpected_keys: + msg = f"Hot swapping the adapter did not succeed, unexpected keys found: {', '.join(unexpected_keys)}." + raise RuntimeError(msg) + + # If the adapter that is being swapped in is missing some keys, this is fine. We just need to ensure that those LoRA + # weights from the previous adapter are set to 0 so that they don't influence the output. We don't need to worry + # about ranks are alphas. + for key in missing_keys: + # in case it's a compiled model + key = key.removeprefix("_orig_mod.") + # get LoRA parent module name by removing the 'lora_*..weight' part + module_name = ".".join(key.split(".")[:-3]) + module = model.get_submodule(module_name) + old_val = attrgetter(key)(model) + old_val.data.fill_(0.0) + + # actual swapping + for key, new_val in state_dict.items(): + # get LoRA parent module name by removing the 'lora_*..weight' part + module_name = ".".join(key.split(".")[:-3]) + module = model.get_submodule(module_name) + + # swap alpha/scaling + r_key = get_pattern_key(config.rank_pattern.keys(), key) + alpha_key = get_pattern_key(config.alpha_pattern.keys(), key) + rank = config.rank_pattern.get(r_key, config.r) + alpha = config.alpha_pattern.get(alpha_key, config.lora_alpha) + if config.use_rslora: + scaling = alpha / math.sqrt(rank) + else: + scaling = alpha / rank + _update_scaling(module, adapter_name=adapter_name, scaling=scaling) + + # swap actual weights + # no need to account for potential _orig_mod in key here, as torch handles that + old_val = attrgetter(key)(model) + new_val = new_val.to(old_val.data.device) + + # 3 options: + # - shapes_match: the new adapter has the same rank as the current tensor (possibly because + # prepare_model_for_compiled_hotswap padded the current tensor to match). + # - new_is_smaller: the new adapter has a smaller rank than the current tensor. This happens either + # when the old adapter had a larger rank, or when the current tensor was padded to a larger + # target_rank. + # - new_is_larger: the new adapter has a larger rank than the current tensor. The parameter shape + # must change, which is only safe when no padded-shape invariant applies (i.e. the model was + # not padded via prepare_model_for_compiled_hotswap). swap_tensors is the only option here. + shapes_match = old_val.shape == new_val.shape + new_is_smaller = (not shapes_match) and all(o >= n for o, n in zip(old_val.shape, new_val.shape)) + new_is_larger = (not shapes_match) and not new_is_smaller + + if shapes_match: + old_val.data.copy_(new_val.data) + elif new_is_smaller: + if old_val.dim() not in (2, 4): + raise NotImplementedError( + f"Trying to hotswap an adapter whose weight has {old_val.dim()} dimensions, but only Conv2d and " + "Linear are supported" + ) + + # Linear or Conv2d: the check for dim 0 or 1 works for both of these layer types + if old_val.shape[0] > new_val.shape[0]: + old_val.data.fill_(0) + old_val.data[: new_val.shape[0]].copy_(new_val.data) + elif old_val.shape[1] > new_val.shape[1]: + old_val.data.fill_(0) + old_val.data[:, : new_val.shape[1]].copy_(new_val.data) + else: + raise ValueError( + f"Incompatible shapes found for LoRA weights {key}: {old_val.shape} vs {new_val.shape}. Please " + "ensure that all ranks are padded to the largest rank among all LoRA adapters by using " + "peft.utils.hotswap.prepare_model_for_compiled_hotswap." + ) + elif new_is_larger: + try: + torch.utils.swap_tensors(old_val, new_val) + except RuntimeError: + # Fallback if swap_tensors is not permitted (e.g. tensor has weakrefs). This still + # rebinds storage and will break inductor if the model is compiled, but growing the + # rank of a compiled-and-padded model is already unsupported; the caller should have + # used prepare_model_for_compiled_hotswap with a sufficient target_rank. + old_val.data = new_val.data + else: + # should be unreachable + raise ValueError( + "Something went wrong during hotswapping, please open an issue on PEFT: " + "https://github.com/huggingface/peft/issues" + ) + + +def check_hotswap_configs_compatible(config0: PeftConfig, config1: PeftConfig) -> None: + """ + Check if two configs are compatible for hot-swapping. + + Only LoRA parameters are checked for now. + + To hot-swap two adapters, their configs must be compatible. Otherwise, the results could be false. E.g. if they use + different alpha values, after hot-swapping, the alphas from the first adapter would still be used with the weights + from the 2nd adapter, which would result in incorrect behavior. There is probably a way to swap these values as + well, but that's not implemented yet, and we need to be careful not to trigger re-compilation if the model is + compiled (so no modification of the dict). + + """ + + if config0.peft_type != config1.peft_type: + msg = f"Incompatible PEFT types found: {config0.peft_type.value} and {config1.peft_type.value}" + raise ValueError(msg) + + if config0.peft_type not in CONFIG_KEYS_TO_CHECK: + msg = ( + f"Hotswapping only supports {', '.join(CONFIG_KEYS_TO_CHECK.keys())} but " + f"{config0.peft_type.value} was passed." + ) + raise ValueError(msg) + config_keys_to_check = CONFIG_KEYS_TO_CHECK[config0.peft_type] + + # TODO: This is a very rough check only for LoRA at the moment. Also, there might be some options that don't + # necessarily require an error. + config0 = config0.to_dict() + config1 = config1.to_dict() + sentinel = object() + for key in config_keys_to_check: + val0 = config0.get(key, sentinel) + val1 = config1.get(key, sentinel) + if val0 != val1: + raise ValueError(f"Configs are incompatible: for {key}, {val0} != {val1}") + + +def hotswap_adapter(model, model_name_or_path, adapter_name, torch_device=None, **kwargs): + """Substitute old adapter data with new adapter data, keeping the rest the same. + + As of now, only LoRA is supported. + + This function is useful when you want to replace the loaded adapter with a new adapter. The adapter name will + remain the same, but the weights and other parameters will be swapped out. + + If the adapters are incomptabile, e.g. targeting different layers or having different alpha values, an error will + be raised. + + Example: + + ```py + >>> import torch + >>> from transformers import AutoModelForCausalLM + >>> from peft import PeftModel + >>> from peft.utils.hotswap import hotswap_adapter + + >>> model_id = ... + >>> inputs = ... + >>> device = ... + >>> model = AutoModelForCausalLM.from_pretrained(model_id).to(device) + + >>> # load lora 0 + >>> model = PeftModel.from_pretrained(model, "path-adapter-0") + >>> model = torch.compile(model) # optionally compile the model + >>> with torch.inference_mode(): + ... output_adapter_0 = model(inputs) + + >>> # replace the "default" lora adapter with the new one + >>> hotswap_adapter(model, "path-adapter-1", adapter_name="default", torch_device=device) + >>> with torch.inference_mode(): + ... output_adapter_1 = model(inputs).logits + ``` + + Args: + model ([`~PeftModel`]): + The PEFT model with the loaded adapter. + model_name_or_path (`str`): + The name or path of the model to load the new adapter from. + adapter_name (`str`): + The name of the adapter to swap, e.g. `"default"`. The name will stay the same after swapping. + torch_device: (`str`, *optional*, defaults to None): + The device to load the new adapter onto. + **kwargs (`optional`): + Additional keyword arguments used for loading the config and weights. + + """ + if torch_device is None: + torch_device = infer_device() + + ############################ + # LOAD CONFIG AND VALIDATE # + ############################ + hf_kwargs = { + "subfolder": kwargs.get("subfolder", None), + "revision": kwargs.get("revision", None), + "cache_dir": kwargs.get("cache_dir", None), + "token": kwargs.get("token", None), + } + if use_auth_token := kwargs.get("use_auth_token", None): + hf_kwargs["use_auth_token"] = use_auth_token + config_cls = PEFT_TYPE_TO_CONFIG_MAPPING[PeftConfig._get_peft_type(model_name_or_path, **hf_kwargs)] + config = config_cls.from_pretrained(model_name_or_path, **kwargs) + # config keys that could affect the model output besides what is determined by the state_dict + check_hotswap_configs_compatible(model.active_peft_config, config) + + state_dict = load_peft_weights(model_name_or_path, device=torch_device, **kwargs) + + ########################### + # LOAD & REMAP STATE_DICT # + ########################### + + parameter_prefix = PEFT_TYPE_TO_PREFIX_MAPPING[config.peft_type] + peft_model_state_dict = _insert_adapter_name_into_state_dict( + state_dict, adapter_name=adapter_name, parameter_prefix=parameter_prefix + ) + + hotswap_adapter_from_state_dict( + model=model, + state_dict=peft_model_state_dict, + adapter_name=adapter_name, + parameter_prefix=parameter_prefix, + config=config, + ) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/utils/incremental_pca.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/utils/incremental_pca.py new file mode 100644 index 0000000000000000000000000000000000000000..de4a7c05174dc436f4c75965ef9585afb480183c --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/utils/incremental_pca.py @@ -0,0 +1,338 @@ +# 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 Optional + +import torch + + +class IncrementalPCA: + """ + An implementation of Incremental Principal Components Analysis (IPCA) that leverages PyTorch for GPU acceleration. + Adapted from https://github.com/scikit-learn/scikit-learn/blob/main/sklearn/decomposition/_incremental_pca.py + + This class provides methods to fit the model on data incrementally in batches, and to transform new data based on + the principal components learned during the fitting process. + + Args: + n_components (int, optional): Number of components to keep. If `None`, it's set to the minimum of the + number of samples and features. Defaults to None. + copy (bool): If False, input data will be overwritten. Defaults to True. + batch_size (int, optional): The number of samples to use for each batch. Only needed if self.fit is called. + If `None`, it's inferred from the data and set to `5 * n_features`. Defaults to None. + svd_driver (str, optional): name of the cuSOLVER method to be used for torch.linalg.svd. This keyword + argument only works on CUDA inputs. Available options are: None, gesvd, gesvdj, and gesvda. Defaults to + None. + lowrank (bool, optional): Whether to use torch.svd_lowrank instead of torch.linalg.svd which can be faster. + Defaults to False. + lowrank_q (int, optional): For an adequate approximation of n_components, this parameter defaults to + n_components * 2. + lowrank_niter (int, optional): Number of subspace iterations to conduct for torch.svd_lowrank. + Defaults to 4. + lowrank_seed (int, optional): Seed for making results of torch.svd_lowrank reproducible. + """ + + def __init__( + self, + n_components: Optional[int] = None, + copy: Optional[bool] = True, + batch_size: Optional[int] = None, + svd_driver: Optional[str] = None, + lowrank: bool = False, + lowrank_q: Optional[int] = None, + lowrank_niter: int = 4, + lowrank_seed: Optional[int] = None, + ): + self.n_components = n_components + self.copy = copy + self.batch_size = batch_size + self.svd_driver = svd_driver + self.lowrank = lowrank + self.lowrank_q = lowrank_q + self.lowrank_niter = lowrank_niter + self.lowrank_seed = lowrank_seed + + self.n_features_ = None + + if self.lowrank: + self._validate_lowrank_params() + + def _validate_lowrank_params(self): + if self.lowrank_q is None: + if self.n_components is None: + raise ValueError("n_components must be specified when using lowrank mode with lowrank_q=None.") + self.lowrank_q = self.n_components * 2 + elif self.lowrank_q < self.n_components: + raise ValueError("lowrank_q must be greater than or equal to n_components.") + + def _svd_fn_full(self, X): + return torch.linalg.svd(X, full_matrices=False, driver=self.svd_driver) + + def _svd_fn_lowrank(self, X): + seed_enabled = self.lowrank_seed is not None + with torch.random.fork_rng(enabled=seed_enabled): + if seed_enabled: + torch.manual_seed(self.lowrank_seed) + U, S, V = torch.svd_lowrank(X, q=self.lowrank_q, niter=self.lowrank_niter) + return U, S, V.mH + + def _validate_data(self, X) -> torch.Tensor: + """ + Validates and converts the input data `X` to the appropriate tensor format. + + Args: + X (torch.Tensor): Input data. + + Returns: + torch.Tensor: Converted to appropriate format. + """ + valid_dtypes = [torch.float32, torch.float64] + + if not isinstance(X, torch.Tensor): + X = torch.tensor(X, dtype=torch.float32) + elif self.copy: + X = X.clone() + + n_samples, n_features = X.shape + if self.n_components is None: + pass + elif self.n_components > n_features: + raise ValueError( + f"n_components={self.n_components} invalid for n_features={n_features}, " + "need more rows than columns for IncrementalPCA processing." + ) + elif self.n_components > n_samples: + raise ValueError( + f"n_components={self.n_components} must be less or equal to the batch number of samples {n_samples}" + ) + + if X.dtype not in valid_dtypes: + X = X.to(torch.float32) + + return X + + @staticmethod + def _incremental_mean_and_var( + X, last_mean, last_variance, last_sample_count + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Computes the incremental mean and variance for the data `X`. + + Args: + X (torch.Tensor): The batch input data tensor with shape (n_samples, n_features). + last_mean (torch.Tensor): The previous mean tensor with shape (n_features,). + last_variance (torch.Tensor): The previous variance tensor with shape (n_features,). + last_sample_count (torch.Tensor): The count tensor of samples processed before the current batch. + + Returns: + Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: Updated mean, variance tensors, and total sample count. + """ + if X.shape[0] == 0: + return last_mean, last_variance, last_sample_count + + if last_sample_count > 0: + if last_mean is None: + raise ValueError("last_mean should not be None if last_sample_count > 0.") + if last_variance is None: + raise ValueError("last_variance should not be None if last_sample_count > 0.") + + new_sample_count = torch.tensor([X.shape[0]], device=X.device) + updated_sample_count = last_sample_count + new_sample_count + + if last_mean is None: + last_sum = torch.zeros(X.shape[1], dtype=torch.float64, device=X.device) + else: + last_sum = last_mean * last_sample_count + + new_sum = X.sum(dim=0, dtype=torch.float64) + + updated_mean = (last_sum + new_sum) / updated_sample_count + + T = new_sum / new_sample_count + temp = X - T + correction = temp.sum(dim=0, dtype=torch.float64).square() + temp.square_() + new_unnormalized_variance = temp.sum(dim=0, dtype=torch.float64) + new_unnormalized_variance -= correction / new_sample_count + if last_variance is None: + updated_variance = new_unnormalized_variance / updated_sample_count + else: + last_unnormalized_variance = last_variance * last_sample_count + last_over_new_count = last_sample_count.double() / new_sample_count + updated_unnormalized_variance = ( + last_unnormalized_variance + + new_unnormalized_variance + + last_over_new_count / updated_sample_count * (last_sum / last_over_new_count - new_sum).square() + ) + updated_variance = updated_unnormalized_variance / updated_sample_count + + return updated_mean, updated_variance, updated_sample_count + + @staticmethod + def _svd_flip(u, v, u_based_decision=True) -> tuple[torch.Tensor, torch.Tensor]: + """ + Adjusts the signs of the singular vectors from the SVD decomposition for deterministic output. + + This method ensures that the output remains consistent across different runs. + + Args: + u (torch.Tensor): Left singular vectors tensor. + v (torch.Tensor): Right singular vectors tensor. + u_based_decision (bool, optional): If True, uses the left singular vectors to determine the sign flipping. + Defaults to True. + + Returns: + Tuple[torch.Tensor, torch.Tensor]: Adjusted left and right singular vectors tensors. + """ + if u_based_decision: + max_abs_cols = torch.argmax(torch.abs(u), dim=0) + signs = torch.sign(u[max_abs_cols, range(u.shape[1])]) + else: + max_abs_rows = torch.argmax(torch.abs(v), dim=1) + signs = torch.sign(v[range(v.shape[0]), max_abs_rows]) + u *= signs[: u.shape[1]].view(1, -1) + v *= signs.view(-1, 1) + return u, v + + def fit(self, X, check_input=True): + """ + Fits the model with data `X` using minibatches of size `batch_size`. + + Args: + X (torch.Tensor): The input data tensor with shape (n_samples, n_features). + check_input (bool, optional): If True, validates the input. Defaults to True. + + Returns: + IncrementalPCA: The fitted IPCA model. + """ + if check_input: + X = self._validate_data(X) + n_samples, n_features = X.shape + if self.batch_size is None: + self.batch_size = 5 * n_features + + for batch in self.gen_batches(n_samples, self.batch_size, min_batch_size=self.n_components or 0): + self.partial_fit(X[batch], check_input=False) + + return self + + def partial_fit(self, X, check_input=True): + """ + Incrementally fits the model with batch data `X`. + + Args: + X (torch.Tensor): The batch input data tensor with shape (n_samples, n_features). + check_input (bool, optional): If True, validates the input. Defaults to True. + + Returns: + IncrementalPCA: The updated IPCA model after processing the batch. + """ + first_pass = not hasattr(self, "components_") + + if check_input: + X = self._validate_data(X) + n_samples, n_features = X.shape + + # Initialize attributes to avoid errors during the first call to partial_fit + if first_pass: + self.mean_ = None # Will be initialized properly in _incremental_mean_and_var based on data dimensions + self.var_ = None # Will be initialized properly in _incremental_mean_and_var based on data dimensions + self.n_samples_seen_ = torch.tensor([0], device=X.device) + self.n_features_ = n_features + if not self.n_components: + self.n_components = min(n_samples, n_features) + + if n_features != self.n_features_: + raise ValueError( + "Number of features of the new batch does not match the number of features of the first batch." + ) + + col_mean, col_var, n_total_samples = self._incremental_mean_and_var( + X, self.mean_, self.var_, self.n_samples_seen_ + ) + + if first_pass: + X -= col_mean + else: + col_batch_mean = torch.mean(X, dim=0) + X -= col_batch_mean + mean_correction_factor = torch.sqrt((self.n_samples_seen_.double() / n_total_samples) * n_samples) + mean_correction = mean_correction_factor * (self.mean_ - col_batch_mean) + X = torch.vstack( + ( + self.singular_values_.view((-1, 1)) * self.components_, + X, + mean_correction, + ) + ) + + if self.lowrank: + U, S, Vt = self._svd_fn_lowrank(X) + else: + U, S, Vt = self._svd_fn_full(X) + U, Vt = self._svd_flip(U, Vt, u_based_decision=False) + explained_variance = S**2 / (n_total_samples - 1) + explained_variance_ratio = S**2 / torch.sum(col_var * n_total_samples) + + self.n_samples_seen_ = n_total_samples + self.components_ = Vt[: self.n_components] + self.singular_values_ = S[: self.n_components] + self.mean_ = col_mean + self.var_ = col_var + self.explained_variance_ = explained_variance[: self.n_components] + self.explained_variance_ratio_ = explained_variance_ratio[: self.n_components] + if self.n_components not in (n_samples, n_features): + self.noise_variance_ = explained_variance[self.n_components :].mean() + else: + self.noise_variance_ = torch.tensor(0.0, device=X.device) + return self + + def transform(self, X) -> torch.Tensor: + """ + Applies dimensionality reduction to `X`. + + The input data `X` is projected on the first principal components previously extracted from a training set. + + Args: + X (torch.Tensor): New data tensor with shape (n_samples, n_features) to be transformed. + + Returns: + torch.Tensor: Transformed data tensor with shape (n_samples, n_components). + """ + X = X - self.mean_ + return torch.mm(X.double(), self.components_.T).to(X.dtype) + + @staticmethod + def gen_batches(n: int, batch_size: int, min_batch_size: int = 0): + """Generator to create slices containing `batch_size` elements from 0 to `n`. + + The last slice may contain less than `batch_size` elements, when `batch_size` does not divide `n`. + + Args: + n (int): Size of the sequence. + batch_size (int): Number of elements in each batch. + min_batch_size (int, optional): Minimum number of elements in each batch. Defaults to 0. + + Yields: + slice: A slice of `batch_size` elements. + """ + start = 0 + for _ in range(int(n // batch_size)): + end = start + batch_size + if end + min_batch_size > n: + continue + yield slice(start, end) + start = end + if start < n: + yield slice(start, n) diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/utils/integrations.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/utils/integrations.py new file mode 100644 index 0000000000000000000000000000000000000000..f4cd59528bbac425cddc40c3e8a5d7d8185cc6ae --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/utils/integrations.py @@ -0,0 +1,295 @@ +# 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 functools +from contextlib import contextmanager +from dataclasses import dataclass +from typing import Literal, Optional + +import packaging.version +import torch +import transformers +from torch import nn + + +@dataclass +class TpInfo: + tp_plan: dict[str, str] + device_mesh: torch.distributed.DeviceMesh + tp_size: int + + +def check_deepspeed_zero3_enabled() -> bool: + if packaging.version.parse(transformers.__version__) >= packaging.version.parse("4.33.0"): + from transformers.integrations import is_deepspeed_zero3_enabled + else: + from transformers.deepspeed import is_deepspeed_zero3_enabled + return is_deepspeed_zero3_enabled() + + +@contextmanager +def gather_params_ctx(param, modifier_rank: Optional[int] = 0, fwd_module: torch.nn.Module = None): + """Call DeepSpeed GatheredParameters context manager if DeepSpeed is enabled, otherwise do nothing.""" + + if not check_deepspeed_zero3_enabled(): + yield + return + + import deepspeed + + with deepspeed.zero.GatheredParameters(param, modifier_rank=modifier_rank, fwd_module=fwd_module): + yield + return + + +def dequantize_module_weight(module: torch.nn.Module) -> torch.nn.Parameter: + """ + Helper function to dequantize a quantized weight. + + This function should be extended if more quantization schemes are added to the library. + + If the weight is not quantized, it will be returned as is. + """ + if hasattr(module, "W_q"): # For handling HQQ quantized weight + weight = module.dequantize() + return weight + elif type(module.weight).__module__.startswith("torchao."): + # check for torchao without requiring any torchao imports + weight = module.weight.dequantize() + return weight + + weight = module.weight + if not isinstance(weight, torch.nn.Parameter): + if isinstance(weight, torch.Tensor): + # this is an FSDP-specific edge case + return weight # type: ignore + raise TypeError(f"Input weight should be of type nn.Parameter, got {type(weight)} instead") + + cls_name = weight.__class__.__name__ + if cls_name not in ("Params4bit", "Int8Params"): + return weight + + quant_state = getattr(module, "state", None) + device = weight.device + is_cpu = device.type == torch.device("cpu").type + weight = dequantize_bnb_weight(weight, state=quant_state) # no-op if not bnb + if is_cpu: + # dequantize_bnb_weight for 8bit moves the device in-place, thus we need to move it back to CPU if necessary + module.weight = module.weight.to(device) + return weight + + +def dequantize_bnb_weight(weight: torch.nn.Parameter, state=None): + """Helper function to dequantize 4bit or 8bit bnb weights.""" + import bitsandbytes as bnb + + device = weight.device + + cls_name = weight.__class__.__name__ + if cls_name == "Params4bit": + dequantized = bnb.functional.dequantize_4bit(weight.data, weight.quant_state) + return dequantized + + # 8bit case + if state is None: + raise ValueError( + "No `state` was passed for bnb 8bit quantized weights. Please open an issue on the PEFT repository and " + "report the error: https://github.com/huggingface/peft/issues" + ) + + if state.SCB is None: + state.SCB = weight.SCB + + if hasattr(bnb.functional, "int8_vectorwise_dequant"): + # Use bitsandbytes API if available (requires v0.45.0+) + dequantized = bnb.functional.int8_vectorwise_dequant(weight.data, state.SCB) + else: + # Multiply by (scale/127) to dequantize. + dequantized = weight.data * state.SCB.view(-1, 1) * 7.874015718698502e-3 + + return dequantized + + +def get_bnb_param_type(param: torch.nn.Parameter) -> Literal[False, "4bit", "8bit"]: + """Returns '4bit' or '8bit' if bitsandbytes parameter, else False""" + if param.__class__.__name__ == "Params4bit": + return "4bit" + if param.__class__.__name__ == "Int8Params": + return "8bit" + return False + + +# adapted from: +# https://github.com/huggingface/transformers/blob/eab6c491d439e83d5e31c660df6f7e36592eb0a2/src/transformers/generation/utils.py#L1617-L1643 +def get_layer_device_map(model): + """ + Derive the device map for the layers of the model. + """ + main_device = next(d for d in model.hf_device_map.values() if d not in ["cpu", "disk"]) + + execution_device_map = { + name: main_device if device in ["cpu", "disk"] else device for name, device in model.hf_device_map.items() + } + + if execution_device_map is None: + return None + + if len(execution_device_map) == 1 and "" in execution_device_map: + return {idx: execution_device_map[""] for idx in range(model.config.num_hidden_layers)} + + layer_device_map = {} + for layer in execution_device_map: + for idx in range(model.config.num_hidden_layers): + if f".{idx}." in f"{layer}.": + layer_device_map[idx] = execution_device_map[layer] + break + for idx in range(model.config.num_hidden_layers): + if idx not in layer_device_map: + raise RuntimeError(f"layer {idx} has not been mapped to a device.") + return layer_device_map + + +# adapted from: +# https://github.com/huggingface/transformers/blob/eab6c491d439e83d5e31c660df6f7e36592eb0a2/src/transformers/cache_utils.py#L1159-L1179 +def map_cache_to_layer_device_map(model, cache) -> None: + """ + Ensure that the key and value cache of the model are on the same device as their corresponding layers. + """ + if not (isinstance(cache, transformers.Cache) and hasattr(model, "hf_device_map")): + return + + if isinstance(cache, transformers.EncoderDecoderCache): + map_cache_to_layer_device_map(model, cache.self_attention_cache) + return + + layer_device_map = get_layer_device_map(model) + for idx in range(model.config.num_hidden_layers): + layer_device = layer_device_map[idx] + if hasattr(cache, "layers"): + # new transformers uses cache.layers (>v4.55) + layer = cache.layers[idx] + layer.keys = layer.keys.to(layer_device) + layer.values = layer.values.to(layer_device) + else: + # old transformers uses cache.{key,value}_cache (<=v4.55) + # TODO: remove if we drop support for transformers <= 4.55 + cache.key_cache[idx] = cache.key_cache[idx].to(layer_device) + cache.value_cache[idx] = cache.value_cache[idx].to(layer_device) + + +################################## +# START: ADAPTED FROM ACCELERATE # +################################## +# +# Modified to support explicitly skipping layer initialization for faster switching between layer states +# (necessary for supporting `nn.MultiHeadAttention` adapters) + + +@contextmanager +def init_empty_weights(include_buffers: bool | None = None): + # adapted from accelerate.big_modeling.py + with _init_on_device(torch.device("meta"), include_buffers=include_buffers) as f: + yield f + + +@contextmanager +def _init_on_device(device: torch.device, include_buffers: bool | None = None): + # adapted from accelerate.big_modeling.py + old_register_parameter = nn.Module.register_parameter + old_register_buffer = nn.Module.register_buffer + + def register_empty_parameter(module, name, param): + # This works because torch first initializes the parameters with torch.empty, thus not assigning any new memory. + # Then the parameter is moved to meta device before reset_parameters() is called, which then operates on the + # meta device, making any subsequent calls to initialization methods no-ops. + old_register_parameter(module, name, param) + if (param is not None) and (getattr(_init_on_device, "_skip", False) is not True): + param_cls = type(module._parameters[name]) + kwargs = module._parameters[name].__dict__ + kwargs["requires_grad"] = param.requires_grad + module._parameters[name] = param_cls(module._parameters[name].to(device), **kwargs) + + def register_empty_buffer(module, name, buffer, persistent=True): + old_register_buffer(module, name, buffer, persistent=persistent) + if buffer is not None: + module._buffers[name] = module._buffers[name].to(device) + + # Patch tensor creation + if include_buffers: + tensor_constructors_to_patch = { + torch_function_name: getattr(torch, torch_function_name) + for torch_function_name in ["empty", "zeros", "ones", "full"] + } + else: + tensor_constructors_to_patch = {} + + def patch_tensor_constructor(fn): + def wrapper(*args, **kwargs): + kwargs["device"] = device + return fn(*args, **kwargs) + + return wrapper + + try: + nn.Module.register_parameter = register_empty_parameter + if include_buffers: + nn.Module.register_buffer = register_empty_buffer + for torch_function_name in tensor_constructors_to_patch.keys(): + setattr(torch, torch_function_name, patch_tensor_constructor(getattr(torch, torch_function_name))) + yield + finally: + nn.Module.register_parameter = old_register_parameter + if include_buffers: + nn.Module.register_buffer = old_register_buffer + for torch_function_name, old_torch_function in tensor_constructors_to_patch.items(): + setattr(torch, torch_function_name, old_torch_function) + + +@contextmanager +def _skip_init_on_device(): + # context manager to skip the _init_on_device context manager + old_val = getattr(_init_on_device, "_skip", False) + try: + _init_on_device._skip = True + yield + finally: + _init_on_device._skip = old_val + + +def skip_init_on_device(func): + """ + Ignore the init_on_device context manager when calling the decorated function. + + This is a narrow use decorator that allows us to avoid initializing on meta device even when we're inside the + init_empty_weights context. + + """ + + # The need for this functionality arose when working on MultiheadAttention, where we have to call _restore_weights + # repeatedly as parametes are overwritten and need to be re-registered. When using low_cpu_mem_usage=True, as + # register_parameter is patched inside of the init_empty_weights context, this would result in those parameters + # suddenly being moved to meta device. Using this decorator allows us to avoid this. + @functools.wraps(func) + def wrapper(*args, **kwargs): + with _skip_init_on_device(): + return func(*args, **kwargs) + + return wrapper + + +####### +# END # +####### diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/utils/loftq_utils.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/utils/loftq_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ea69b73368a304eed3130a6e292bdd4f0c88325b --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/utils/loftq_utils.py @@ -0,0 +1,427 @@ +# 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. + +# Reference code: https://github.com/yxli2123/LoftQ/blob/main/utils.py +# Reference paper: https://huggingface.co/papers/2310.08659 + +from __future__ import annotations + +import os +import warnings +from collections.abc import Callable +from typing import Optional, Union + +import torch +from accelerate.utils.memory import clear_device_cache +from huggingface_hub import snapshot_download +from huggingface_hub.errors import HFValidationError, LocalEntryNotFoundError +from safetensors import SafetensorError, safe_open +from transformers.utils import cached_file +from transformers.utils.hub import get_checkpoint_shard_files + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available, is_xpu_available + + +# TODO for PEFT 0.20, remove NFQuantizer in favor of bnb 4bit quantization. +class NFQuantizer: + def __init__(self, num_bits=2, device="cuda", method="normal", block_size=64, *args, **kwargs): + super().__init__(*args, **kwargs) + + warnings.warn( + "NFQuantizer is deprecated and is going to be removed in PEFT 0.20. Consider using " + "alternative quantization libraries for nf{2,4,8} quantization.", + category=DeprecationWarning, + ) + + self.num_bits = num_bits + self.device = device + self.method = method + self.block_size = block_size + if self.method == "normal": + self.norm_lookup_table = self.create_normal_map(num_bits=self.num_bits) + self.norm_lookup_table = self.norm_lookup_table.to(device) + elif self.method == "uniform": + self.norm_lookup_table = self.create_uniform_map(num_bits=self.num_bits) + self.norm_lookup_table = self.norm_lookup_table.to(device) + else: + raise NotImplementedError("Other quantization methods not supported yet.") + + @staticmethod + def create_uniform_map(symmetric=False, num_bits=4): + if symmetric: + # print("symmetric uniform quantization") + negative = torch.linspace(-1, 0, 2 ** (num_bits - 1)) + positive = torch.linspace(0, 1, 2 ** (num_bits - 1)) + table = torch.cat([negative, positive[1:]]) + else: + # print("asymmetric uniform quantization") + table = torch.linspace(-1, 1, 2**num_bits) + return table + + @staticmethod + def create_normal_map(offset=0.9677083, symmetric=False, num_bits=2): + try: + from scipy.stats import norm + except ImportError: + raise ImportError("The required package 'scipy' is not installed. Please install it to continue.") + + variations = 2**num_bits + if symmetric: + v = norm.ppf(torch.linspace(1 - offset, offset, variations + 1)).tolist() + values = [] + for index in range(len(v) - 1): + values.append(0.5 * v[index] + 0.5 * v[index + 1]) + v = values + else: + # one more positive value, this is an asymmetric type + v1 = norm.ppf(torch.linspace(offset, 0.5, variations // 2 + 1)[:-1]).tolist() + v2 = [0] + v3 = (-norm.ppf(torch.linspace(offset, 0.5, variations // 2)[:-1])).tolist() + v = v1 + v2 + v3 + + values = torch.Tensor(v) + values = values.sort().values + values /= values.max() + return values + + def quantize_tensor(self, weight): + max_abs = torch.abs(weight).max() + weight_normed = weight / max_abs + + weight_normed_expanded = weight_normed.unsqueeze(-1) + + # Reshape L to have the same number of dimensions as X_expanded + L_reshaped = torch.tensor(self.norm_lookup_table).reshape(1, -1) + + # Calculate the absolute difference between X_expanded and L_reshaped + abs_diff = torch.abs(weight_normed_expanded - L_reshaped) + + # Find the index of the minimum absolute difference for each element + qweight = torch.argmin(abs_diff, dim=-1) + return qweight, max_abs + + def dequantize_tensor(self, qweight, max_abs): + qweight_flatten = qweight.flatten() + + weight_normed = self.norm_lookup_table[qweight_flatten] + weight = weight_normed * max_abs + + weight = weight.reshape(qweight.shape) + + return weight + + def quantize_block(self, weight): + if len(weight.shape) != 2: + raise ValueError(f"Only support 2D matrix, but your input has {len(weight.shape)} dimensions.") + if weight.shape[0] * weight.shape[1] % self.block_size != 0: + raise ValueError( + f"Weight with shape ({weight.shape[0]} x {weight.shape[1]}) " + f"is not dividable by block size {self.block_size}." + ) + + M, N = weight.shape + device = weight.device + + # Quantization + weight_flatten = weight.flatten() # (M*N, ) + weight_block = weight_flatten.reshape(-1, self.block_size) # (L, B), L = M * N / B + if self.method == "normal": + weight_max = weight_block.abs().max(dim=-1)[0] # (L, 1) + elif self.method == "uniform": + weight_max = weight_block.mean(dim=-1) + 2.5 * weight_block.std(dim=-1) + else: + raise NotImplementedError("Method not supported yet.") + weight_max = weight_max.unsqueeze(-1) + weight_divabs = weight_block / weight_max # (L, B) + weight_divabs = weight_divabs.unsqueeze(-1) # (L, B, 1) + L_reshaped = self.norm_lookup_table.reshape(1, -1) # (1, 2**K) + + abs_diff = torch.abs(weight_divabs - L_reshaped) # (L, B, 2**K) + qweight = torch.argmin(abs_diff, dim=-1) # (L, B) + + # Pack multiple k-bit into uint8 + qweight = qweight.reshape(-1, 8 // self.num_bits) + qweight_pack = torch.zeros((M * N // 8 * self.num_bits, 1), dtype=torch.uint8, device=device) + + # data format example: + # [1, 0, 3, 2] or [01, 00, 11, 10] -> [10110001], LIFO + for i in range(8 // self.num_bits): + qweight[:, i] = qweight[:, i] << i * self.num_bits + qweight_pack[:, 0] |= qweight[:, i] + + return qweight_pack, weight_max, weight.shape + + def dequantize_block(self, qweight, weight_max, weight_shape): + # unpack weight + device = qweight.device + weight = torch.zeros((qweight.shape[0], 8 // self.num_bits), dtype=torch.float32, device=device) + for i in range(8 // self.num_bits): + lookup_table_idx = qweight.to(torch.long) % 2**self.num_bits # get the most right 2 bits + lookup_table_idx = lookup_table_idx.to(torch.long) + weight[:, i] = self.norm_lookup_table[lookup_table_idx].squeeze() + qweight = qweight >> self.num_bits # right shift 2 bits of the original data + + weight_block = weight.reshape(-1, self.block_size) + weight = weight_block * weight_max + weight = weight.reshape(weight_shape) + + return weight + + +def _low_rank_decomposition(weight, reduced_rank=32): + """ + :param weight: The matrix to decompose, of shape (H, W) :param reduced_rank: the final rank :return: + """ + matrix_dimension = len(weight.size()) + if matrix_dimension != 2: + raise ValueError(f"Only support 2D matrix, but your input has {matrix_dimension} dimensions.") + + # Use SVD to decompose a matrix, default full_matrices is False to save parameters + U, S, Vh = torch.linalg.svd(weight, full_matrices=False) + + L = U @ (torch.sqrt(torch.diag(S)[:, 0:reduced_rank])) + R = torch.sqrt(torch.diag(S)[0:reduced_rank, :]) @ Vh + + return {"L": L, "R": R, "U": U, "S": S, "Vh": Vh, "reduced_rank": reduced_rank} + + +@torch.no_grad() +def loftq_init(weight: Union[torch.Tensor, torch.nn.Parameter], num_bits: int, reduced_rank: int, num_iter=1): + if is_bnb_available(): + import bitsandbytes as bnb + else: + raise ValueError("bitsandbytes is not available, please install it to use LoftQ.") + + if num_bits not in [4, 8]: + raise ValueError("Only nf4 and int8 quantization is supported") + if num_iter <= 0: + raise ValueError("Number of iterations must be greater than 0") + + device = weight.device + dtype = weight.dtype + if not is_bnb_4bit_available() and num_bits == 4: + # TODO for PEFT 0.20 remove NFQuantizer invocation and throw an exception + quantizer = NFQuantizer(num_bits=num_bits, device=device, method="normal", block_size=64) + compute_device = device + warnings.warn( + "Native support for nf4 is being deprecated with PEFT 0.20. Please install a recent version of bitsandbytes.", + category=DeprecationWarning, + ) + else: + compute_device = "xpu" if is_xpu_available() else "cuda" + + weight = weight.to(device=compute_device, dtype=torch.float32) + res = weight.clone() + for i in range(num_iter): + clear_device_cache() + # Quantization + if num_bits == 4 and is_bnb_4bit_available(): + qweight = bnb.nn.Params4bit( + res.to("cpu"), requires_grad=False, compress_statistics=False, quant_type="nf4" + ).to(compute_device) + dequantized_weight = bnb.functional.dequantize_4bit(qweight.data, qweight.quant_state) + elif num_bits == 4: + quantized_weight, max_abs, shape = quantizer.quantize_block(res) + dequantized_weight = quantizer.dequantize_block(quantized_weight, max_abs, shape) + elif num_bits == 8: + qweight = bnb.nn.Int8Params(res.to("cpu"), requires_grad=False).to(device) + dequantized_weight = bnb.functional.int8_vectorwise_dequant(qweight.data, qweight.SCB).to(compute_device) + + res = weight - dequantized_weight + + # Decompose the residual by SVD + output = _low_rank_decomposition(res, reduced_rank=reduced_rank) + L, R, reduced_rank = output["L"], output["R"], output["reduced_rank"] + + # don't prepare the residual if we're at the end + if i + 1 == num_iter: + break + + res = weight - torch.mm(L, R) + + lora_A, lora_B = R, L + + return dequantized_weight.to(device=device, dtype=dtype), lora_A, lora_B + + +@torch.no_grad() +def _loftq_init_new(qweight, weight, num_bits: int, reduced_rank: int): + import bitsandbytes as bnb + + if num_bits != 4: + raise ValueError("Only 4 bit quantization supported at the moment.") + if not is_bnb_4bit_available(): + raise ValueError("bitsandbytes 4bit quantization is not available.") + + compute_device = "xpu" if is_xpu_available() else "cuda" + dequantized_weight = bnb.functional.dequantize_4bit(qweight.data, qweight.quant_state) + + weight = weight.to(device=compute_device, dtype=torch.float32) + residual = weight - dequantized_weight + clear_device_cache() + # Decompose the residualidual by SVD + output = _low_rank_decomposition(residual, reduced_rank=reduced_rank) + L, R, reduced_rank = output["L"], output["R"], output["reduced_rank"] + return R, L + + +class _SafetensorLoader: + """ + Simple utility class that loads tensors with safetensors from a single file or sharded files. + + Takes care of file name normalization etc. + + """ + + def __init__(self, peft_model, model_path): + if model_path is None: + try: + model_path = snapshot_download(peft_model.base_model.config._name_or_path, local_files_only=True) + except (AttributeError, HFValidationError) as exc: + raise ValueError( + "The provided model does not appear to be a transformers model or is a local model. In this case, " + "you must pass the model_path argument that points to the safetensors file." + ) from exc + except LocalEntryNotFoundError as exc: + raise ValueError( + "The model.safetensors file must be present on disk, but it could not be found." + ) from exc + + suffix = "model.safetensors" + if not model_path.endswith(suffix): + model_path = os.path.join(model_path, suffix) + + self.model_path = model_path + self.base_model_prefix = getattr(peft_model.get_base_model(), "base_model_prefix", None) + self.prefix = "base_model.model." + self.is_sharded = False + self.weight_map = None + + if not os.path.exists(model_path): + # check if the file is sharded + par_dir = model_path.rpartition(os.path.sep)[0] + try: + resolved_archive_file, sharded_metadata = get_checkpoint_shard_files( + par_dir, cached_file(par_dir, "model.safetensors.index.json") + ) + except OSError as exc: + raise FileNotFoundError( + f"Could not find file for {model_path}, ensure that there is a (sharded) safetensors file of the model." + ) from exc + + self.is_sharded = True + # maps from 'model-X-of-Y.safetensors' to full file path + file_map = {k.rpartition(os.path.sep)[-1]: k for k in resolved_archive_file} + self.weight_map = {k: file_map[v] for k, v in sharded_metadata["weight_map"].items()} + + def get_tensor(self, name): + if not self.is_sharded: + file_path = self.model_path + else: + file_path = self.weight_map[name] + + with safe_open(file_path, framework="pt", device="cpu") as f: + try: + tensor = f.get_tensor(name) + except SafetensorError as exc: + # no matching key found, we probably need to remove the base model prefix + if self.base_model_prefix: + # remove 1 extra character for "." + name = name[len(self.base_model_prefix) + 1 :] + tensor = f.get_tensor(name) + else: + raise + return tensor + + +@torch.no_grad() +def replace_lora_weights_loftq( + peft_model, + model_path: Optional[str] = None, + adapter_name: str = "default", + callback: Optional[Callable[[torch.nn.Module, str], bool]] = None, +): + """ + Replace the LoRA weights of a model quantized with bitsandbytes, using the LoftQ technique. + + The replacement is done on the fly by loading in the non-quantized weights from a locally stored safetensors model + file and initializing the LoRA weights such that the quantization error between the original and quantized weights + is minimized. + + As lazy loading is not possible with pickle, normal PyTorch checkpoint files cannot be supported. + + Depending on the model size, calling this function may take some time to finish. + + Args: + peft_model (`PeftModel`): + The model to replace the weights of. Must be a quantized PEFT model with LoRA layers. + model_path (`Optional[str]`): + The path to the model safetensors file. If the model is a Hugging Face model, this will be inferred from + the model's config. Otherwise, it must be provided. + adapter_name (`str`): + The name of the adapter to replace the weights of. The default adapter name is "default". + callback (`Optional[Callable[[PeftModel, str], bool]]`): + A callback function that will be called after each module is replaced. The callback function should take + the model and the name of the current module as input and return a boolean indicating whether the + replacement should be kept. If the callback returns False, the replacement will be rolled back. This can be + very useful to confirm that the LoftQ initialization actually decreases the quantization error of the + model. As an example, this callback could generate logits for given input and compare it with the logits + from the original, non-quanitzed model with the same input, and only return `True` if there is an + improvement. As this is a greedy optimization, it's possible that calling this function multiple times + yields incremental improvements. + """ + if not is_bnb_4bit_available(): + raise ValueError("bitsandbytes must be installed and the model must be quantized in 4bits.") + + from peft.tuners.lora import Linear4bit + + # model_path = _check_model_path_loftq(model_path, peft_model) + prefix = "base_model.model." + any_match = False + safetensor_loader = _SafetensorLoader(peft_model, model_path) + + # if too slow, consider adding tqdm as an option + for name, module in peft_model.named_modules(): + if not isinstance(module, Linear4bit): + continue + + if not name.startswith(prefix): + raise TypeError("The passed model does not appear to be a valid PeftModel") + + any_match = True + name = name[len(prefix) :] + tensor = safetensor_loader.get_tensor(name + ".weight") + + reduced_rank = module.r[adapter_name] + lora_A, lora_B = _loftq_init_new(module.weight, tensor, num_bits=4, reduced_rank=reduced_rank) + if not callback: + module.lora_A[adapter_name].weight.data = lora_A + module.lora_B[adapter_name].weight.data = lora_B + continue + + lora_A_before = module.lora_A[adapter_name].weight.data + lora_B_before = module.lora_B[adapter_name].weight.data + + module.lora_A[adapter_name].weight.data = lora_A + module.lora_B[adapter_name].weight.data = lora_B + should_replace = callback(peft_model, name) + if not should_replace: + # roll back + module.lora_A[adapter_name].weight.data = lora_A_before + module.lora_B[adapter_name].weight.data = lora_B_before + + del lora_A_before, lora_B_before + + if not any_match: + raise ValueError("No bnb LoRA module found on the model") diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/utils/merge_utils.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/utils/merge_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..27e3f7e7b1ee04e157a9817a06624f345e619170 --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/utils/merge_utils.py @@ -0,0 +1,268 @@ +# 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 typing import Literal + +import torch + + +def reshape_weight_task_tensors(task_tensors: torch.Tensor, weights: torch.Tensor) -> torch.Tensor: + """ + Reshapes `weights` to match the shape of `task_tensors` by unsqeezing in the remaining dimenions. + + Args: + task_tensors (`torch.Tensor`): The tensors that will be used to reshape `weights`. + weights (`torch.Tensor`): The tensor to be reshaped. + + Returns: + `torch.Tensor`: The reshaped tensor. + """ + new_shape = weights.shape + (1,) * (task_tensors.dim() - weights.dim()) + weights = weights.view(new_shape) + return weights + + +def magnitude_based_pruning(tensor: torch.Tensor, density: float) -> torch.Tensor: + """ + Prune the smallest values of the task tensors and retain the top-k values based on the specified fraction + `density`. + + Args: + tensor (`torch.Tensor`):The tensor to prune. + density (`float`):The fraction of values to preserve. Should be in [0,1]. + + Returns: + `torch.Tensor`: The tensor with the pruned weights. + """ + mask = torch.zeros_like(tensor).reshape(-1) + k = int(density * tensor.numel()) + top_k = torch.topk(tensor.abs().reshape(-1), k=k, largest=True) + mask[top_k[1]] = 1 + return tensor * mask.reshape(tensor.shape) + + +def random_pruning(tensor: torch.Tensor, density: float, rescale: bool) -> torch.Tensor: + """ + Prune random values based on the specified fraction `density`. + + Args: + tensor (`torch.Tensor`):The tensor to prune. + density (`float`):The fraction of values to preserve. Should be in [0,1]. + rescale (`bool`):Whether to rescale the result to preserve the expected value of the original tensor. + + Returns: + `torch.Tensor`: The pruned tensor. + """ + mask = torch.bernoulli(torch.full_like(input=tensor, fill_value=density)) + pruned_tensor = tensor * mask + if rescale: + pruned_tensor = pruned_tensor / density + return pruned_tensor + + +def prune( + tensor: torch.Tensor, density: float, method: Literal["magnitude", "random"], rescale: bool = False +) -> torch.Tensor: + """ + Prune the values of task tensors based on the `method`. + + Args: + tensor (`torch.Tensor`):The tensor to prune. + density (`float`):The fraction of values to preserve. Should be in [0,1]. + method (`str`):The method to use to prune. Should be one of ["magnitude", "random"]. + rescale (`bool`):Whether to rescale the result to preserve the expected value of the original tensor. + + Returns: + `torch.Tensor`: The pruned tensor. + """ + if density >= 1: + warnings.warn(f"The density {density} is greater than or equal to 1, no pruning will be performed.") + return tensor + elif density < 0: + raise ValueError(f"Density should be >= 0, got {density}") + if method == "magnitude": + return magnitude_based_pruning(tensor, density) + elif method == "random": + return random_pruning(tensor, density, rescale=rescale) + else: + raise ValueError(f"Unknown method {method}") + + +def calculate_majority_sign_mask( + tensor: torch.Tensor, method: Literal["total", "frequency"] = "total" +) -> torch.Tensor: + """ + Get the mask of the majority sign across the task tensors. Task tensors are stacked on dimension 0. + + Args: + tensor (`torch.Tensor`):The tensor to get the mask from. + method (`str`):The method to use to get the mask. Should be one of ["total", "frequency"]. + + Returns: + `torch.Tensor`: The majority sign mask. + """ + + sign = tensor.sign() + if method == "total": + sign_magnitude = tensor.sum(dim=0) + elif method == "frequency": + sign_magnitude = sign.sum(dim=0) + else: + raise RuntimeError(f'Unimplemented mask method "{method}"') + majority_sign = torch.where(sign_magnitude >= 0, 1, -1) + return sign == majority_sign + + +def disjoint_merge(task_tensors: torch.Tensor, majority_sign_mask: torch.Tensor) -> torch.Tensor: + """ + Merge the task tensors using disjoint merge. + + Args: + task_tensors (`torch.Tensor`):The task tensors to merge. + majority_sign_mask (`torch.Tensor`):The mask of the majority sign across the task tensors. + + Returns: + `torch.Tensor`: The merged tensor. + """ + mixed_task_tensors = (task_tensors * majority_sign_mask).sum(dim=0) + num_params_preserved = majority_sign_mask.sum(dim=0) + return mixed_task_tensors / torch.clamp(num_params_preserved, min=1.0) + + +def task_arithmetic(task_tensors: list[torch.Tensor], weights: torch.Tensor) -> torch.Tensor: + """ + Merge the task tensors using `task arithmetic`. + + Args: + task_tensors(`List[torch.Tensor]`):The task tensors to merge. + weights (`torch.Tensor`):The weights of the task tensors. + + Returns: + `torch.Tensor`: The merged tensor. + """ + task_tensors = torch.stack(task_tensors, dim=0) + # weighted task tensors + weights = reshape_weight_task_tensors(task_tensors, weights) + weighted_task_tensors = task_tensors * weights + mixed_task_tensors = weighted_task_tensors.sum(dim=0) + return mixed_task_tensors + + +def magnitude_prune(task_tensors: list[torch.Tensor], weights: torch.Tensor, density: float) -> torch.Tensor: + """ + Merge the task tensors using `task arithmetic`. + + Args: + task_tensors(`List[torch.Tensor]`):The task tensors to merge. + weights (`torch.Tensor`):The weights of the task tensors. + density (`float`): The fraction of values to preserve. Should be in [0,1]. + + Returns: + `torch.Tensor`: The merged tensor. + """ + # sparsify + task_tensors = [prune(tensor, density, method="magnitude") for tensor in task_tensors] + task_tensors = torch.stack(task_tensors, dim=0) + # weighted task tensors + weights = reshape_weight_task_tensors(task_tensors, weights) + weighted_task_tensors = task_tensors * weights + mixed_task_tensors = weighted_task_tensors.sum(dim=0) + return mixed_task_tensors + + +def ties( + task_tensors: list[torch.Tensor], + weights: torch.Tensor, + density: float, + majority_sign_method: Literal["total", "frequency"] = "total", +) -> torch.Tensor: + """ + Merge the task tensors using `ties`. + + Args: + task_tensors(`List[torch.Tensor]`):The task tensors to merge. + weights (`torch.Tensor`):The weights of the task tensors. + density (`float`):The fraction of values to preserve. Should be in [0,1]. + majority_sign_method (`str`): + The method to use to get the majority sign mask. Should be one of ["total", "frequency"]. + + Returns: + `torch.Tensor`: The merged tensor. + """ + # sparsify + task_tensors = [prune(tensor, density, method="magnitude") for tensor in task_tensors] + task_tensors = torch.stack(task_tensors, dim=0) + # Elect Sign + majority_sign_mask = calculate_majority_sign_mask(task_tensors, method=majority_sign_method) + # weighted task tensors + weights = reshape_weight_task_tensors(task_tensors, weights) + weighted_task_tensors = task_tensors * weights + # Disjoint Merge + mixed_task_tensors = disjoint_merge(weighted_task_tensors, majority_sign_mask) + return mixed_task_tensors + + +def dare_linear(task_tensors: list[torch.Tensor], weights: torch.Tensor, density: float) -> torch.Tensor: + """ + Merge the task tensors using `dare linear`. + + Args: + task_tensors(`List[torch.Tensor]`):The task tensors to merge. + weights (`torch.Tensor`):The weights of the task tensors. + density (`float`):The fraction of values to preserve. Should be in [0,1]. + + Returns: + `torch.Tensor`: The merged tensor. + """ + # sparsify + task_tensors = [prune(tensor, density, method="random", rescale=True) for tensor in task_tensors] + task_tensors = torch.stack(task_tensors, dim=0) + # weighted task tensors + weights = reshape_weight_task_tensors(task_tensors, weights) + weighted_task_tensors = task_tensors * weights + mixed_task_tensors = weighted_task_tensors.sum(dim=0) + return mixed_task_tensors + + +def dare_ties( + task_tensors: list[torch.Tensor], + weights: torch.Tensor, + density: float, + majority_sign_method: Literal["total", "frequency"] = "total", +) -> torch.Tensor: + """ + Merge the task tensors using `dare ties`. + + Args: + task_tensors(`List[torch.Tensor]`):The task tensors to merge. + weights (`torch.Tensor`):The weights of the task tensors. + density (`float`):The fraction of values to preserve. Should be in [0,1]. + majority_sign_method (`str`): + The method to use to get the majority sign mask. Should be one of ["total", "frequency"]. + + Returns: + `torch.Tensor`: The merged tensor. + """ + # sparsify + task_tensors = [prune(tensor, density, method="random", rescale=True) for tensor in task_tensors] + task_tensors = torch.stack(task_tensors, dim=0) + # Elect Sign + majority_sign_mask = calculate_majority_sign_mask(task_tensors, method=majority_sign_method) + # weighted task tensors + weights = reshape_weight_task_tensors(task_tensors, weights) + weighted_task_tensors = task_tensors * weights + # Disjoint Merge + mixed_task_tensors = disjoint_merge(weighted_task_tensors, majority_sign_mask) + return mixed_task_tensors diff --git a/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/utils/other.py b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/utils/other.py new file mode 100644 index 0000000000000000000000000000000000000000..4cc720c4a5b429f3ec7c1786d4fcafa67463c03c --- /dev/null +++ b/tasks/tasksmith-749ff8d440e1/environment/source/src/peft/utils/other.py @@ -0,0 +1,1767 @@ +# 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 copy +import functools +import inspect +import os +import re +import warnings +from collections.abc import Sequence +from contextlib import nullcontext +from operator import attrgetter +from typing import Any, Optional, Union + +import accelerate +import torch +import transformers +from accelerate import FullyShardedDataParallelPlugin +from accelerate.hooks import add_hook_to_module, remove_hook_from_module +from accelerate.utils import is_npu_available, is_xpu_available +from huggingface_hub import file_exists +from huggingface_hub.errors import EntryNotFoundError, HFValidationError +from packaging import version +from safetensors.torch import storage_ptr, storage_size +from transformers import PreTrainedModel + +from ..import_utils import is_gptqmodel_available, is_torch_tpu_available, is_transformers_ge_v5_1_0 +from .constants import ( + CONFIG_NAME, + EMBEDDING_LAYER_NAMES, + INCLUDE_LINEAR_LAYERS_SHORTHAND, + SAFETENSORS_WEIGHTS_NAME, + TRANSFORMERS_MODELS_TO_ADALORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_ADAMSS_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_BEFT_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_BOFT_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_C3A_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_DELORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_FOURIERFT_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_GRALORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_HRA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_IA3_FEEDFORWARD_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_IA3_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_LILY_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_LNTUNING_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_LOHA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_LOKR_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_MISS_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_OFT_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_PEANUT_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_POLY_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING, + TRANSFORMERS_MODELS_TO_PSOFT_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_PVERA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_RANDLORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_ROAD_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_SHIRA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_TINYLORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_VBLORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_VERA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_WAVEFT_TARGET_MODULES_MAPPING, + WEIGHTS_NAME, + bloom_model_postprocess_past_key_value, + starcoder_model_postprocess_past_key_value, +) + + +mlu_available = False +if version.parse(accelerate.__version__) >= version.parse("0.29.0"): + from accelerate.utils import is_mlu_available + + mlu_available = is_mlu_available() + +__all__ = [ + "CONFIG_NAME", + "EMBEDDING_LAYER_NAMES", + "INCLUDE_LINEAR_LAYERS_SHORTHAND", + "SAFETENSORS_WEIGHTS_NAME", + "TRANSFORMERS_MODELS_TO_ADALORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_ADAMSS_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_BEFT_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_BOFT_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_C3A_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_DELORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_FOURIERFT_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_GRALORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_HRA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_IA3_FEEDFORWARD_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_IA3_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_LILY_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_LNTUNING_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_LOHA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_LOKR_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_MISS_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_OFT_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_PEANUT_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_POLY_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING", + "TRANSFORMERS_MODELS_TO_PSOFT_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_PVERA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_RANDLORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_ROAD_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_SHIRA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_TINYLORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_VBLORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_VERA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_WAVEFT_TARGET_MODULES_MAPPING", + "WEIGHTS_NAME", + "bloom_model_postprocess_past_key_value", + "starcoder_model_postprocess_past_key_value", +] + + +# Get current device name based on available devices +def infer_device() -> str: + if torch.cuda.is_available(): + return "cuda" + elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available(): + return "mps" + elif mlu_available: + return "mlu" + elif is_xpu_available(): + return "xpu" + elif is_npu_available(): + return "npu" + return "cpu" + + +def prepare_model_for_kbit_training(model, use_gradient_checkpointing=True, gradient_checkpointing_kwargs=None): + r""" + Note this method only works for `transformers` models. + + This method wraps the entire protocol for preparing a model before running a training. This includes: + 1- Cast the layernorm in fp32 2- making output embedding layer require grads 3- Add the upcasting of the lm + head to fp32 4- Freezing the base model layers to ensure they are not updated during training + + + Args: + model (`transformers.PreTrainedModel`): + The loaded model from `transformers` + use_gradient_checkpointing (`bool`, *optional*, defaults to `True`): + If True, use gradient checkpointing to save memory at the expense of slower backward pass. + gradient_checkpointing_kwargs (`dict`, *optional*, defaults to `None`): + Keyword arguments to pass to the gradient checkpointing function, please refer to the documentation of + `torch.utils.checkpoint.checkpoint` for more details about the arguments that you can pass to that method. + Note this is only available in the latest transformers versions (> 4.34.1). + """ + loaded_in_kbit = getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_loaded_in_4bit", False) + is_gptq_quantized = getattr(model, "quantization_method", None) == "gptq" + is_aqlm_quantized = getattr(model, "quantization_method", None) == "aqlm" + is_eetq_quantized = getattr(model, "quantization_method", None) == "eetq" + is_torchao_quantized = getattr(model, "quantization_method", None) == "torchao" + is_hqq_quantized = getattr(model, "quantization_method", None) == "hqq" or getattr(model, "hqq_quantized", False) + + if gradient_checkpointing_kwargs is None: + gradient_checkpointing_kwargs = {} + + for name, param in model.named_parameters(): + # freeze base model's layers + param.requires_grad = False + + if ( + not is_gptq_quantized + and not is_aqlm_quantized + and not is_eetq_quantized + and not is_hqq_quantized + and not is_torchao_quantized + ): + # cast all non INT8 parameters to fp32 + for param in model.parameters(): + if ( + (param.dtype == torch.float16) or (param.dtype == torch.bfloat16) + ) and param.__class__.__name__ != "Params4bit": + param.data = param.data.to(torch.float32) + + if ( + loaded_in_kbit + or is_gptq_quantized + or is_aqlm_quantized + or is_eetq_quantized + or is_hqq_quantized + or is_torchao_quantized + ) and use_gradient_checkpointing: + # When having `use_reentrant=False` + gradient_checkpointing, there is no need for this hack + if "use_reentrant" not in gradient_checkpointing_kwargs or gradient_checkpointing_kwargs["use_reentrant"]: + # For backward compatibility + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + else: + + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + # To support older transformers versions, check if the model supports gradient_checkpointing_kwargs + _supports_gc_kwargs = "gradient_checkpointing_kwargs" in list( + inspect.signature(model.gradient_checkpointing_enable).parameters + ) + + if not _supports_gc_kwargs and len(gradient_checkpointing_kwargs) > 0: + warnings.warn( + "gradient_checkpointing_kwargs is not supported in this version of transformers. The passed kwargs will be ignored." + " if you want to use that feature, please upgrade to the latest version of transformers.", + FutureWarning, + ) + + gc_enable_kwargs = ( + {} if not _supports_gc_kwargs else {"gradient_checkpointing_kwargs": gradient_checkpointing_kwargs} + ) + + # enable gradient checkpointing for memory efficiency + model.gradient_checkpointing_enable(**gc_enable_kwargs) + return model + + +# copied from transformers.models.bart.modeling_bart +def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int) -> torch.Tensor: + """ + Shift input ids one token to the right. + + Args: + input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): input ids + pad_token_id (`int`): The id of the `padding` token. + decoder_start_token_id (`int`): The id of the `start` token. + """ + shifted_input_ids = input_ids.new_zeros(input_ids.shape) + shifted_input_ids[:, 1:] = input_ids[:, :-1].clone() + shifted_input_ids[:, 0] = decoder_start_token_id + + if pad_token_id is None: + raise ValueError("self.model.config.pad_token_id has to be defined.") + # replace possible -100 values in labels by `pad_token_id` + shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id) + + return shifted_input_ids + + +def _set_layer_requires_grad(layer, requires_grad: bool) -> None: + """Set requires_grad on all leaf parameters of a layer. + + This handles the FSDP case where params may be non-leaf tensors (wrapped in DTensors). Only leaf tensors can have + their requires_grad flag toggled, so non-leaf tensors are silently skipped + + Args: + layer: A module, parameter or tensor + requires_grad: enable or disable gradients + """ + if isinstance(layer, (torch.nn.Parameter, torch.Tensor)): + if layer.is_leaf: + layer.requires_grad_(requires_grad) + else: + for param in layer.parameters(): + if param.is_leaf: + param.requires_grad_(requires_grad) + + +class AuxiliaryTrainingWrapper(torch.nn.Module): + """Wrap a specific module so that it can be trained and saved in a way that is tangential to how + PEFT normally works, e.g. fully training a classification layer instead of using an adapter. + + """ + + # All names of layers that may contain adapter (trainable) weights + adapter_layer_names: tuple[str, ...] = () + # All names of other parameters that may contain adapter-related parameters + other_param_names: tuple[str, ...] = () + # List all merged adapters + merged_adapters: list[str] = [] + + def __init__(self, module_to_save, adapter_name, **kwargs): + """Extra kwargs will be passed to `self.init_modules` and `self.update`.""" + super().__init__() + self.original_module = module_to_save + self._active_adapter = [adapter_name] + self._disable_adapters = False + self._adapters = set() + + self.init_modules(adapter_name, **kwargs) + + self.update(adapter_name, **kwargs) + self.check_module() + + def init_modules(self, adapter_name, **kwargs): + """A place to initialize PyTorch modules in `__init__` before the call to `self.update()`.""" + raise NotImplementedError + + def _get_available_adapters(self) -> set[str]: + """Return all adapter names that can be found on this module.""" + raise NotImplementedError + + def _error_message_name(self): + """Returns a user friendly identifier for error messages, e.g. for type compatibility error messages from + `check_module()` so that the user can backtrack where the error comes from. A generic "training wrapper" is + less helpful than "modules_to_save", for example. + """ + return "training wrapper" + + def check_module(self): + """Perform some sanity checks on the module to ensure that it works""" + # Try to anticipate some modules that users could try to target that would not work. + # Note: It's not possible to check hasattr(module, "forward"), since that returns True for ModuleDict and + # ModuleList, even though their forward methods cannot be called + forbidden_classes = (torch.nn.ModuleDict, torch.nn.ModuleList, torch.nn.ParameterDict, torch.nn.ParameterList) + if isinstance(self.original_module, forbidden_classes): + cls_name = self.original_module.__class__ + raise TypeError(f"{self._error_message_name()} cannot be applied to modules of type {cls_name}") + + # local import to avoid circular import + from peft.tuners.tuners_utils import BaseTunerLayer + + if isinstance(self.original_module, BaseTunerLayer): + # e.g. applying a training wrapper to a lora layer makes no sense + cls_name = self.original_module.__class__ + raise TypeError(f"{self._error_message_name()} cannot be applied to modules of type {cls_name}") + + @property + def disable_adapters(self) -> bool: + # use a property to ensure that disable_adapters is not set directly, instead use the enable_adapters method + return self._disable_adapters + + @property + def active_adapter(self) -> Union[list[str], str]: + # use a property to ensure that active_adapter is not set directly, instead use the set_adapter method + return self._active_adapter + + @property + def active_adapters(self) -> list[str]: + if isinstance(self._active_adapter, str): + return [self._active_adapter] + return self._active_adapter + + def _hasattr_wrapped(self, name, modules): + """Infrastructure to enable the implementing class to delegate attributes to other modules. + Returns True if the implementing class knows how to handle attribute `name`. + + Gets passed `modules` which is PyTorch's internal list of assigned modules from `nn.Module`. + """ + return False + + def _getattr_wrapped(self, name, modules): + """If `_hasattr_wrapped` returns True for `name`, then this function should return the corresponding + value associated with `name`. + """ + return + + def __getattr__(self, name: str): + # Note: This whole method may seem overly complex at first but PyTorch messes with __getattr__ in a way that + # requires very careful handling to avoid infinite recursion. + try: + return super().__getattr__(name) + except AttributeError: + pass + + if "_modules" not in self.__dict__: + raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'") + + # Could not find the attribute the PyTorch way. So let's check if it's an attribute on the + # original_module or the module further down (e.g., `modules_to_save[active_adapter]`). + modules = self.__dict__["_modules"] + if self.disable_adapters or (not self.active_adapters): + # no PEFT adapter is active, thus refer to original module + return getattr(self.original_module, name) + elif self._hasattr_wrapped(name, modules): + return self._getattr_wrapped(name, modules) + + # For some reason, there is no module corresponding to the active adapter; this should normally not be + # reached and exists as a failsafe (otherwise, a KeyError would be raised) + raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'") + + def update(self, adapter_name, **kwargs): + """Called when this instance should be part of an adapter's training. + Adds the given adapter to the list of adapters that this instance is training along with. + + Additional kwargs are expected to be the same kwargs that are also passed for initializing this class. + """ + if adapter_name not in self._adapters: + self._adapters.add(adapter_name) + + def _create_new_hook(self, old_hook): + r""" + Creates a new hook based on the old hook. Use it only if you know what you are doing ! + """ + old_hook_cls = getattr(accelerate.hooks, old_hook.__class__.__name__) + old_hook_attr = old_hook.__dict__ + filtered_old_hook_attr = {} + old_hook_init_signature = inspect.signature(old_hook_cls.__init__) + for k in old_hook_attr.keys(): + if k in old_hook_init_signature.parameters: + filtered_old_hook_attr[k] = old_hook_attr[k] + new_hook = old_hook_cls(**filtered_old_hook_attr) + return new_hook + + def _check_forward_args(self, *args, **kwargs): + """Check if the arguments are compatible with the configs and state of the model""" + adapter_names = kwargs.get("adapter_names", None) + if adapter_names is None or not args: + return + + x = args[0] + if len(x) != len(adapter_names): + msg = ( + "Length of `adapter_names` should be the same as the number of inputs, but got " + f"{len(adapter_names)} and {len(x)} respectively." + ) + raise ValueError(msg) + + def _forward_wrapped(self, *args: Any, **kwargs: Any) -> torch.Tensor: + raise NotImplementedError + + def _forward_wrapped_mixed_batch( + self, x: torch.Tensor, active_adapter: str, *args: Any, **kwargs: Any + ) -> torch.Tensor: + raise NotImplementedError + + def _forward_wrapped_passthrough(self, *args: Any, **kwargs: Any) -> torch.Tensor: + """The forward call when no adapter is involved in the forward computation, only the base model""" + raise NotImplementedError + + def _mixed_batch_forward( + self, input: 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. + + SUPPORTED_MODULES = (torch.nn.Linear, torch.nn.Embedding, torch.nn.Conv1d, torch.nn.Conv2d, torch.nn.Conv3d) + + module_names = ", ".join([module.__name__ for module in SUPPORTED_MODULES]) + + if not isinstance(self.original_module, SUPPORTED_MODULES): + raise TypeError(f"Mixed batching is only supported for the following modules: {module_names}.") + + 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]) + + results = [0 for _ in range(len(input))] + + for i, active_adapter in enumerate(unique_adapters): + sub_batch = input[sub_batch_indices_list[i]] + + if active_adapter == "__base__": + output = self.original_module(sub_batch, *args, **kwargs) + else: + output = self._forward_wrapped_mixed_batch(sub_batch, active_adapter, *args, **kwargs) + + for index, j in enumerate(sub_batch_indices_list[i]): + results[j] = output[index] + + return torch.stack(results) + + def forward(self, *args, **kwargs): + self._check_forward_args(*args, **kwargs) + adapter_names = kwargs.pop("adapter_names", None) + + if self.disable_adapters or any(adapter not in self._adapters for adapter in self.active_adapters): + return self._forward_wrapped_passthrough(*args, **kwargs) + + if adapter_names is None: + return self._forward_wrapped(*args, **kwargs) + return self._mixed_batch_forward(*args, adapter_names=adapter_names, **kwargs) + + def enable_adapters(self, enabled: bool): + """Toggle the enabling and disabling of adapters + + Args: + enabled (bool): True to enable adapters, False to disable adapters + """ + if enabled: + self._disable_adapters = False + else: + self._disable_adapters = True + + def check_set_adapter(self, adapter_name: str | list[str]) -> str | None: + """Helper function to check if the given adapter(s) can be set. + + Return the name of the adapter to be set or None if no adapter should be set. + """ + raise NotImplementedError + + def set_adapter(self, adapter_names: Union[str, list[str]], inference_mode: bool = False) -> None: + """Set the active adapter + + Note: This only deals with active_adapters, not with requires_grad. If the latter needs changing, handle it via + the subclass. + + Args: + adapter_names (str or list[str]): + The name(s) of the adapter(s) to set as active + inference_mode (bool, optional): + Whether the activated adapter should be frozen (i.e. `requires_grad=False`). Default is False. + """ + if isinstance(adapter_names, str): + self._active_adapter = adapter_names + else: + self._active_adapter = [] + for adapter_name in adapter_names: + if adapter_name not in self._adapters: + raise ValueError(f"Adapter {adapter_name} not found in {self._adapters}") + + self._active_adapter.append(adapter_name) + + def delete_adapter(self, adapter_name: str, new_active_adapters: Optional[list[str]]) -> None: + """Delete an adapter from the layer, set a new active adapter if necessary""" + raise NotImplementedError + + def set_requires_grad(self, adapter_names: str | Sequence[str], requires_grad: bool = True) -> None: + """ + Enable or disable gradients on the given adapter(s). + + Args: + adapter_name (`str` or `Sequence[str]`): + The name of the adapter(s) whose gradients should be enabled/disabled. + requires_grad (`bool`, *optional*) + Whether to enable (`True`, default) or disable (`False`). + """ + if isinstance(adapter_names, str): + adapter_names_set = {adapter_names} + else: + adapter_names_set = set(adapter_names) + + for layer_name in self.adapter_layer_names: + # use attrgetter, as it resolves `.` in the attribute name + module_dict = attrgetter(layer_name)(self) + for key, layer in module_dict.items(): + if key in adapter_names_set: + _set_layer_requires_grad(layer, requires_grad) + + def adapter_state_dict(self, adapter_name): + """Return the state dict of this module for a given adapter.""" + raise NotImplementedError + + def adapter_state_dict_load_map(self, adapter_name): + """Return a mapping from the key present in disk-loaded state dict + and how it should be represented in the loaded model's state dict. + + The default should be a 1:1 mapping but it is important to define a mapping as it also serves as the + ground-truth for which keys are supposed to be loaded from a saved state dict. + """ + raise NotImplementedError + + def unload_and_optionally_merge_module( + self, merge: bool, safe_merge: bool, adapter_names: Optional[list[str]] + ) -> torch.nn.Module: + """Handles unloading when called from PEFT models. Returns the wrapped module + and handles merging onto the wrapped module if requested. + """ + raise NotImplementedError + + +class ModulesToSaveWrapper(AuxiliaryTrainingWrapper): + """Wraps a module that is supposed to be trained (i.e. `requires_grad_(True)`) and saved after training.""" + + # All names of layers that may contain adapter (trainable) weights + adapter_layer_names: tuple[str, ...] = ("modules_to_save",) + + def __init__(self, module_to_save, adapter_name, tied_module=None): + super().__init__(module_to_save, adapter_name, tied_module=tied_module) + + def init_modules(self, adapter_name, **kwargs): + # we treat each adapter separately, so we have multiple adapters, same (copied) module for each + self.modules_to_save = torch.nn.ModuleDict({}) + + def _error_message_name(self): + return "modules_to_save" + + def _forward_wrapped(self, *args, **kwargs): + if not self.active_adapters: + return self._forward_wrapped_passthrough(*args, **kwargs) + return self.modules_to_save[self.active_adapters[0]](*args, **kwargs) + + def _forward_wrapped_mixed_batch(self, x, active_adapter, *args, **kwargs): + return self.modules_to_save[active_adapter](x, *args, **kwargs) + + def _forward_wrapped_passthrough(self, *args, **kwargs): + return self.original_module(*args, **kwargs) + + def _hasattr_wrapped(self, name, modules): + # this method is only called if there is at least one active adapter + return self.active_adapters[0] in modules["modules_to_save"] + + def _getattr_wrapped(self, name, modules): + return getattr(modules["modules_to_save"][self.active_adapters[0]], name) + + def update(self, adapter_name, tied_module=None, **kwargs): + super().update(adapter_name) + + context_manager = nullcontext() + for _, param in self.original_module.named_parameters(): + num_params = param.numel() + # if using DS Zero 3 and the weights are initialized empty + if num_params == 0 and hasattr(param, "ds_numel"): + import deepspeed + + context_manager = deepspeed.zero.GatheredParameters(self.original_module.parameters(), modifier_rank=0) + break + + if adapter_name not in self.modules_to_save: + with context_manager: + if tied_module: + new_linear = torch.nn.Linear(*tied_module.weight.shape, bias=False) + new_linear.weight = tied_module.weight + + self.modules_to_save[adapter_name] = new_linear + else: + self.modules_to_save[adapter_name] = copy.deepcopy(self.original_module) + + if hasattr(self.modules_to_save[adapter_name], "_hf_hook"): + old_hook = self.modules_to_save[adapter_name]._hf_hook + new_hook = self._create_new_hook(old_hook) + remove_hook_from_module(self.modules_to_save[adapter_name]) + add_hook_to_module(self.modules_to_save[adapter_name], new_hook) + + self.original_module.requires_grad_(False) + + # note that there currently cannot be more than one active adapter for the same layer with modules to save + # since there would be no clear way to decide which adapter's weights are the correct ones. therefore we + # assume that there is only one active adapter. this precondition is enforced by _set_adapter. + if adapter_name == self.active_adapter: + _set_layer_requires_grad(self.modules_to_save[adapter_name], True) + + def enable_adapters(self, enabled: bool): + """Takes care of setting the required_grad flag on the modules_to_save. + If adapters are enabled, gradients for the modules_to_save are required as well. + """ + super().enable_adapters(enabled) + + if enabled: + for adapter_name in self.active_adapters: + _set_layer_requires_grad(self.modules_to_save[adapter_name], True) + else: + for module in self.modules_to_save.values(): + _set_layer_requires_grad(module, False) + + def check_set_adapter(self, adapter_name: str | list[str]) -> str | None: + """Helper function to check if the given adapter(s) can be set. + + Return the name of the adapter to be set or None if no adapter should be set. + """ + if isinstance(adapter_name, str): + return adapter_name + + # adapter_name is a list of str + if len(adapter_name) == 0: + raise ValueError("Please specify at least one adapter to set") + + adapter_names_in_module = [n for n in adapter_name if n in self.modules_to_save] + + if len(adapter_names_in_module) > 1: + raise ValueError(f"Only one adapter can be set at a time for {self}, got {len(adapter_names_in_module)}") + + adapter_name_to_set: str | None + if not adapter_names_in_module: + adapter_name_to_set = None + else: + adapter_name_to_set = adapter_names_in_module[0] + + return adapter_name_to_set + + def set_adapter(self, adapter_names: Union[str, list[str]], inference_mode: bool = False) -> None: + """Set the active adapter + + Additionally, this function will set the specified adapter to trainable (i.e., requires_grad=True) unless + inference_mode is True. + + Args: + adapter_names (list[str], str): + The name(s) of the adapter(s) to set as active. + inference_mode (bool, optional): + Whether the activated adapter should be frozen (i.e. `requires_grad=False`). Default is False. + """ + if isinstance(adapter_names, str): + adapter_names = [adapter_names] + + if len(adapter_names) > 1: + raise ValueError(f"Attempted to set multiple ({adapter_names}) adapters at once for modules_to_save.") + + for currently_active_adapter_name in self.active_adapters: + _set_layer_requires_grad(self.modules_to_save[currently_active_adapter_name], False) + + if len(adapter_names) == 0: + # when calling model.add_adapter, the new adapter is not automatically active + self._active_adapter = [] + return + + adapter_name = adapter_names[0] + + if adapter_name not in self._adapters: + raise ValueError(f"Adapter {adapter_name} not found in {self._adapters}") + + _set_layer_requires_grad(self.modules_to_save[adapter_name], not inference_mode) + self._active_adapter = adapter_name + + def delete_adapter(self, adapter_name: str, new_active_adapters: Optional[list[str]]) -> None: + """ + Delete the adapter if present. + + This method will also set a new active adapter if the deleted adapter was the active adapter. It is important + that the new adapter is chosen by the caller in a deterministic way, so that the same adapter is chosen on all + layers. + """ + if adapter_name not in self.modules_to_save: + return + + # set new active adapter, if necessary + # note: there can only ever be one active adapter, unlike for LoRA etc. + if isinstance(new_active_adapters, (list, tuple)) and len(new_active_adapters) > 1: + name = self.__class__.__name__ + raise ValueError( + f"Attempted to set multiple ({new_active_adapters}) adapters at once for {name}, which is not allowed." + ) + + if adapter_name in self._adapters: + self._adapters.remove(adapter_name) + + if not new_active_adapters: + # no active adapter now + del self.modules_to_save[adapter_name] + self._active_adapter = [] + return + + new_active_adapter = new_active_adapters[0] + if new_active_adapter not in self.modules_to_save: + # a new active adapter was chosen but it seems like it has no modules_to_save + del self.modules_to_save[adapter_name] + self._active_adapter = [] + return + + if new_active_adapter != self.active_adapters[0]: + self.set_adapter(new_active_adapter) + del self.modules_to_save[adapter_name] + + def adapter_state_dict_load_map(self, adapter_name): + # Maps the module keys as they are in the saved state dict to the in-memory state dict. + # Must contain all keys that are supposed to be loaded. + if adapter_name not in self._adapters: + # In caes of multiple adapters, each bringing their own modules to save, each + # ModulesToSaveWrapper will be queried but not every wrapper is obliged to serve the same adapters. + return {} + return {k: f"modules_to_save.{adapter_name}.{k}" for k in self.modules_to_save[adapter_name].state_dict()} + + def adapter_state_dict(self, adapter_name, state_dict): + if adapter_name not in self._adapters: + # In caes of multiple adapters, each bringing their own modules to save, each + # ModulesToSaveWrapper will be queried but not every wrapper is obliged to serve the same adapters. + return {} + + return { + k: state_dict[f"modules_to_save.{adapter_name}.{k}"] + for k in self.modules_to_save[adapter_name].state_dict() + } + + def unload_and_optionally_merge_module( + self, merge: bool, safe_merge: bool, adapter_names: Optional[list[str]] + ) -> torch.nn.Module: + """Unloading in case of `ModulesToSave` means to simply return the wrapped module. + + However, if the wrapped module is itself a tuner, we'll call merge on it before. + """ + new_module = self.modules_to_save[self.active_adapter] + + # TODO: not sure if this is still a sensible thing to do. We would basically have to + # do the same checks as `_unload_and_optionally_merge` to support MHA, for example. + if hasattr(new_module, "base_layer"): + # check if the module is itself a tuner layer + if merge: + new_module.merge(safe_merge=safe_merge, adapter_names=adapter_names) + new_module = new_module.get_base_layer() + + return new_module + + def _get_available_adapters(self) -> set[str]: + """Return all adapter names that can be found on this module.""" + return set(self.modules_to_save.keys()) + + +class TrainableTokensWrapper(AuxiliaryTrainingWrapper): + """Wraps a module (typically an embedding layer) that is supposed to be re-trained selectively (i.e. + solely updating a few columns) using the `TrainableTokensLayer` PEFT method. + + Supports weight-tying to another adapter when passed a `tied_adapter` which is expected to be a + `TrainableTokensLayer`. + """ + + # All names of layers that may contain adapter (trainable) weights + adapter_layer_names: tuple[str, ...] = ("token_adapter.trainable_tokens_delta",) + other_param_names: tuple[str, ...] = ("token_adapter.token_indices", "token_adapter.trainable_tokens_original") + + def __init__( + self, + module_to_save: torch.nn.Module, + adapter_name: str, + token_indices: list[int], + tied_adapter=None, + ) -> None: + super().__init__(module_to_save, adapter_name, token_indices=token_indices, tied_adapter=tied_adapter) + + # unset the original_module attribute since we're using a property to remove this from the state dict. + self.original_module = None + + @property + def original_module(self): + # use a property instead of an attribute to exclude this pointer from the state dict + # to make sure that it will not be saved. + return self.token_adapter.base_layer + + def init_modules(self, adapter_name, token_indices, tied_adapter): + # use a local import to avoid potential circular imports + from peft.tuners.trainable_tokens import TrainableTokensLayer + + # since super().__init__() calls update before we have a chance to initialise the adapter we would + # need here, we do the initialization here. + self.token_adapter = TrainableTokensLayer(self.original_module, adapter_name, token_indices, tied_adapter) + + def _error_message_name(self): + return "trainable_token_indices" + + def _hasattr_wrapped(self, name, modules): + return name == "weight" + + def _getattr_wrapped(self, name, modules): + # some models query self.wte.weight.dtype, some may query the weights directly. for the first case it is not + # necessary to do anything special but we don't know if is going to be `.dtype`. so we need to get the merged + # weights from the adapter. + if name == "weight": + return modules["token_adapter"].get_merged_weights(self.token_adapter.active_adapters) + + raise RuntimeError( + f"This code should've never been reached, probably a bad check in `_hasattr_wrapped` for {name}. " + "Please file an issue under https://github.com/huggingface/peft/issues." + ) + + def _forward_wrapped(self, x, *args, **kwargs): + if not self.active_adapters: + return self._forward_wrapped_passthrough(x, *args, **kwargs) + return self.token_adapter(x) + + def _forward_wrapped_mixed_batch(self, x, active_adapter, *args, **kwargs): + return self.token_adapter.forward_adapters(x, [active_adapter]) + + def _forward_wrapped_passthrough(self, x, *args, **kwargs): + # the token adapter knows how to deal with disabled adapter / no active adapter, don't call original_module + # directly + return self.token_adapter(x, *args, **kwargs) + + def update(self, active_adapter, **kwargs): + # TODO this does not support deepspeed/fsdp since it is missing a context manager + # see ModulesToSaveWrapper implementation + if active_adapter not in self._adapters: + self.token_adapter.update_layer(active_adapter, **kwargs) + + super().update(active_adapter) + + def adapter_state_dict_load_map(self, adapter_name): + if self.token_adapter.tied_adapter: + return {} + return {"token_adapter.trainable_tokens_delta": f"token_adapter.trainable_tokens_delta.{adapter_name}"} + + def adapter_state_dict(self, adapter_name, state_dict): + if self.token_adapter.tied_adapter: + # storing of weight-tied layers is not up to us and will be handled by + # transformers. we're just here to keep those layers in sync during training. + # therefore we return an empty state dict. + return {} + + return { + f"token_adapter.{k}": state_dict[f"token_adapter.{k}.{adapter_name}"] for k in ["trainable_tokens_delta"] + } + + def enable_adapters(self, enabled: bool): + """Enables/disables the underlying `TrainableTokens` adapter. + Also handles the internal adapter disable flag. + """ + super().enable_adapters(enabled) + + self.token_adapter.enable_adapters(enabled) + + def check_set_adapter(self, adapter_name: str | list[str]) -> str | None: + """Helper function to check if the given adapter(s) can be set. + + Return the name of the adapter to be set or None if no adapter should be set. + """ + if isinstance(adapter_name, str): + return adapter_name + + # adapter_name is a list of str + if len(adapter_name) == 0: + raise ValueError("Please specify at least one adapter to set") + + # TODO In theory, multiple active trainable tokens is fine when the indices don't overlap + adapter_names_in_module = [n for n in adapter_name if n in self.token_adapter.trainable_tokens_delta] + + if len(adapter_names_in_module) > 1: + raise ValueError(f"Only one adapter can be set at a time for {self}, got {len(adapter_names_in_module)}") + + adapter_name_to_set: str | None + if not adapter_names_in_module: + adapter_name_to_set = None + else: + adapter_name_to_set = adapter_names_in_module[0] + + return adapter_name_to_set + + def set_adapter(self, adapter_names: Union[str, list[str]], inference_mode: bool = False) -> None: + super().set_adapter(adapter_names, inference_mode=inference_mode) + self.token_adapter.set_adapter(adapter_names, inference_mode=inference_mode) + + def delete_adapter(self, adapter_name: str, new_active_adapters: Optional[list[str]]) -> None: + """ + Delete the adapter if present. + + This method will also set a new active adapter if the deleted adapter was the active adapter. It is important + that the new adapter is chosen by the caller in a deterministic way, so that the same adapter is chosen on all + layers. + """ + self.token_adapter.delete_adapter(adapter_name) + + # set new active adapter, if necessary + # note: there can only ever be one active adapter, unlike for LoRA etc. + if isinstance(new_active_adapters, (list, tuple)) and len(new_active_adapters) > 1: + name = self.__class__.__name__ + raise ValueError( + f"Attempted to set multiple ({new_active_adapters}) adapters at once for {name}, which is not allowed." + ) + + if adapter_name in self._adapters: + self._adapters.remove(adapter_name) + + if not new_active_adapters: + self._active_adapter = [] + return + + if new_active_adapters[0] not in self.token_adapter.trainable_tokens_delta: + # a new active adapter was chosen but it seems like it has no trainable_tokens + self._active_adapter = [] + return + + new_active_adapter = new_active_adapters[0] + self.set_adapter(new_active_adapter) + + def unload_and_optionally_merge_module( + self, merge: bool, safe_merge: bool, adapter_names: Optional[list[str]] + ) -> torch.nn.Module: + """Unloading for `TrainableTokensWrapper` means to return the wrapped module, e.g. the embedding layer and, + if requested, merging the `TrainableTokens` adapter onto the wrapped module. + """ + if merge: + self.token_adapter.merge(safe_merge=safe_merge, adapter_names=adapter_names) + return self.token_adapter.get_base_layer() + + def _get_available_adapters(self) -> set[str]: + """Return all adapter names that can be found on this module.""" + return set(self.token_adapter.trainable_tokens_delta.keys()) + + +def _get_input_embeddings_name(model: torch.nn.Module, default: Optional[str] = None) -> Optional[str]: + if not hasattr(model, "get_input_embeddings"): + return default + + input_embeddings = model.get_input_embeddings() + for name, module in model.named_modules(): + if module is input_embeddings: + return name + + return default + + +def _get_submodules(model: torch.nn.Module, key: str) -> tuple[torch.nn.Module, torch.nn.Module, str]: + parent = model.get_submodule(".".join(key.split(".")[:-1])) + target_name = key.split(".")[-1] + target = model.get_submodule(key) + return parent, target, target_name + + +def _get_submodules_with_grandparent( + model: torch.nn.Module, key: str +) -> tuple[torch.nn.Module, Optional[torch.nn.Module], torch.nn.Module, str]: + parent = model.get_submodule(".".join(key.split(".")[:-1])) + try: + grandparent = model.get_submodule(".".join(key.split(".")[:-2])) + except AttributeError: + # no grand parent + grandparent = None + target_name = key.split(".")[-1] + target = model.get_submodule(key) + return parent, grandparent, target, target_name + + +def _freeze_adapter(model: torch.nn.Module, adapter_name: str) -> None: + for n, p in model.named_parameters(): + if adapter_name in n: + p.requires_grad = False + + +def _set_trainable( + model, + adapter_name, + module_names, + inference_mode: bool, + strict_module_check: bool = False, + wrapper_cls: Optional[AuxiliaryTrainingWrapper] = None, + activate_adapter: bool = True, + **wrapper_kwargs, +): + """Wraps modules that are supposed to be re-trained either normally, i.e. marking them to require gradients and + saving them alongside other modules, or with certain methods that go alongside PEFT methods, such as retraining + specific token indices using selective read/write. + + Note that you need to validate beforehand if there are layers targeted by multiple wrappers, e.g. if the + 'embedding' layer is configured for both `ModulesToSaveWrapper` and `TrainableTokensWrapper` there would be + conflicts down the line. + + The default is to wrap the module in a `ModulesToSaveWrapper` wrapper. + + If `strict_module_check` is set, this method raises an ValueError, similar to BaseTuner.inject_adapter when none of + the requested modules in `module_names` is not found in the model. + + The `active_adapter` flag indicates if this new adapter should be activated. + """ + from peft.tuners.tuners_utils import BaseTunerLayer + + if wrapper_cls is None: + wrapper_cls = ModulesToSaveWrapper + + if not module_names: + # This is useful for the case that the PEFT config does not have `modules_to_save`, e.g. + # in the case of prompt tuning and friends. + return + + trainable_modules = [] + found_modules = set() + # disable removal of duplicates to support targeting tied weights + key_list = [key for key, _ in model.named_modules(remove_duplicate=False)] + + for key in key_list: + target_module_found = any(key.endswith(target_key) for target_key in module_names) + if target_module_found: + parent, grandparent, target, target_name = _get_submodules_with_grandparent(model, key) + if isinstance(grandparent, BaseTunerLayer): + # This is an extreme edge case: Let's assume that there is a PEFT config with + # modules_to_save=["default"], which is the same name as the adapter name. The PEFT method's adapter + # (e.g. LoRA) is applied first. Then, when the modules_to_save matching is performed, the LoRA layer + # would be considered a valid target. Assuming that the name is "foo.bar.lora_A.default", it would + # match, with "default" being an nn.Linear and the parent, "lora_A", being an nn.ModuleDict. This by + # itself is not enough to prove that this is an unintended match. Thererfore, we also need to check the + # grandparent, "bar", that would be a lora.LoraLayer. When we see this, we should raise an error. + raise ValueError( + f"You are trying to target a module with {wrapper_cls} that is a child of {type(grandparent)}. " + "This is almost certainly not the intended behavior. Please ensure that the adapter name, " + f"'{adapter_name}', does not conflict with any of the targeted modules." + ) + + # For transformers >=5 we need to check the grandparent to detect already modified tied weights. The way + # the new `get_tied_weights_keys` works is that we resolve the current name of the module tied to the + # embeddings. If we replaced the tied weight (i.e. moved it to, say, `lm_head.token_adapter.base_layer`) + # we'll get the new name whereas the old way was that we got `lm_head` regardless of whether it was modified + # or not. We'll assume that we always have two levels of nesting and therefore do the same check as before + # but on the grandparent to accommodate for the new behavior. + if isinstance(grandparent, wrapper_cls): + grandparent.update(adapter_name, **wrapper_kwargs) + grandparent.set_adapter(grandparent.active_adapter, inference_mode=inference_mode) + elif isinstance(target, wrapper_cls): + target.update(adapter_name, **wrapper_kwargs) + target.set_adapter(target.active_adapter, inference_mode=inference_mode) + else: + new_module = wrapper_cls(target, adapter_name, **wrapper_kwargs) + if activate_adapter: + new_module.set_adapter(adapter_name, inference_mode=inference_mode) + else: + new_module.set_adapter([], inference_mode=inference_mode) + setattr(parent, target_name, new_module) + trainable_modules.append(new_module) + found_modules.add(target_name) + + not_found = set(module_names).difference(found_modules) + if strict_module_check and not found_modules: + raise ValueError( + f"Target modules {not_found} not found in the base model. Please check the target modules and try again." + ) + + return trainable_modules + + +def _set_adapter(model, adapter_name: str | list[str], inference_mode: bool = False) -> None: + """Call set_adapter on the AuxiliaryTrainingWrapper modules""" + for module in model.modules(): + if isinstance(module, AuxiliaryTrainingWrapper): + # only check the adapter_name if we actually encounter a AuxiliaryTrainingWrapper, otherwise we don't care + adapter_name_to_set = module.check_set_adapter(adapter_name) + + # if the adapter is found in this module, set it as the active adapter, else disable the adapters of this + # module + if adapter_name_to_set in module._adapters: + module.set_adapter(adapter_name_to_set, inference_mode=inference_mode) + else: + module.set_adapter([], inference_mode=inference_mode) + + +def _prepare_prompt_learning_config(peft_config, model_config): + orig_model_config = model_config + if hasattr(model_config, "to_dict"): + model_config = model_config.to_dict() + # In case of VLM we focus on the language model portion of the model. + if "text_config" in model_config: + model_config = model_config["text_config"] + + if peft_config.num_layers is None: + if hasattr(orig_model_config, "num_hidden_layers"): + # dict entry was removed in https://github.com/huggingface/transformers/pull/41250 + num_layers = orig_model_config.num_hidden_layers + elif "num_hidden_layers" in model_config: + num_layers = model_config["num_hidden_layers"] + elif "num_layers" in model_config: + num_layers = model_config["num_layers"] + elif "n_layer" in model_config: + num_layers = model_config["n_layer"] + else: + raise ValueError("Please specify `num_layers` in `peft_config`") + peft_config.num_layers = num_layers + + if peft_config.token_dim is None: + if "hidden_size" in model_config: + token_dim = model_config["hidden_size"] + elif "n_embd" in model_config: + token_dim = model_config["n_embd"] + elif "d_model" in model_config: + token_dim = model_config["d_model"] + else: + raise ValueError("Please specify `token_dim` in `peft_config`") + peft_config.token_dim = token_dim + + if peft_config.num_attention_heads is None: + if "num_attention_heads" in model_config: + num_attention_heads = model_config["num_attention_heads"] + elif "n_head" in model_config: + num_attention_heads = model_config["n_head"] + elif "num_heads" in model_config: + num_attention_heads = model_config["num_heads"] + elif "encoder_attention_heads" in model_config: + num_attention_heads = model_config["encoder_attention_heads"] + else: + raise ValueError("Please specify `num_attention_heads` in `peft_config`") + peft_config.num_attention_heads = num_attention_heads + + # For grouped-query attention, see #1901. + if (peft_config.peft_type in {"PREFIX_TUNING", "CARTRIDGE"}) and ("num_key_value_heads" in model_config): + # Models with heterogeneous attention (e.g. Gemma4) expose distinct shapes for global vs. sliding layers via + # `global_head_dim` / `num_global_key_value_heads`. Provision the prefix for the global-layer footprint; sliding + # layers whose KV shape doesn't match are skipped per-layer at injection time. Matches the default in + # google-deepmind/gemma#631. + if model_config.get("global_head_dim") is not None: + head_dim = model_config["global_head_dim"] + num_key_value_heads = model_config.get("num_global_key_value_heads") or model_config["num_key_value_heads"] + elif model_config.get("head_dim", None) is not None: + head_dim = model_config["head_dim"] + num_key_value_heads = model_config["num_key_value_heads"] + else: + head_dim = peft_config.token_dim // peft_config.num_attention_heads + num_key_value_heads = model_config["num_key_value_heads"] + peft_config.token_dim = head_dim * num_key_value_heads + peft_config.num_attention_heads = num_key_value_heads + + if getattr(peft_config, "encoder_hidden_size", None) is None: + peft_config.encoder_hidden_size = peft_config.token_dim + + return peft_config + + +def _get_no_split_modules(model) -> set[str]: + """ + Get the modules of the model that should not be split when using device_map. We iterate through the modules to get + the underlying `_no_split_modules`. + + Returns: + `List[str]`: List of modules that should not be split + """ + # After discussion in https://github.com/huggingface/transformers/pull/38141, based on: + # https://github.com/huggingface/transformers/blob/1e921a3a9cea92b383ca4b0484ee45596bbdadc3/src/transformers/modeling_utils.py#L2677-L2704 + _no_split_modules: set[str] = set() + if not hasattr(model, "_no_split_modules"): + return _no_split_modules + + if is_transformers_ge_v5_1_0: + # See https://github.com/huggingface/transformers/commit/36ec3bfa33ebf6c3b38a1d6808292aeea4aae84d + return model._no_split_modules + + # TODO remove once transformers <5.1.0 is not supported anymore + modules_to_check = [model] + while len(modules_to_check) > 0: + module = modules_to_check.pop(-1) + # if the module does not appear in _no_split_modules, we also check the children + if module.__class__.__name__ not in _no_split_modules: + if isinstance(module, PreTrainedModel): + if module._no_split_modules is not None: + _no_split_modules = _no_split_modules | set(module._no_split_modules) + modules_to_check += list(module.children()) + return _no_split_modules + + +def fsdp_auto_wrap_policy(model): + if hasattr(FullyShardedDataParallelPlugin, "get_module_class_from_name"): + get_module_class_from_name = FullyShardedDataParallelPlugin.get_module_class_from_name + else: + from accelerate.utils.dataclasses import get_module_class_from_name + from torch.distributed.fsdp.wrap import _or_policy, lambda_auto_wrap_policy, transformer_auto_wrap_policy + + from ..tuners import CartridgeEncoder, PrefixEncoder, PromptEmbedding, PromptEncoder + + default_transformer_cls_names_to_wrap = ",".join(_get_no_split_modules(model)) + transformer_cls_names_to_wrap = os.environ.get( + "FSDP_TRANSFORMER_CLS_TO_WRAP", default_transformer_cls_names_to_wrap + ).split(",") + transformer_cls_to_wrap = {CartridgeEncoder, PrefixEncoder, PromptEncoder, PromptEmbedding} + for layer_class in transformer_cls_names_to_wrap: + if len(layer_class) == 0: + continue + transformer_cls = get_module_class_from_name(model, layer_class) + if transformer_cls is None: + raise TypeError("Could not find the transformer layer class to wrap in the model.") + else: + transformer_cls_to_wrap.add(transformer_cls) + + def lambda_policy_fn(module): + return ( + len(list(module.named_children())) == 0 + and getattr(module, "weight", None) is not None + and module.weight.requires_grad + ) + + lambda_policy = functools.partial(lambda_auto_wrap_policy, lambda_fn=lambda_policy_fn) + transformer_wrap_policy = functools.partial( + transformer_auto_wrap_policy, + transformer_layer_cls=transformer_cls_to_wrap, + ) + + auto_wrap_policy = functools.partial(_or_policy, policies=[lambda_policy, transformer_wrap_policy]) + return auto_wrap_policy + + +def transpose(weight: torch.Tensor, fan_in_fan_out: bool) -> torch.Tensor: + if not fan_in_fan_out: + return weight + + if isinstance(weight, torch.nn.Parameter): + return torch.nn.Parameter(weight.T) + return weight.T + + +def _is_valid_match(key: str, target_key: str) -> bool: + """ + Helper function to match module names target_key and key. Makes sure that either the key is exactly the target_key + or the target_key is a submodule of key + """ + if key.endswith(target_key): + if len(key) > len(target_key): + return key.endswith("." + target_key) # must be a sub module + return True + return False + + +def _get_batch_size(input_ids: Optional[torch.Tensor], inputs_embeds: Optional[torch.Tensor]) -> int: + """Get the batch size based on either input_ids or input_embeds + + Raises an ValueError if both are None. + + """ + if (input_ids is None) and (inputs_embeds is None): + raise ValueError("You have to provide either input_ids or inputs_embeds") + + if input_ids is not None: + batch_size = input_ids.shape[0] + else: + batch_size = inputs_embeds.shape[0] + return batch_size + + +def get_quantization_config(model: torch.nn.Module, method: str): + """ + Get the quantization config of the related quantization method + """ + if ( + hasattr(model, "config") + and hasattr(model.config, "quantization_config") + and (getattr(model, "quantization_method", None) == method) + ): + return model.config.quantization_config + return None + + +def is_gptqmodel_quant_linear(module: Optional[torch.nn.Module]) -> bool: + """ + Check if a module is a GPT-QModel quantized linear. + """ + if module is None or not is_gptqmodel_available(): + return False + + try: + from gptqmodel.nn_modules.qlinear import BaseQuantLinear + except ImportError: + return False + + return isinstance(module, BaseQuantLinear) + + +def is_gptqmodel_awq_layer(module: Optional[torch.nn.Module]) -> bool: + """ + Check if a module is a GPT-QModel quantized linear that supports the AWQ method. + """ + if not is_gptqmodel_quant_linear(module): + return False + + supported_methods = getattr(module, "SUPPORTS_METHODS", []) + return any(method.value == "awq" for method in supported_methods) + + +def get_gptqmodel_quant_linear(gptq_quantization_config, device_map=None): + """ + Get the right GPTQQuantLinear class based on the quantization config file + """ + if gptq_quantization_config is None: + return None + + if not is_gptqmodel_available(): + return None + + from gptqmodel import BACKEND + from gptqmodel.quantization import METHOD + from gptqmodel.utils.importer import hf_select_quant_linear_v2 + + desc_act = gptq_quantization_config.desc_act + group_size = gptq_quantization_config.group_size + bits = gptq_quantization_config.bits + checkpoint_format = ( + gptq_quantization_config.checkpoint_format + if hasattr(gptq_quantization_config, "checkpoint_format") + else "gptq" + ) + sym = gptq_quantization_config.sym + meta = gptq_quantization_config.meta if hasattr(gptq_quantization_config, "meta") else None + + QuantLinear = hf_select_quant_linear_v2( + bits=bits, + group_size=group_size, + desc_act=desc_act, + sym=sym, + device_map=device_map, + format=checkpoint_format, + quant_method=METHOD.GPTQ, + meta=meta, + backend=BACKEND.AUTO_TRAINABLE, + pack=False, + ) + + return QuantLinear + + +def id_tensor_storage(tensor: torch.Tensor) -> tuple[torch.device, int, int]: + """ + Unique identifier to a tensor storage. Multiple different tensors can share the same underlying storage. For + example, "meta" tensors all share the same storage, and thus their identifier will all be equal. This identifier is + guaranteed to be unique and constant for this tensor's storage during its lifetime. Two tensor storages with + non-overlapping lifetimes may have the same id. + + This method is the exact same copy of + https://github.com/huggingface/transformers/blob/main/src/transformers/pytorch_utils.py#L282C1-L300C58 but we added + it here manually to avoid import issue with old versions of transformers. + """ + if tensor.device.type == "xla" and is_torch_tpu_available(): + # NOTE: xla tensors dont have storage + # use some other unique id to distinguish. + # this is a XLA tensor, it must be created using torch_xla's + # device. So the following import is safe: + import torch_xla + + unique_id = torch_xla._XLAC._xla_get_tensor_id(tensor) + else: + unique_id = storage_ptr(tensor) + + return tensor.device, unique_id, storage_size(tensor) + + +def cast_mixed_precision_params(model: torch.nn.Module, dtype: torch.dtype) -> None: + """ + Cast all non-trainable parameters of the model to the given `dtype`. The `dtype` can be `torch.float16` or + `torch.bfloat16` as per the mixed-precision training you are performing. The trainable parameters are cast to full + precision. This is meant to reduce the GPU memory usage when using PEFT methods by using half-precision dtype for + non-trainable parameters. Having the trainable parameters in full-precision preserves training stability when using + automatic mixed-precision training. + + Args: + model (`torch.nn.Module`): + The model to cast the non-trainable parameters of. + dtype (`torch.dtype`): + The dtype to cast the non-trainable parameters to. The `dtype` can be `torch.float16` or + `torch.bfloat16` as per the mixed-precision training you are performing. + """ + for p in model.parameters(): + if not p.requires_grad: + p.data = p.to(dtype) + else: + p.data = p.to(torch.float32) + + +def str_to_bool(value: str) -> int: + """ + Converts a string representation of truth to `True` (1) or `False` (0). + + True values are `y`, `yes`, `t`, `true`, `on`, and `1`; False value are `n`, `no`, `f`, `false`, `off`, and `0`; + """ + # same as function as in accelerate.utils, which replaces the deprecated distutils.util.strtobool + value = value.lower() + if value in ("y", "yes", "t", "true", "on", "1"): + return 1 + elif value in ("n", "no", "f", "false", "off", "0"): + return 0 + else: + raise ValueError(f"invalid truth value {value}") + + +def check_file_exists_on_hf_hub(repo_id: str, filename: str, **kwargs) -> Optional[bool]: + """Check if a file exists on HF Hub, if check was not successful returns None instead of erroring. + + Respect offline mode if set. + + """ + exists: Optional[bool] = None + if str_to_bool(os.environ.get("HF_HUB_OFFLINE", "0")): + # user set offline mode, cannot check + return exists + + try: + exists = file_exists(repo_id, filename, **kwargs) + except (HFValidationError, EntryNotFoundError): + # error, exists stays None + pass + except Exception as e: + warnings.warn( + f"Unable to fetch remote file due to the following error {e} - silently ignoring the lookup" + f" for the file {filename} in {repo_id}." + ) + + return exists + + +def match_target_against_key(target_pattern: str, key: str) -> Optional[re.Match[str]]: + """Backing function for `target_modules` config parameter. + + Having this as its own function ensures that target key matching can be implemented in the same way everywhere. + """ + return re.fullmatch(target_pattern, key) + + +def get_pattern_key(pattern_keys: Sequence[str], key_to_match: str) -> str: + """Match a substring of key_to_match in pattern keys""" + for key in pattern_keys: + match = re.match(rf"(.*\.)?({key})$", key_to_match) + if not match: + continue + return key + + return key_to_match + + +def set_additional_trainable_modules(model, peft_config, model_config, adapter_name, activate_adapter: bool = True): + """Handle the resolution of additional trainable modules (also called AuxiliaryTrainingWrapper) + by checking the config if such modules are requested and adding them to the model. + + Currently trainable tokens and modules to save are considered additional trainable modules. + + If `activate_adapter` is set to `False`, the adapter won't be activated. This is typically the case when + `model.add_adapter` or `model.load_adapter` are being called. + """ + if getattr(peft_config, "modules_to_save", None) is not None: + # this may add a new ModulesToSaveWrapper + _set_trainable( + model, + adapter_name, + inference_mode=peft_config.inference_mode, + module_names=getattr(peft_config, "modules_to_save", None), + activate_adapter=activate_adapter, + ) + + if getattr(peft_config, "modules_to_tie", None) is not None: + # Tie the modules if any tied layer is passed in `modules_to_save`. + # This should always be called after + # `_set_trainable` is called for `modules_to_save`. + tied_module = getattr(model.get_input_embeddings().modules_to_save, adapter_name) + _set_trainable( + model, + adapter_name, + inference_mode=peft_config.inference_mode, + module_names=getattr(peft_config, "modules_to_tie", None), + activate_adapter=activate_adapter, + tied_module=tied_module, + ) + + if getattr(peft_config, "trainable_token_indices", None) is not None: + if isinstance(peft_config.trainable_token_indices, dict): + target_layers = peft_config.trainable_token_indices + else: + layer_name = _get_input_embeddings_name(model, "embed_tokens") + target_layers = {layer_name: peft_config.trainable_token_indices} + + modules_to_save = getattr(peft_config, "modules_to_save", None) + if modules_to_save is not None: + for target_layer_name in target_layers: + if target_layer_name in modules_to_save: + raise ValueError( + "The embedding layer is already marked to be trained fully, either specify " + f'`modules_to_save=[..., "{target_layer_name}", ...]` or ' + f"`trainable_tokens={{'{target_layer_name}': x}}` but not both." + ) + + # Check weight tying configuration first to determine which layers to wrap + weights_tied = model_config.get("tie_word_embeddings", False) + ensure_weight_tying = getattr(peft_config, "ensure_weight_tying", False) + + # When multiple target layers are specified, check if they correspond to tied weights + indices_mismatch = False + layers_to_skip = set() + tied_layer_keys = [] + + if len(target_layers) > 1 and weights_tied: + # Get module names that are tied with the embedding + tied_module_names = set(_get_module_names_tied_with_embedding(model)) + + # Also get the input embedding layer name as it's the source of tied weights + embedding_module = model.get_input_embeddings() + # Get the full embedding name (not just the last part) to support nested structures + embedding_name = next(n for n, m in model.named_modules() if m is embedding_module) + + # Find which target layers are in the tied weights (including the embedding source) + for target_layer_name in target_layers: + # Check if this is the embedding layer (use endswith to allow flexible matching) + # This allows users to specify just "embed_tokens" OR "m1.encoder.embed_tokens" for precision + if embedding_name.endswith(target_layer_name): + tied_layer_keys.append(target_layer_name) + continue + # Check if this target layer matches any tied module (considering nested structures) + for tied_module in tied_module_names: + if tied_module.endswith(target_layer_name) or target_layer_name in tied_module.split("."): + tied_layer_keys.append(target_layer_name) + break + + # If we found multiple tied layers in our targets, check their indices + if len(tied_layer_keys) >= 2: + # Check if all tied layers have the same indices + first_indices = target_layers[tied_layer_keys[0]] + indices_mismatch = not all(target_layers[key] == first_indices for key in tied_layer_keys[1:]) + + # Raise error immediately if ensure_weight_tying=True and indices mismatch + if indices_mismatch and ensure_weight_tying: + tied_layers_info = ", ".join([f"{key}: {target_layers[key]}" for key in tied_layer_keys]) + raise ValueError( + f"Cannot ensure weight tying when different token indices are specified for tied layers. " + f"Conflicting layers: {tied_layers_info}. " + f"Please use the same indices for all tied layers or set ensure_weight_tying=False." + ) + + # If indices match, skip tied modules (except embedding) as they'll be handled by weight tying logic + if not indices_mismatch: + layers_to_skip = set(tied_layer_keys) & tied_module_names + + # Wrap target layers (skip those that will be handled by weight tying logic) + for target_layer_name, token_indices in target_layers.items(): + if target_layer_name in layers_to_skip: + continue + + _set_trainable( + model, + adapter_name, + inference_mode=peft_config.inference_mode, + module_names=[target_layer_name], + strict_module_check=True, + wrapper_cls=TrainableTokensWrapper, + token_indices=token_indices, + activate_adapter=activate_adapter, + ) + + # Warn if user expects weight tying but model doesn't have tied weights + if not weights_tied and ensure_weight_tying: + warnings.warn( + "ensure_weight_tying=True but the model does not have tied weights " + "(tie_word_embeddings=False). Weight tying will not be applied for trainable_token_indices." + ) + + # Apply weight tying when appropriate + should_apply_tying = ( + weights_tied + and isinstance(model.get_input_embeddings(), TrainableTokensWrapper) + and (ensure_weight_tying or not indices_mismatch) + ) + + if should_apply_tying: + # There might be the possibility that we have output weights that are tied to the input weights. + # In that case we will tie any module that wants tied weights to the token adapter to make sure that + # any modification is reflected in the tied layers as well. + tied_weights_module_names = _get_module_names_tied_with_embedding(model) + token_adapter = model.get_input_embeddings().token_adapter + _set_trainable( + model, + adapter_name, + inference_mode=peft_config.inference_mode, + module_names=tied_weights_module_names, + strict_module_check=True, + wrapper_cls=TrainableTokensWrapper, + token_indices=token_adapter.token_indices[adapter_name], + tied_adapter=model.get_input_embeddings().token_adapter, + ) + + +def create_attention_mask( + model, *, model_input, attention_mask, past_key_values, cache_position, batch_size, sequence_length, position_ids +): + # adapted from: + # https://github.com/huggingface/transformers/blob/cb4c56ce0dfa1350267ed28e57760986a58a9ba4/src/transformers/generation/utils.py#L644-L680 + # In PEFT, we sometimes need to re-create the attention mask. This is because some prompt learning methods insert + # new items into the sequence, which results in the attention mask needing an update. We re-use transformers code + # for this as much as possible. + transformers_ge_4_53_1 = version.parse(transformers.__version__) >= version.parse("4.53.1") + if transformers_ge_4_53_1: + # the function already exists in v4.53.0 but has a different signature, so we check for 4.53.1 + from transformers.masking_utils import create_masks_for_generate + else: + raise ImportError("Your transformers version is too old, please upgrade it to >= 4.53.1") + + # Create the causal mask with fixed shape in advance, to reduce recompilations. If the function to create + # the 4D causal mask exists, it should be present in the base model (XXXModel class) or in its decoder. + base_model = getattr(model, model.base_model_prefix, model) + decoder = base_model.get_decoder() if hasattr(base_model, "get_decoder") else None + causal_mask_creation_function = getattr(base_model, "_prepare_4d_causal_attention_mask_with_cache_position", None) + if causal_mask_creation_function is None and decoder is not None: # it may be in the decoder + causal_mask_creation_function = getattr(decoder, "_prepare_4d_causal_attention_mask_with_cache_position", None) + + # If it's not defined, it means the model uses the new general mask API + if causal_mask_creation_function is None: # can't be found + token_type_ids = getattr(model_input, "token_type_ids", None) + # Some models may overwrite the general one + causal_mask_creation_function = getattr(model, "create_masks_for_generate", create_masks_for_generate) + attention_mask = causal_mask_creation_function( + config=model.config, + # we only need batch size, seq_length and dtype here - we don't care about the values of the embeddings + input_embeds=torch.empty((batch_size, sequence_length), dtype=model.dtype), + attention_mask=attention_mask, + cache_position=cache_position, + past_key_values=past_key_values, + token_type_ids=token_type_ids, + position_ids=position_ids, + ) + else: + attention_mask = causal_mask_creation_function( + attention_mask, + sequence_length=sequence_length, + target_length=past_key_values.get_max_cache_shape(), + dtype=model.dtype, + cache_position=cache_position, + batch_size=batch_size, + config=model.config, + past_key_values=past_key_values, + position_ids=position_ids, + ) + return attention_mask + + +def _get_module_names_tied_with_embedding(model) -> list[str]: + """ + Get the list of the fully qualified names of the modules that are tied to the input embeddings. In case of a + source-target-mapping `_tied_weights_keys`, it will attempt to identify the input embedding weights from the + mapping and return the list of tied modules accordingly. This gives a unified interface to both transformers v4 + tied weights and v5 mapped tied weights. + + For example: For models which have `embed_tokens` and `lm_head` as the tied keys, this function will return + [`lm_head`]. The PEFT model is assumed to be transparent: returned names will be relative to the base model, so + even though `model.base_model.lm_head` is tied, the returned name is `lm_head` since such attributes are forwarded + to the base model anyway. Non-transformer models have to provide a `_tied_weights_keys` attribute for this function + to work. + + If the model's config has `tie_word_embeddings` set to `False`, this function returns an empty list, as weight + tying is explicitly disabled for that model checkpoint. + """ + tied_weights: list[str] = [] + + if hasattr(model, "get_base_model"): + # unpack PeftModel + model = model.get_base_model() + + if hasattr(model, "tuner_layer_cls"): + # unpack BaseTuner + model = model.model + + # `_tied_weights_keys` is architectural capability; `tie_word_embeddings=False` means tying is + # explicitly disabled for this checkpoint and must be respected. + model_config = getattr(model, "config", None) + if ( + model_config is not None + and hasattr(model_config, "tie_word_embeddings") + and model_config.tie_word_embeddings is False + ): + return [] + + if not hasattr(model, "_tied_weights_keys"): + return [] + + base_layer_pattern = re.compile(r"[^.]+\.base_layer\.") + + if isinstance(model._tied_weights_keys, dict): + if not hasattr(model, "get_input_embeddings"): + raise ValueError( + "The supplied model implements `_tied_weights_keys` as a dict but doesn't implement " + "'get_input_embeddings' so we can't determine which weights are tied to embeddings." + ) + + # collect all _tied_weights_keys, as sub-modules may have additional entries + tied_weights_keys: dict[str, str] = {} + for module_name, module in model.named_modules(): + module_tied_weights_keys = getattr(module, "_tied_weights_keys", None) + if module_tied_weights_keys and not module_name: + tied_weights_keys.update(module_tied_weights_keys) + elif module_tied_weights_keys: + tied_weights_keys.update( + {f"{module_name}.{k}": f"{module_name}.{v}" for k, v in module_tied_weights_keys.items()} + ) + + # technically it would be sufficient to just return candidates since that contains all the keys of + # all models that are tied (not just equal!) to the input embeddings. the only reason why we aren't + # doing that is because we need to filter out the original embedding name since we promise to just + # return the keys of the tying targets. + input_embedding_params = set(model.get_input_embeddings().parameters()) + candidates = [n for n, p in model.named_parameters(remove_duplicate=False) if p in input_embedding_params] + + # Consider the case that sources and targets are already wrapped by a PEFT method. In that case we won't + # find them by their old names. Therefore, we need to create a map of the new names to the old names so + # that we can translate back and forth. + peft_reverse_mapping = {base_layer_pattern.sub("", name): name for name in candidates} + + # AuxiliaryTrainingWrapper don't have an adapter suffix but still have a base_layer attribute, + # add those as a potential translation. + peft_reverse_mapping.update(**{name.replace("base_layer.", ""): name for name in candidates}) + + tied_weights.extend( + peft_reverse_mapping.get(k, k) + for k, v in tied_weights_keys.items() + if peft_reverse_mapping.get(v, v) in candidates + ) + + elif model._tied_weights_keys is not None: + # TODO remove this when transformers