AdithyaSK HF Staff commited on
Commit
ccff786
·
verified ·
1 Parent(s): a7870f3

Stage Harbor release files 53001-53500

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/tasksmith-749ff8d440e1/environment/source/method_comparison/text_generation_benchmark/temporary_results/.gitkeep +0 -0
  2. tasks/tasksmith-749ff8d440e1/environment/source/method_comparison/text_generation_benchmark/utils.py +458 -0
  3. tasks/tasksmith-749ff8d440e1/environment/source/pyproject.toml +67 -0
  4. tasks/tasksmith-749ff8d440e1/environment/source/requirements.txt +15 -0
  5. tasks/tasksmith-749ff8d440e1/environment/source/scripts/ci_clean_cache.py +68 -0
  6. tasks/tasksmith-749ff8d440e1/environment/source/scripts/convert-bone-to-miss.py +69 -0
  7. tasks/tasksmith-749ff8d440e1/environment/source/scripts/evaluate-lora-conversion.py +156 -0
  8. tasks/tasksmith-749ff8d440e1/environment/source/scripts/launch_notebook_mp.py +47 -0
  9. tasks/tasksmith-749ff8d440e1/environment/source/scripts/log_reports.py +144 -0
  10. tasks/tasksmith-749ff8d440e1/environment/source/scripts/stale.py +65 -0
  11. tasks/tasksmith-749ff8d440e1/environment/source/scripts/train_memory.py +276 -0
  12. tasks/tasksmith-749ff8d440e1/environment/source/setup.py +117 -0
  13. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/__init__.py +306 -0
  14. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/auto.py +225 -0
  15. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/config.py +408 -0
  16. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/functional.py +34 -0
  17. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/helpers.py +577 -0
  18. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/import_utils.py +189 -0
  19. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/mapping.py +92 -0
  20. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/mapping_func.py +128 -0
  21. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/mixed_model.py +473 -0
  22. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/optimizers/__init__.py +19 -0
  23. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/optimizers/lorafa.py +255 -0
  24. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/optimizers/loraplus.py +121 -0
  25. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/peft_model.py +0 -0
  26. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/py.typed +0 -0
  27. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/__init__.py +171 -0
  28. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/_buffer_dict.py +159 -0
  29. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adalora/__init__.py +51 -0
  30. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adalora/bnb.py +142 -0
  31. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adalora/config.py +108 -0
  32. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adalora/gptq.py +71 -0
  33. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adalora/layer.py +515 -0
  34. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adalora/model.py +349 -0
  35. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adamss/__init__.py +32 -0
  36. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adamss/asa_callback.py +90 -0
  37. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adamss/config.py +340 -0
  38. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adamss/layer.py +668 -0
  39. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adamss/model.py +279 -0
  40. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adamss/utils.py +121 -0
  41. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adaption_prompt/__init__.py +23 -0
  42. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adaption_prompt/config.py +88 -0
  43. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adaption_prompt/layer.py +223 -0
  44. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adaption_prompt/model.py +171 -0
  45. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adaption_prompt/utils.py +154 -0
  46. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/beft/__init__.py +24 -0
  47. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/beft/config.py +73 -0
  48. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/beft/layer.py +166 -0
  49. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/beft/model.py +103 -0
  50. tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/boft/__init__.py +24 -0
tasks/tasksmith-749ff8d440e1/environment/source/method_comparison/text_generation_benchmark/temporary_results/.gitkeep ADDED
File without changes
tasks/tasksmith-749ff8d440e1/environment/source/method_comparison/text_generation_benchmark/utils.py ADDED
@@ -0,0 +1,458 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ Utilities for PEFT benchmarking.
17
+ """
18
+
19
+ import datetime
20
+ import json
21
+ import os
22
+ import platform
23
+ import subprocess
24
+ from collections.abc import Callable
25
+ from dataclasses import asdict, dataclass, field
26
+ from enum import Enum
27
+ from typing import Any, Optional
28
+
29
+ import psutil
30
+ import torch
31
+
32
+ from peft.utils import infer_device
33
+
34
+
35
+ FILE_NAME_BENCHMARK_PARAMS = "benchmark_params.json"
36
+ FILE_NAME_DEFAULT_CONFIG = "default_benchmark_params.json"
37
+
38
+ RESULT_PATH = os.path.join(os.path.dirname(__file__), "results")
39
+ RESULT_PATH_TEMP = os.path.join(os.path.dirname(__file__), "temporary_results")
40
+ RESULT_PATH_CANCELLED = os.path.join(os.path.dirname(__file__), "cancelled_results")
41
+
42
+
43
+ class BenchmarkStatus(Enum):
44
+ """Status of a benchmark run."""
45
+
46
+ SUCCESS = "success"
47
+ FAILED = "failed"
48
+ CANCELLED = "cancelled"
49
+ RUNNING = "running"
50
+
51
+
52
+ @dataclass
53
+ class BenchmarkResult:
54
+ """Container for benchmark results."""
55
+
56
+ experiment_name: str
57
+ status: BenchmarkStatus
58
+
59
+ model_id: str
60
+
61
+ run_info: dict = field(default_factory=dict)
62
+ generation_info: dict = field(default_factory=dict)
63
+ meta_info: dict = field(default_factory=dict)
64
+
65
+ def __post_init__(self):
66
+ """Initialize structured data format."""
67
+ device = infer_device()
68
+ torch_accelerator_module = getattr(torch, device, torch.cuda)
69
+ self.run_info = {
70
+ "timestamp": datetime.datetime.now(tz=datetime.timezone.utc).isoformat(),
71
+ "duration": 0.0,
72
+ "status": self.status.value,
73
+ "hardware": {
74
+ "num_accelerators": torch_accelerator_module.device_count() if torch_accelerator_module.is_available() else 0,
75
+ "accelerator_type": torch_accelerator_module.get_device_name(0) if torch_accelerator_module.is_available() else "N/A",
76
+ "cuda_version": torch.version.cuda if torch.cuda.is_available() else "N/A",
77
+ "pytorch_version": torch.__version__,
78
+ },
79
+ }
80
+
81
+ self.meta_info = {
82
+ "model_id": self.model_id,
83
+ "parameters": {
84
+ "base_params": 0,
85
+ "trainable_params": 0,
86
+ "total_params": 0,
87
+ "param_ratio": 0.0,
88
+ },
89
+ "model_size": {
90
+ "base_model_size_mb": 0.0,
91
+ "adapter_size_mb": 0.0,
92
+ },
93
+ "package_info": {
94
+ "transformers-version": None,
95
+ "transformers-commit-hash": None,
96
+ "peft-version": None,
97
+ "peft-commit-hash": None,
98
+ "datasets-version": None,
99
+ "datasets-commit-hash": None,
100
+ "bitsandbytes-version": None,
101
+ "bitsandbytes-commit-hash": None,
102
+ "torch-version": torch.__version__,
103
+ "torch-commit-hash": None,
104
+ },
105
+ "system_info": {
106
+ "system": platform.system(),
107
+ "release": platform.release(),
108
+ "version": platform.version(),
109
+ "machine": platform.machine(),
110
+ "processor": platform.processor(),
111
+ "accelerator": torch_accelerator_module.get_device_name(0) if torch_accelerator_module.is_available() else "N/A",
112
+ },
113
+ }
114
+
115
+ self.generation_info = {
116
+ "memory": {
117
+ "peak_accelerator_memory_mb": 0.0,
118
+ "peak_ram_memory_mb": 0.0,
119
+ "memory_logs": [],
120
+ },
121
+ "by_category": {},
122
+ "overall": {},
123
+ }
124
+
125
+ def update_meta_info(self, param_counts: dict, size_info: dict, package_info: Optional[dict] = None):
126
+ """Update model metadata information."""
127
+ self.meta_info["parameters"].update(param_counts)
128
+ self.meta_info["model_size"].update(size_info)
129
+ if package_info:
130
+ self.meta_info["package_info"].update(package_info)
131
+
132
+ def update_generation_info(self, memory_data: Optional[dict] = None, performance_metrics: Optional[dict] = None):
133
+ """Update generation performance information, primarily for memory and high-level performance."""
134
+ if memory_data:
135
+ self.generation_info["memory"].update(memory_data)
136
+ if performance_metrics: # For things like overall tokens/sec if calculated
137
+ self.generation_info.update(performance_metrics)
138
+
139
+ def add_memory_log(self, stage: str, ram_mb: float, accelerator_allocated_mb: float, accelerator_reserved_mb: float):
140
+ """Add a memory usage log entry to generation_info."""
141
+ self.generation_info["memory"]["memory_logs"].append(
142
+ {
143
+ "stage": stage,
144
+ "ram_mb": ram_mb,
145
+ "accelerator_allocated_mb": accelerator_allocated_mb,
146
+ "accelerator_reserved_mb": accelerator_reserved_mb,
147
+ }
148
+ )
149
+
150
+ def add_metrics_for_category(self, category: str, metrics: dict, individual_samples: Optional[list] = None):
151
+ """Add metrics for a specific prompt category under generation_info."""
152
+ category_data = {"metrics": metrics, "samples": individual_samples if individual_samples is not None else []}
153
+ self.generation_info["by_category"][category] = category_data
154
+
155
+ def update_run_info(
156
+ self,
157
+ duration: float,
158
+ status: BenchmarkStatus,
159
+ error: Optional[str] = None,
160
+ peft_config: Optional[dict] = None,
161
+ benchmark_config: Optional[dict] = None,
162
+ ):
163
+ """Update run information."""
164
+ self.run_info["duration"] = duration
165
+ self.run_info["status"] = status.value
166
+ if error:
167
+ self.run_info["error"] = error
168
+ if peft_config:
169
+ self.run_info["peft_config"] = peft_config
170
+ if benchmark_config:
171
+ self.run_info["benchmark_config"] = benchmark_config
172
+
173
+ def compute_overall_metrics(self):
174
+ """Compute overall metrics across all categories within generation_info."""
175
+ if not self.generation_info["by_category"]:
176
+ return
177
+
178
+ categories = self.generation_info["by_category"]
179
+ key_metrics = [
180
+ "inference_time",
181
+ "base_inference_time",
182
+ "inference_overhead_pct",
183
+ "time_per_token",
184
+ "generated_tokens",
185
+ ]
186
+
187
+ for metric in key_metrics:
188
+ values = []
189
+ for category_data in categories.values():
190
+ if "metrics" in category_data and metric in category_data["metrics"]:
191
+ values.append(category_data["metrics"][metric])
192
+
193
+ if values:
194
+ self.generation_info["overall"][metric] = sum(values) / len(values)
195
+
196
+ def to_dict(self) -> dict[str, Any]:
197
+ """Convert result to dictionary."""
198
+ self.compute_overall_metrics()
199
+ return {
200
+ "run_info": self.run_info,
201
+ "generation_info": self.generation_info,
202
+ "meta_info": self.meta_info,
203
+ }
204
+
205
+ def save(self, path: Optional[str] = None):
206
+ """Save result to JSON file."""
207
+ if path is None:
208
+ peft_branch = get_peft_branch()
209
+ if self.status == BenchmarkStatus.CANCELLED:
210
+ base_path = RESULT_PATH_CANCELLED
211
+ elif peft_branch != "main":
212
+ base_path = RESULT_PATH_TEMP
213
+ elif self.status == BenchmarkStatus.SUCCESS:
214
+ base_path = RESULT_PATH
215
+ elif self.status == BenchmarkStatus.FAILED:
216
+ base_path = RESULT_PATH_CANCELLED
217
+ else:
218
+ base_path = RESULT_PATH_TEMP
219
+
220
+ filename = f"{self.experiment_name}.json"
221
+ path = os.path.join(base_path, filename)
222
+
223
+ os.makedirs(os.path.dirname(path), exist_ok=True)
224
+
225
+ with open(path, "w") as f:
226
+ json.dump(self.to_dict(), f, indent=2)
227
+
228
+ return path
229
+
230
+
231
+ @dataclass
232
+ class BenchmarkConfig:
233
+ """Configuration for benchmarking PEFT methods."""
234
+
235
+ model_id: str
236
+
237
+ seed: int
238
+ num_inference_runs: int
239
+ max_new_tokens: int
240
+
241
+ dtype: str = "float16"
242
+ use_4bit: bool = False
243
+ use_8bit: bool = False
244
+
245
+ category_generation_params: Optional[dict] = None
246
+
247
+ def __post_init__(self) -> None:
248
+ """Validate configuration."""
249
+ if not isinstance(self.model_id, str):
250
+ raise TypeError(f"Invalid model_id: {self.model_id}")
251
+
252
+ if self.seed < 0:
253
+ raise ValueError(f"Invalid seed: {self.seed}")
254
+
255
+ if self.num_inference_runs <= 0:
256
+ raise ValueError(f"Invalid num_inference_runs: {self.num_inference_runs}")
257
+
258
+ if self.max_new_tokens <= 0:
259
+ raise ValueError(f"Invalid max_new_tokens: {self.max_new_tokens}")
260
+
261
+ @classmethod
262
+ def from_dict(cls, config_dict: dict) -> "BenchmarkConfig":
263
+ """Create config from dictionary."""
264
+ valid_keys = set(cls.__dataclass_fields__.keys())
265
+ filtered_dict = {k: v for k, v in config_dict.items() if k in valid_keys}
266
+
267
+ return cls(**filtered_dict)
268
+
269
+ @classmethod
270
+ def from_json(cls, json_path: str) -> "BenchmarkConfig":
271
+ """Load config from JSON file."""
272
+ with open(json_path) as f:
273
+ config_dict = json.load(f)
274
+ return cls.from_dict(config_dict)
275
+
276
+ def to_dict(self) -> dict[str, Any]:
277
+ """Convert config to dictionary."""
278
+ result = asdict(self)
279
+ return result
280
+
281
+ def save(self, path: str) -> None:
282
+ """Save config to JSON file."""
283
+ with open(path, "w") as f:
284
+ json.dump(self.to_dict(), f, indent=2)
285
+
286
+ def merge_from_dict(self, config_dict: dict) -> None:
287
+ """Merge settings from a dictionary into this config object.
288
+ Keys in config_dict will override existing attributes.
289
+ """
290
+ for key, value in config_dict.items():
291
+ if hasattr(self, key):
292
+ setattr(self, key, value)
293
+
294
+
295
+ def validate_experiment_path(path: str) -> tuple[str, "BenchmarkConfig"]:
296
+ """Validate experiment path, load and merge configs, and return them."""
297
+ if not os.path.exists(path):
298
+ raise FileNotFoundError(f"Experiment path not found: {path}")
299
+
300
+ path_parts = os.path.normpath(path).split(os.sep)
301
+
302
+ try:
303
+ experiments_idx = path_parts.index("experiments")
304
+ except ValueError:
305
+ experiment_name = os.path.basename(path.rstrip(os.sep))
306
+ else:
307
+ if experiments_idx + 1 < len(path_parts):
308
+ method_name = path_parts[experiments_idx + 1]
309
+ remaining_parts = path_parts[experiments_idx + 2 :]
310
+ if remaining_parts:
311
+ remaining_name = "-".join(remaining_parts)
312
+ experiment_name = f"{method_name}--{remaining_name}"
313
+ else:
314
+ experiment_name = method_name
315
+ else:
316
+ experiment_name = os.path.basename(path.rstrip(os.sep))
317
+
318
+ default_config_path = os.path.join(os.path.dirname(__file__), FILE_NAME_DEFAULT_CONFIG)
319
+ experiment_benchmark_params_path = os.path.join(path, FILE_NAME_BENCHMARK_PARAMS)
320
+
321
+ if not os.path.exists(default_config_path):
322
+ raise FileNotFoundError(f"Default configuration file not found: {default_config_path}. This is required.")
323
+ benchmark_config = BenchmarkConfig.from_json(default_config_path)
324
+ print(f"Loaded default configuration from {default_config_path}")
325
+
326
+ if os.path.exists(experiment_benchmark_params_path):
327
+ with open(experiment_benchmark_params_path) as f:
328
+ experiment_specific_params = json.load(f)
329
+
330
+ benchmark_config.merge_from_dict(experiment_specific_params)
331
+ print(f"Loaded and merged experiment-specific parameters from {experiment_benchmark_params_path}")
332
+ else:
333
+ print(f"No {FILE_NAME_BENCHMARK_PARAMS} found in {path}. Using only default configuration.")
334
+
335
+ return experiment_name, benchmark_config
336
+
337
+
338
+ def get_memory_usage() -> tuple[float, float, float]:
339
+ """Get current memory usage (RAM and accelerator)."""
340
+ process = psutil.Process(os.getpid())
341
+ ram_usage_bytes = process.memory_info().rss
342
+ ram_usage_mb = ram_usage_bytes / (1024 * 1024)
343
+
344
+ if torch.cuda.is_available():
345
+ accelerator_allocated = torch.cuda.memory_allocated()
346
+ accelerator_reserved = torch.cuda.memory_reserved()
347
+ accelerator_allocated_mb = accelerator_allocated / (1024 * 1024)
348
+ accelerator_reserved_mb = accelerator_reserved / (1024 * 1024)
349
+ elif torch.xpu.is_available():
350
+ accelerator_allocated = torch.xpu.memory_allocated()
351
+ accelerator_reserved = torch.xpu.memory_reserved()
352
+ accelerator_allocated_mb = accelerator_allocated / (1024 * 1024)
353
+ accelerator_reserved_mb = accelerator_reserved / (1024 * 1024)
354
+ else:
355
+ accelerator_allocated_mb = 0.0
356
+ accelerator_reserved_mb = 0.0
357
+
358
+ return ram_usage_mb, accelerator_allocated_mb, accelerator_reserved_mb
359
+
360
+
361
+ def init_accelerator() -> tuple[float, float]:
362
+ """Initialize accelerator and return initial memory usage."""
363
+ if torch.cuda.is_available():
364
+ torch.cuda.init()
365
+ torch.cuda.empty_cache()
366
+ _, accelerator_allocated, accelerator_reserved = get_memory_usage()
367
+ elif torch.xpu.is_available():
368
+ torch.xpu.init()
369
+ torch.xpu.empty_cache()
370
+ _, accelerator_allocated, accelerator_reserved = get_memory_usage()
371
+ else:
372
+ accelerator_allocated = 0.0
373
+ accelerator_reserved = 0.0
374
+ return accelerator_allocated, accelerator_reserved
375
+
376
+
377
+ def get_model_size_mb(model: torch.nn.Module, dtype_bytes: int = 4) -> float:
378
+ """Calculate model size in MB."""
379
+ return sum(p.numel() * dtype_bytes for p in model.parameters()) / (1024 * 1024)
380
+
381
+
382
+ def get_peft_branch() -> str:
383
+ repo_root = os.path.dirname(__file__)
384
+ return subprocess.check_output(["git", "rev-parse", "--abbrev-ref", "HEAD"], cwd=repo_root).decode().strip()
385
+
386
+
387
+ def log_results(
388
+ experiment_name: str,
389
+ benchmark_result: BenchmarkResult,
390
+ print_fn: Callable = print,
391
+ ) -> None:
392
+ """Log benchmark results to console."""
393
+ print_fn("\n" + "=" * 50)
394
+ print_fn(f"Benchmark Results: {experiment_name}")
395
+ print_fn("=" * 50)
396
+
397
+ print_fn(f"Status: {benchmark_result.run_info.get('status', 'N/A')}")
398
+ print_fn(f"Duration: {benchmark_result.run_info.get('duration', 0):.2f} seconds")
399
+
400
+ if benchmark_result.run_info.get("status") != BenchmarkStatus.SUCCESS.value:
401
+ print_fn(f"Error: {benchmark_result.run_info.get('error', 'Unknown error')}")
402
+ print_fn("=" * 50)
403
+ return
404
+
405
+ print_fn("\nModel Information:")
406
+ print_fn(f" Base Model: {benchmark_result.meta_info.get('model_id', 'N/A')}")
407
+
408
+ print_fn("\nParameter Counts:")
409
+ params = benchmark_result.meta_info.get("parameters", {})
410
+ print_fn(f" Base Parameters: {params.get('base_params', 0):,}")
411
+ print_fn(f" Trainable Parameters: {params.get('trainable_params', 0):,}")
412
+ print_fn(f" Parameter Ratio: {params.get('param_ratio', 0):.5%}")
413
+
414
+ print_fn("\nModel Size:")
415
+ size_info = benchmark_result.meta_info.get("model_size", {})
416
+ print_fn(f" Base Model: {size_info.get('base_model_size_mb', 0):.2f} MB")
417
+ print_fn(f" Adapter: {size_info.get('adapter_size_mb', 0):.2f} MB")
418
+
419
+ print_fn("\nMemory Usage (from generation_info):")
420
+ memory_data = benchmark_result.generation_info.get("memory", {})
421
+ print_fn(f" Peak Accelerator Memory: {memory_data.get('peak_accelerator_memory_mb', 0):.2f} MB")
422
+ print_fn(f" Peak RAM Memory: {memory_data.get('peak_ram_memory_mb', 0):.2f} MB")
423
+
424
+ print_fn("\nDetailed Metrics (from generation_info.by_category):")
425
+ if benchmark_result.generation_info.get("by_category"):
426
+ for category, cat_data in benchmark_result.generation_info["by_category"].items():
427
+ print_fn(f" Category: {category}")
428
+ metrics = cat_data.get("metrics", {})
429
+ print_fn(f" Inference Time: {metrics.get('inference_time', 0):.4f} seconds")
430
+ print_fn(f" Base Inference Time: {metrics.get('base_inference_time', 0):.4f} seconds")
431
+ print_fn(f" Inference Overhead: {metrics.get('inference_overhead_pct', 0):.2f}%")
432
+ print_fn(f" Time Per Token: {metrics.get('time_per_token', 0):.6f} seconds/token")
433
+ print_fn(f" Generated Tokens: {metrics.get('generated_tokens', 0):.1f}")
434
+
435
+ samples = cat_data.get("samples", [])
436
+ if samples:
437
+ print_fn(f" Number of Samples: {len(samples)}")
438
+ print_fn(
439
+ f" Average Generated Tokens: {sum(s.get('generated_tokens', 0) for s in samples) / len(samples):.1f}"
440
+ )
441
+ else:
442
+ print_fn(" No per-category metrics available.")
443
+
444
+ benchmark_result.compute_overall_metrics()
445
+
446
+ print_fn("\nOverall Metrics (from generation_info.overall):")
447
+ overall = benchmark_result.generation_info.get("overall")
448
+ if overall:
449
+ print_fn(f" Inference Time: {overall.get('inference_time', 0):.4f} seconds")
450
+ print_fn(f" Base Inference Time: {overall.get('base_inference_time', 0):.4f} seconds")
451
+ print_fn(f" Inference Overhead: {overall.get('inference_overhead_pct', 0):.2f}%")
452
+ print_fn(f" Time Per Token: {overall.get('time_per_token', 0):.6f} seconds/token")
453
+ print_fn(f" Generated Tokens: {overall.get('generated_tokens', 0):.1f}")
454
+ else:
455
+ print_fn(" No overall metrics computed.")
456
+
457
+ print_fn("\nSaved results to:", benchmark_result.save())
458
+ print_fn("=" * 50)
tasks/tasksmith-749ff8d440e1/environment/source/pyproject.toml ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [tool.black]
2
+ # Only used by `hf-doc-builder´.
3
+ line-length = 119
4
+ target-version = ['py310']
5
+
6
+ [tool.ruff]
7
+ target-version = "py310"
8
+ line-length = 119
9
+ extend-exclude = ["*.ipynb"]
10
+ required-version = "~=0.15.12"
11
+
12
+ [tool.ruff.lint]
13
+ preview = true
14
+ explicit-preview-rules = true
15
+ extend-select = [
16
+ "C", # Complexity
17
+ "E", # PEP8 errors
18
+ "F", # PEP8 formatting
19
+ "I", # Import sorting
20
+ "UP", # Pyupgrade upgrades
21
+ "W", # PEP8 warnings
22
+ "PT009", # Pytest assertions
23
+ "RUF022", # Sorting of __all__
24
+ ]
25
+ ignore = [
26
+ "C901", # Function too complex
27
+ "E501", # Line length (handled by ruff-format)
28
+ "F841", # unused variable
29
+ "UP007", # X | Y style Unions
30
+ "C420", # dict.fromkeys
31
+ "UP045", # don't force replacing Optional[X] with X | None
32
+ "SIM118", # `for key in dct.keys()` is allowed
33
+ "PLC0206", # allow iterating over dict keys and pulling values later, can be more consistent
34
+ "RUF012", # allow mutable default values, contrary to popular belief, not always evil
35
+ "B018", # a "useless expression" is not useless when it tests for an AttributeError
36
+ "SIM117", # allow nesting of `with` statements: can be *more* readable of they are long
37
+ "BLE001", # allow catching bare `Exception`
38
+ "SIM102", # collapse multiple `if` statements: nice to have but requires too many changes
39
+ "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)
40
+ ]
41
+
42
+ [tool.ruff.lint.isort]
43
+ lines-after-imports = 2
44
+ known-first-party = ["peft"]
45
+
46
+ [tool.pytest]
47
+ doctest_optionflags = [
48
+ "NORMALIZE_WHITESPACE",
49
+ "ELLIPSIS",
50
+ "NUMBER",
51
+ ]
52
+
53
+ addopts = ["--cov=src/peft", "--cov-report=term-missing", "--durations=10"]
54
+
55
+ markers = [
56
+ "single_gpu_tests: tests that run on a single GPU",
57
+ "multi_gpu_tests: tests that run on multiple GPUs",
58
+ "regression: whether to run regression suite test",
59
+ "bitsandbytes: select bitsandbytes integration tests",
60
+ ]
61
+
62
+ filterwarnings = [
63
+ "error::DeprecationWarning:transformers",
64
+ # in sync with tests/conftest.py regarding BPE deprecation
65
+ "ignore:.*BPE.__init__ will not create from files anymore.*:DeprecationWarning:transformers",
66
+ "error::FutureWarning:transformers",
67
+ ]
tasks/tasksmith-749ff8d440e1/environment/source/requirements.txt ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ accelerate
2
+ torch
3
+ safetensors
4
+ bitsandbytes
5
+ scipy
6
+ peft
7
+ transformers
8
+ tqdm
9
+ packaging
10
+ pytest
11
+ numpy
12
+ pyyaml
13
+ datasets
14
+ psutil
15
+ setuptools
tasks/tasksmith-749ff8d440e1/environment/source/scripts/ci_clean_cache.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Utility to clean cache files that exceed a specific time in days according to their
3
+ last access time recorded in the cache.
4
+
5
+ Exit code:
6
+ - 1 if no candidates are found
7
+ - 0 if candidates are found
8
+
9
+ Deletion can be enabled by passing `-d` parameter, otherwise it will only list the candidates.
10
+ """
11
+
12
+ import sys
13
+ from datetime import datetime as dt
14
+ from datetime import timezone
15
+
16
+ from huggingface_hub import scan_cache_dir
17
+
18
+
19
+ def find_old_revisions(scan_results, max_age_days=30):
20
+ """Find commit hashes of objects in the cache. These objects need a last access time that
21
+ is above the passed `max_age_days` parameter. Returns an empty list if no objects are found.
22
+ Time measurement is based of the current time and the recorded last access tiem in the cache.
23
+ """
24
+ now = dt.now(timezone.utc)
25
+ revisions = [(i.revisions, i.last_accessed) for i in scan_results.repos]
26
+ revisions_ages = [(rev, (now - dt.fromtimestamp(ts_access, timezone.utc)).days) for rev, ts_access in revisions]
27
+ delete_candidates = [rev for rev, age in revisions_ages if age > max_age_days]
28
+ hashes = [n.commit_hash for rev in delete_candidates for n in rev]
29
+
30
+ return hashes
31
+
32
+
33
+ def delete_old_revisions(scan_results, delete_candidates, do_delete=False):
34
+ delete_operation = scan_results.delete_revisions(*delete_candidates)
35
+ print(f"Would free {delete_operation.expected_freed_size_str}")
36
+ print(f"Candidates: {delete_candidates}")
37
+
38
+ if do_delete:
39
+ print("Deleting now.")
40
+ delete_operation.execute()
41
+ else:
42
+ print("Not deleting, pass the -d flag.")
43
+
44
+
45
+ if __name__ == "__main__":
46
+ from argparse import ArgumentParser
47
+
48
+ parser = ArgumentParser()
49
+ parser.add_argument("-a", "--max-age", type=int, default=30, help="Max. age in days items in the cache may have.")
50
+ parser.add_argument(
51
+ "-d",
52
+ "--delete",
53
+ action="store_true",
54
+ help=(
55
+ "Delete mode; Really delete items if there are candidates. Exit code = 0 when we found something to delete, 1 "
56
+ "otherwise."
57
+ ),
58
+ )
59
+ args = parser.parse_args()
60
+
61
+ scan_results = scan_cache_dir()
62
+
63
+ delete_candidates = find_old_revisions(scan_results, args.max_age)
64
+ if not delete_candidates:
65
+ print("No delete candidates found, not deleting anything.")
66
+ sys.exit(1)
67
+
68
+ delete_old_revisions(scan_results, delete_candidates, do_delete=args.delete)
tasks/tasksmith-749ff8d440e1/environment/source/scripts/convert-bone-to-miss.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 Your Organization/Project. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Convert Bone checkpoint to MiSS format."""
16
+
17
+ import argparse
18
+ import json
19
+ import os
20
+ from pathlib import Path
21
+
22
+ from safetensors import safe_open
23
+ from safetensors.torch import save_file
24
+
25
+ from peft.utils import CONFIG_NAME, SAFETENSORS_WEIGHTS_NAME
26
+
27
+
28
+ def convert_bone_to_miss(bone_dir: Path, miss_dir: Path) -> None:
29
+ """Convert Bone checkpoint files to MiSS format."""
30
+ bone_config_path = bone_dir / CONFIG_NAME
31
+ miss_config_path = miss_dir / CONFIG_NAME
32
+ if not os.path.exists(miss_dir):
33
+ os.makedirs(miss_dir, exist_ok=True)
34
+ with open(bone_config_path, encoding="utf-8") as f:
35
+ config = json.load(f)
36
+
37
+ config["peft_type"] = "MISS"
38
+
39
+ with open(miss_config_path, "w", encoding="utf-8") as f:
40
+ json.dump(config, f, indent=2, ensure_ascii=False)
41
+
42
+ bone_weight_path = bone_dir / SAFETENSORS_WEIGHTS_NAME
43
+ miss_weight_path = miss_dir / SAFETENSORS_WEIGHTS_NAME
44
+
45
+ new_data = {}
46
+
47
+ with safe_open(bone_weight_path, framework="pt") as f:
48
+ for old_key in f.keys():
49
+ tensor = f.get_tensor(old_key)
50
+ new_key = old_key.replace(".bone_", ".miss_")
51
+ new_data[new_key] = tensor
52
+
53
+ save_file(new_data, miss_weight_path)
54
+
55
+ print(f"Converted checkpoint saved at {miss_weight_path}")
56
+
57
+
58
+ def main() -> None:
59
+ parser = argparse.ArgumentParser(description="Convert Bone checkpoint to MiSS format.")
60
+ parser.add_argument("bone_dir", type=Path, help="Directory containing Bone checkpoint files")
61
+ parser.add_argument("miss_dir", type=Path, help="Directory to save MiSS checkpoint files")
62
+ args = parser.parse_args()
63
+
64
+ args.miss_dir.mkdir(parents=True, exist_ok=True)
65
+ convert_bone_to_miss(args.bone_dir, args.miss_dir)
66
+
67
+
68
+ if __name__ == "__main__":
69
+ main()
tasks/tasksmith-749ff8d440e1/environment/source/scripts/evaluate-lora-conversion.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Script to evaluate a PEFT checkpoint converted into a LoRA on GSM8K
16
+
17
+ To run this script, first train a PEFT model on MetaMathQA as described here:
18
+
19
+ https://github.com/huggingface/peft/tree/main/method_comparison/MetaMathQA
20
+
21
+ Call the script with the `-v` (verbose) option. When that run finishes, it will save a checkpoint of that model and
22
+ print a message like this: "Saved PEFT checkpoint to ...". Use this path as the `--path` argument to this script.
23
+
24
+ Example usage:
25
+
26
+ ```bash
27
+ # Convert to LoRA with rank 8 and evaluate it
28
+ python evaluate-lora-conversion.py --path /path/to/peft/checkpoint --rank 8
29
+ # Convert to LoRA with dynamic rank (50% singular value threshold) and evaluate it
30
+ python evaluate-lora-conversion.py --path /path/to/peft/checkpoint --rank 0.5
31
+ # Evaluate the original PEFT model without LoRA conversion
32
+ python evaluate-lora-conversion.py --path /path/to/peft/checkpoint
33
+ ```
34
+
35
+ The script will report the evaluation accuracy, maximum CUDA memory reserved, and evaluation time for the converted LoRA
36
+ model.
37
+
38
+ """
39
+
40
+ import argparse
41
+ import importlib.util
42
+ import os
43
+ import sys
44
+ import time
45
+
46
+ import torch
47
+ from transformers import AutoModelForCausalLM
48
+
49
+ from peft import PeftModel, convert_to_lora, get_peft_model, set_peft_model_state_dict
50
+
51
+
52
+ root = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
53
+
54
+ spec = importlib.util.spec_from_file_location("data", os.path.join(root, "method_comparison", "MetaMathQA", "data.py"))
55
+ mm_data = importlib.util.module_from_spec(spec)
56
+ spec.loader.exec_module(mm_data)
57
+ sys.modules["data"] = mm_data
58
+
59
+ spec = importlib.util.spec_from_file_location(
60
+ "utils", os.path.join(root, "method_comparison", "MetaMathQA", "utils.py")
61
+ )
62
+ mm_utils = importlib.util.module_from_spec(spec)
63
+ spec.loader.exec_module(mm_utils)
64
+ sys.modules["utils"] = mm_utils
65
+
66
+ spec = importlib.util.spec_from_file_location("run", os.path.join(root, "method_comparison", "MetaMathQA", "run.py"))
67
+ mm_run = importlib.util.module_from_spec(spec)
68
+ spec.loader.exec_module(mm_run)
69
+
70
+
71
+ def noop(*args, **kwargs):
72
+ pass
73
+
74
+
75
+ def evaluate_model(model, tokenizer, ds_test):
76
+ torch.cuda.empty_cache()
77
+ torch.cuda.reset_peak_memory_stats()
78
+ tic = time.perf_counter()
79
+ predictions, responses = mm_run.evaluate(
80
+ model=model,
81
+ tokenizer=tokenizer,
82
+ ds=ds_test,
83
+ batch_size=50,
84
+ generate_kwargs={"max_length": 800, "max_new_tokens": 300, "pad_token_id": tokenizer.eos_token_id},
85
+ use_tqdm=True,
86
+ )
87
+ toc = time.perf_counter()
88
+ accuracy_peft = mm_utils.get_accuracy(predictions=predictions, responses=responses)
89
+ cuda_mem_reserved_max = torch.cuda.memory_reserved(0)
90
+ print(f"Evaluation Accuracy: {100 * accuracy_peft:.2f}%")
91
+ print(f"Max CUDA Memory Reserved: {cuda_mem_reserved_max / (1024**3):.2f} GB")
92
+ print(f"Evaluation Time: {toc - tic:.0f} seconds".format(toc - tic))
93
+
94
+
95
+ def main(path_peft_model: str, rank: float | None) -> None:
96
+ model_id = "meta-llama/Llama-3.2-3B"
97
+ tokenizer = mm_utils.get_tokenizer(model_id=model_id, max_seq_length=768)
98
+ _, _, ds_test = mm_data.get_train_valid_test_datasets(
99
+ tokenizer=tokenizer, query_template="Question: {query} Think step by step.\nAnswer:", print_fn=noop
100
+ )
101
+
102
+ model = AutoModelForCausalLM.from_pretrained(model_id, dtype=torch.bfloat16).to(0)
103
+ model = PeftModel.from_pretrained(model, path_peft_model)
104
+ if rank is None:
105
+ print("Evaluating the original PEFT model without LoRA conversion...")
106
+ model.set_adapter("default")
107
+ model.print_trainable_parameters()
108
+ model.eval()
109
+ evaluate_model(model, tokenizer, ds_test)
110
+ return
111
+
112
+ print(f"Converting PEFT model to LoRA with rank={rank}...")
113
+ tic = time.perf_counter()
114
+ lora_config, lora_state_dict = convert_to_lora(model, rank=rank, progressbar=True)
115
+ toc = time.perf_counter()
116
+ print(f"Conversion completed in {toc - tic:.0f} seconds.".format(toc - tic))
117
+
118
+ del model
119
+ torch.cuda.empty_cache()
120
+ model = AutoModelForCausalLM.from_pretrained(model_id, dtype=torch.bfloat16).to(0)
121
+
122
+ model = get_peft_model(model, lora_config)
123
+ model.print_trainable_parameters()
124
+
125
+ load_result = set_peft_model_state_dict(model, lora_state_dict)
126
+ assert not load_result.unexpected_keys, (
127
+ f"Unexpected keys when loading LoRA state dict: {load_result.unexpected_keys}"
128
+ )
129
+
130
+ del lora_state_dict
131
+ model.eval()
132
+ evaluate_model(model, tokenizer, ds_test)
133
+
134
+
135
+ if __name__ == "__main__":
136
+ parser = argparse.ArgumentParser(description="Evaluate a PEFT checkpoint converted into a LoRA on GSM8K")
137
+ parser.add_argument(
138
+ "--path",
139
+ type=str,
140
+ required=True,
141
+ help="Path to the input PEFT checkpoint",
142
+ )
143
+ parser.add_argument(
144
+ "--rank",
145
+ required=False,
146
+ default=None,
147
+ help="Rank for the LoRA decomposition (int, float, or None for no conversion)",
148
+ )
149
+
150
+ args = parser.parse_args()
151
+ if args.rank is not None:
152
+ if "." in str(args.rank):
153
+ args.rank = float(args.rank)
154
+ else:
155
+ args.rank = int(args.rank)
156
+ main(args.path, args.rank)
tasks/tasksmith-749ff8d440e1/environment/source/scripts/launch_notebook_mp.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # This is a minimal example of launching PEFT with Accelerate. This used to cause issues because PEFT would eagerly
16
+ # import bitsandbytes, which initializes CUDA, resulting in:
17
+ # > RuntimeError: Cannot re-initialize CUDA in forked subprocess. To use CUDA with multiprocessing, you must use the
18
+ # > 'spawn' start method
19
+ # This script exists to ensure that this issue does not reoccur.
20
+
21
+ import torch
22
+ from accelerate import notebook_launcher
23
+
24
+ import peft
25
+ from peft.utils import infer_device
26
+
27
+
28
+ def init():
29
+ class MyModule(torch.nn.Module):
30
+ def __init__(self):
31
+ super().__init__()
32
+ self.linear = torch.nn.Linear(1, 2)
33
+
34
+ def forward(self, x):
35
+ return self.linear(x)
36
+
37
+ device = infer_device()
38
+ model = MyModule().to(device)
39
+ peft.get_peft_model(model, peft.LoraConfig(target_modules=["linear"]))
40
+
41
+
42
+ def main():
43
+ notebook_launcher(init, (), num_processes=2)
44
+
45
+
46
+ if __name__ == "__main__":
47
+ main()
tasks/tasksmith-749ff8d440e1/environment/source/scripts/log_reports.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import os
4
+ from datetime import UTC, datetime
5
+ from pathlib import Path
6
+
7
+ from tabulate import tabulate
8
+
9
+
10
+ MAX_LEN_MESSAGE = 2900 # slack endpoint has a limit of 3001 characters
11
+
12
+ parser = argparse.ArgumentParser()
13
+ parser.add_argument(
14
+ "--slack_channel_name",
15
+ default="peft-ci-daily",
16
+ )
17
+
18
+
19
+ def main(slack_channel_name=None):
20
+ failed = []
21
+ passed = []
22
+
23
+ group_info = []
24
+
25
+ total_num_failed = 0
26
+ empty_file = False or len(list(Path().glob("*.log"))) == 0
27
+
28
+ total_empty_files = []
29
+
30
+ for log in Path().glob("*.log"):
31
+ section_num_failed = 0
32
+ i = 0
33
+ with open(log) as f:
34
+ for line in f:
35
+ line = json.loads(line)
36
+ i += 1
37
+ if line.get("nodeid", "") != "":
38
+ test = line["nodeid"]
39
+ if line.get("duration", None) is not None:
40
+ duration = f"{line['duration']:.4f}"
41
+ if line.get("outcome", "") == "failed":
42
+ section_num_failed += 1
43
+ failed.append([test, duration, log.name.split("_")[0]])
44
+ total_num_failed += 1
45
+ else:
46
+ passed.append([test, duration, log.name.split("_")[0]])
47
+ empty_file = i == 0
48
+ group_info.append([str(log), section_num_failed, failed])
49
+ total_empty_files.append(empty_file)
50
+ os.remove(log)
51
+ failed = []
52
+ text = (
53
+ "🌞 There were no failures!"
54
+ if not any(total_empty_files)
55
+ else "Something went wrong there is at least one empty file - please check GH action results."
56
+ )
57
+ no_error_payload = {
58
+ "type": "section",
59
+ "text": {
60
+ "type": "plain_text",
61
+ "text": text,
62
+ "emoji": True,
63
+ },
64
+ }
65
+
66
+ message = ""
67
+ payload = [
68
+ {
69
+ "type": "header",
70
+ "text": {
71
+ "type": "plain_text",
72
+ "text": "🤗 Results of the {} PEFT scheduled tests.".format(os.environ.get("TEST_TYPE", "")),
73
+ },
74
+ },
75
+ ]
76
+ if total_num_failed > 0:
77
+ for i, (name, num_failed, failed_tests) in enumerate(group_info):
78
+ if num_failed > 0:
79
+ if num_failed == 1:
80
+ message += f"*{name}: {num_failed} failed test*\n"
81
+ else:
82
+ message += f"*{name}: {num_failed} failed tests*\n"
83
+ failed_table = []
84
+ for test in failed_tests:
85
+ failed_table.append(test[0].split("::"))
86
+ failed_table = tabulate(
87
+ failed_table,
88
+ headers=["Test Location", "Test Case", "Test Name"],
89
+ showindex="always",
90
+ tablefmt="grid",
91
+ maxcolwidths=[12, 12, 12],
92
+ )
93
+ message += "\n```\n" + failed_table + "\n```"
94
+
95
+ if total_empty_files[i]:
96
+ message += f"\n*{name}: Warning! Empty file - please check the GitHub action job *\n"
97
+ print(f"### {message}")
98
+ else:
99
+ payload.append(no_error_payload)
100
+
101
+ if os.environ.get("TEST_TYPE", "") != "":
102
+ from slack_sdk import WebClient
103
+
104
+ if len(message) > MAX_LEN_MESSAGE:
105
+ print(f"Truncating long message from {len(message)} to {MAX_LEN_MESSAGE}")
106
+ message = message[:MAX_LEN_MESSAGE] + "..."
107
+
108
+ if len(message) != 0:
109
+ md_report = {
110
+ "type": "section",
111
+ "text": {"type": "mrkdwn", "text": message},
112
+ }
113
+ payload.append(md_report)
114
+ action_button = {
115
+ "type": "section",
116
+ "text": {"type": "mrkdwn", "text": "*For more details:*"},
117
+ "accessory": {
118
+ "type": "button",
119
+ "text": {"type": "plain_text", "text": "Check Action results", "emoji": True},
120
+ "url": f"https://github.com/huggingface/peft/actions/runs/{os.environ['GITHUB_RUN_ID']}",
121
+ },
122
+ }
123
+ payload.append(action_button)
124
+
125
+ date_report = {
126
+ "type": "context",
127
+ "elements": [
128
+ {
129
+ "type": "plain_text",
130
+ "text": f"Nightly {os.environ.get('TEST_TYPE')} test results for {datetime.now(UTC).date()}",
131
+ },
132
+ ],
133
+ }
134
+ payload.append(date_report)
135
+
136
+ print(payload)
137
+
138
+ client = WebClient(token=os.environ.get("SLACK_API_TOKEN"))
139
+ client.chat_postMessage(channel=f"#{slack_channel_name}", text=message, blocks=payload)
140
+
141
+
142
+ if __name__ == "__main__":
143
+ args = parser.parse_args()
144
+ main(args.slack_channel_name)
tasks/tasksmith-749ff8d440e1/environment/source/scripts/stale.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team, the AllenNLP library authors. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """
15
+ Script to close stale issue. Taken in part from the AllenNLP repository.
16
+ https://github.com/allenai/allennlp.
17
+ """
18
+
19
+ import os
20
+ from datetime import datetime as dt
21
+ from datetime import timezone
22
+
23
+ from github import Github
24
+
25
+
26
+ LABELS_TO_EXEMPT = [
27
+ "good first issue",
28
+ "good second issue",
29
+ "good difficult issue",
30
+ "feature request",
31
+ "new model",
32
+ "wip",
33
+ "PRs welcome to address this",
34
+ ]
35
+
36
+
37
+ def main():
38
+ g = Github(os.environ["GITHUB_TOKEN"])
39
+ repo = g.get_repo("huggingface/peft")
40
+ open_issues = repo.get_issues(state="open")
41
+
42
+ for issue in open_issues:
43
+ comments = sorted(issue.get_comments(), key=lambda i: i.created_at, reverse=True)
44
+ last_comment = comments[0] if len(comments) > 0 else None
45
+ if (
46
+ (last_comment is not None and last_comment.user.login == "github-actions[bot]")
47
+ and (dt.now(timezone.utc) - issue.updated_at).days > 7
48
+ and (dt.now(timezone.utc) - issue.created_at).days >= 30
49
+ and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels())
50
+ ):
51
+ issue.edit(state="closed")
52
+ elif (
53
+ (dt.now(timezone.utc) - issue.updated_at).days > 23
54
+ and (dt.now(timezone.utc) - issue.created_at).days >= 30
55
+ and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels())
56
+ ):
57
+ issue.create_comment(
58
+ "This issue has been automatically marked as stale because it has not had "
59
+ "recent activity. If you think this still needs to be addressed "
60
+ "please comment on this thread.\n\n"
61
+ )
62
+
63
+
64
+ if __name__ == "__main__":
65
+ main()
tasks/tasksmith-749ff8d440e1/environment/source/scripts/train_memory.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """This script trains a model on a small text dataset and measures the memory consumption, as well as a few other
16
+ useful metrics.
17
+
18
+ Example:
19
+
20
+ Get help:
21
+
22
+ ```bash
23
+ python train_memory.py --help
24
+ ```
25
+
26
+ Train the google/gemma-2-2b model with a LoRA config json at the indicated location.
27
+
28
+ ```bash
29
+ python train_memory.py "google/gemma-2-2b" --max_seq_length 256 --batch_size 1 --rank 32 --dtype bfloat16 --path_config <path-to-adapter-config.json>
30
+ ```
31
+
32
+ Fully fine-tune the model (i.e. without LoRA) by setting the rank to 0:
33
+
34
+ ```bash
35
+ python train_memory.py "google/gemma-2-2b" --rank 0
36
+ ```
37
+
38
+ 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:
39
+
40
+ ```bash
41
+ 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
42
+ ```
43
+
44
+ """
45
+
46
+ import argparse
47
+ import gc
48
+ import os
49
+ import sys
50
+ import tempfile
51
+ import time
52
+ import warnings
53
+ from collections import Counter
54
+ from contextlib import nullcontext
55
+ from functools import partial
56
+
57
+ import torch
58
+ from datasets import load_dataset
59
+ from torch import nn
60
+ from transformers import (
61
+ AutoModelForCausalLM,
62
+ AutoTokenizer,
63
+ BitsAndBytesConfig,
64
+ )
65
+
66
+ from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
67
+ from peft.utils import CONFIG_NAME, SAFETENSORS_WEIGHTS_NAME
68
+
69
+
70
+ # suppress all warnings
71
+ warnings.filterwarnings("ignore")
72
+
73
+ device = torch.accelerator.current_accelerator().type if hasattr(torch, "accelerator") else "cuda"
74
+ dtype_to_bytes_linear = {"float32": 4, "float16": 2, "bfloat16": 2, "int8": 1, "int4": 0.5}
75
+
76
+
77
+ def init_accelerator():
78
+ torch.manual_seed(0)
79
+ if device == "cpu":
80
+ return
81
+
82
+ device_module = getattr(torch, device, torch.cuda)
83
+ device_module.reset_peak_memory_stats()
84
+ device_module.manual_seed_all(0)
85
+ # might not be necessary, but just to be sure
86
+ nn.Linear(1, 1).to(device)
87
+
88
+
89
+ def get_data(tokenizer):
90
+ def tokenize(samples):
91
+ # For some reason, the max sequence length is not honored by the tokenizer, resulting in IndexErrors. Thus,
92
+ # manually ensure that sequences are not too long.
93
+ tokenized = tokenizer(samples["quote"])
94
+ tokenized["input_ids"] = [input_ids[: tokenizer.model_max_length] for input_ids in tokenized["input_ids"]]
95
+ tokenized["attention_mask"] = [
96
+ input_ids[: tokenizer.model_max_length] for input_ids in tokenized["attention_mask"]
97
+ ]
98
+ return tokenized
99
+
100
+ data = load_dataset("ybelkada/english_quotes_copy")
101
+ data = data.map(tokenize, batched=True)
102
+ # We need to manually remove unused columns. This is because we cannot use remove_unused_columns=True in the
103
+ # Trainer, as this leads to errors with torch.compile. We also cannot just leave them in, as they contain
104
+ # strings. Therefore, manually remove all unused columns.
105
+ data = data.remove_columns(["quote", "author", "tags"])
106
+ return data
107
+
108
+
109
+ def train(model_id, rank, dtype, monitor_tensors, max_seq_length, batch_size, max_steps, path_config):
110
+ init_accelerator()
111
+ device_module = getattr(torch, device, torch.cuda)
112
+ accelerator_memory_init = device_module.max_memory_allocated()
113
+ accelerator_memory_log = []
114
+
115
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
116
+ tokenizer.model_max_length = max_seq_length
117
+ if not tokenizer.pad_token:
118
+ tokenizer.pad_token = tokenizer.eos_token
119
+ data = get_data(tokenizer)
120
+
121
+ if dtype == "int4":
122
+ quant_config = BitsAndBytesConfig(load_in_4bit=True)
123
+ model = AutoModelForCausalLM.from_pretrained(model_id, device_map=device, quantization_config=quant_config)
124
+ model = prepare_model_for_kbit_training(model)
125
+ elif dtype == "int8":
126
+ quant_config = BitsAndBytesConfig(load_in_8bit=True)
127
+ model = AutoModelForCausalLM.from_pretrained(model_id, device_map=device, quantization_config=quant_config)
128
+ model = prepare_model_for_kbit_training(model)
129
+ elif dtype == "bfloat16":
130
+ model = AutoModelForCausalLM.from_pretrained(model_id, device_map=device, torch_dtype=torch.bfloat16)
131
+ elif dtype == "float16":
132
+ model = AutoModelForCausalLM.from_pretrained(model_id, device_map=device, torch_dtype=torch.float16)
133
+ elif dtype == "float32":
134
+ model = AutoModelForCausalLM.from_pretrained(model_id, device_map=device)
135
+ else:
136
+ raise ValueError(f"Invalid dtype: {dtype}")
137
+
138
+ if rank > 0:
139
+ if path_config is None:
140
+ raise RuntimeError("LoRA rank > 0 requires a path to a LoRA config")
141
+ if path_config.endswith(CONFIG_NAME):
142
+ path_config = path_config.removesuffix(CONFIG_NAME)
143
+ config = LoraConfig.from_pretrained(path_config)
144
+ model = get_peft_model(model, config)
145
+ model.print_trainable_parameters()
146
+ else:
147
+ print("Not using LoRA")
148
+
149
+ model.config.use_cache = False
150
+ storage = []
151
+
152
+ def pack(x):
153
+ storage.append(x)
154
+ return len(storage) - 1
155
+
156
+ def unpack(x):
157
+ return storage[x]
158
+
159
+ train_ctx = partial(torch.autograd.graph.saved_tensors_hooks, pack, unpack) if monitor_tensors else nullcontext
160
+
161
+ optimizer = torch.optim.AdamW(model.parameters(), lr=1e-5)
162
+ losses = []
163
+ sample = 0
164
+ tic_total = time.perf_counter()
165
+ for i in range(max_steps):
166
+ storage.clear()
167
+ tic = time.perf_counter()
168
+ try:
169
+ batch = tokenizer.pad(data["train"][sample : sample + batch_size], return_tensors="pt").to(model.device)
170
+ sample += batch_size
171
+
172
+ # add targets
173
+ batch["labels"] = batch["input_ids"].clone()
174
+ optimizer.zero_grad()
175
+
176
+ with train_ctx():
177
+ outputs = model(**batch)
178
+ loss = outputs.loss
179
+ loss.backward()
180
+ optimizer.step()
181
+ losses.append(loss.item())
182
+ accelerator_memory_log.append(device_module.memory_allocated() - accelerator_memory_init)
183
+ device_module.empty_cache()
184
+ gc.collect()
185
+ toc = time.perf_counter()
186
+ print(f"step {i:3d} loss {loss.item():.6f} time {toc - tic:.2f}s", file=sys.stderr)
187
+ except KeyboardInterrupt:
188
+ print("canceled training")
189
+ break
190
+
191
+ if monitor_tensors:
192
+ break
193
+
194
+ toc_total = time.perf_counter()
195
+
196
+ accelerator_memory_final = device_module.max_memory_allocated()
197
+ accelerator_memory_avg = int(sum(accelerator_memory_log) / len(accelerator_memory_log))
198
+ print(f"{model.device.type} memory avg: {accelerator_memory_avg // 2**20}MB")
199
+ print(f"{model.device.type} memory max: {(accelerator_memory_final - accelerator_memory_init) // 2**20}MB")
200
+ print(f"total time: {toc_total - tic_total:.2f}s")
201
+
202
+ with tempfile.TemporaryDirectory() as tmp_dir:
203
+ model.save_pretrained(tmp_dir)
204
+ stat = os.stat(os.path.join(tmp_dir, SAFETENSORS_WEIGHTS_NAME))
205
+ file_size = stat.st_size
206
+ print(f"file size: {file_size / 2**20:.1f}MB")
207
+
208
+ if monitor_tensors:
209
+ dtype_counts = Counter(t.dtype for t in storage)
210
+ shape_counts = Counter(t.shape for t in storage)
211
+ param_shape_counts = Counter(p.shape for p in model.parameters())
212
+ param_shape_counts_copy = dict(param_shape_counts).copy()
213
+
214
+ # shape counts includes the params, so we need to subtract them; note that they can be transposed
215
+ # this is an approximation
216
+ diff_shape_counts = {}
217
+ for shape, count in shape_counts.items():
218
+ if shape in param_shape_counts_copy:
219
+ diff_count = count - param_shape_counts[shape]
220
+ if diff_count > 0:
221
+ diff_shape_counts[shape] = diff_count
222
+ param_shape_counts_copy[shape] = max(0, param_shape_counts_copy[shape] - diff_count)
223
+ elif shape[::-1] in param_shape_counts:
224
+ diff_count = count - param_shape_counts[shape[::-1]]
225
+ if diff_count > 0:
226
+ diff_shape_counts[shape] = diff_count
227
+ param_shape_counts_copy[shape[::-1]] = max(0, param_shape_counts_copy[shape[::-1]] - diff_count)
228
+ else:
229
+ diff_shape_counts[shape] = count
230
+
231
+ total_size = sum(t.numel() * t.element_size() for t in storage)
232
+ total_size_mb = f"{total_size // 2**20}MB"
233
+ diff_size = 0
234
+ for shape, count in diff_shape_counts.items():
235
+ diff_size += count * torch.zeros(shape).numel() * dtype_to_bytes_linear[dtype]
236
+ param_size = total_size - diff_size
237
+
238
+ diff_size_mb = f"{diff_size // 2**20}MB"
239
+ param_size_mb = f"{param_size // 2**20}MB"
240
+
241
+ print(f"Dtype counts: {dtype_counts.most_common()}")
242
+ print(f"Total size of tensors: {total_size_mb: >12}")
243
+ print(f"Total size of activations: {diff_size_mb: >12}")
244
+ print(f"Total size of parameters: {param_size_mb: >12}")
245
+
246
+
247
+ if __name__ == "__main__":
248
+ parser = argparse.ArgumentParser()
249
+ parser.add_argument("model_id", type=str, help="Model name on Hugging Face Hub")
250
+ parser.add_argument("--rank", type=int, default=8, help="Rank of LoRA, 0 => no LoRA, default 8")
251
+ parser.add_argument(
252
+ "--dtype",
253
+ type=str,
254
+ default="float32",
255
+ help="Data type, one of float32, float16, bfloat16, int8, int4, default float32",
256
+ )
257
+ parser.add_argument(
258
+ "--monitor_tensors",
259
+ action="store_true",
260
+ help="Monitor tensor sizes during training for a single training step, off by default",
261
+ )
262
+ parser.add_argument("--max_seq_length", type=int, default=128, help="Maximum sequence length, default 128")
263
+ parser.add_argument("--batch_size", type=int, default=1, help="Batch size, default 1")
264
+ parser.add_argument("--max_steps", type=int, default=50, help="Maximum number of training steps, default 50")
265
+ parser.add_argument("--path_config", type=str, default=None, help="Path to LoRA config")
266
+ args = parser.parse_args()
267
+ train(
268
+ model_id=args.model_id,
269
+ rank=args.rank,
270
+ dtype=args.dtype,
271
+ monitor_tensors=args.monitor_tensors,
272
+ max_seq_length=args.max_seq_length,
273
+ batch_size=args.batch_size,
274
+ max_steps=args.max_steps,
275
+ path_config=args.path_config,
276
+ )
tasks/tasksmith-749ff8d440e1/environment/source/setup.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from setuptools import find_packages, setup
16
+
17
+
18
+ VERSION = "0.19.2.dev0"
19
+
20
+ extras = {}
21
+ extras["quality"] = [
22
+ "black", # doc-builder has an implicit dependency on Black, see huggingface/doc-builder#434
23
+ "hf-doc-builder",
24
+ # when upgrading this, also upgrade required version in pyproject.toml and pre-commit-config.yaml
25
+ "ruff~=0.15.12",
26
+ ]
27
+ extras["docs_specific"] = [
28
+ "black", # doc-builder has an implicit dependency on Black, see huggingface/doc-builder#434
29
+ "requests", # doc-builder has an implicit dependency on requests (setup.py doesn't mention it, pyproject does)
30
+ "hf-doc-builder",
31
+ ]
32
+ extras["dev"] = extras["quality"] + extras["docs_specific"]
33
+ extras["test"] = extras["dev"] + [
34
+ "pytest",
35
+ "pytest-cov",
36
+ "pytest-xdist",
37
+ "parameterized",
38
+ "datasets",
39
+ "diffusers",
40
+ "scipy",
41
+ "scikit-learn",
42
+ "protobuf",
43
+ "sentencepiece",
44
+ "torchvision",
45
+ ]
46
+
47
+ with open("README.md", encoding="utf-8") as f:
48
+ long_description = f.read()
49
+
50
+ setup(
51
+ name="peft",
52
+ version=VERSION,
53
+ description="Parameter-Efficient Fine-Tuning (PEFT)",
54
+ license_files=["LICENSE"],
55
+ long_description=long_description,
56
+ long_description_content_type="text/markdown",
57
+ keywords="deep learning",
58
+ license="Apache",
59
+ author="The HuggingFace team",
60
+ author_email="benjamin@huggingface.co",
61
+ url="https://github.com/huggingface/peft",
62
+ package_dir={"": "src"},
63
+ packages=find_packages("src"),
64
+ package_data={"peft": ["py.typed", "tuners/boft/fbd/fbd_cuda.cpp", "tuners/boft/fbd/fbd_cuda_kernel.cu"]},
65
+ entry_points={},
66
+ python_requires=">=3.10.0",
67
+ install_requires=[
68
+ "numpy>=1.17",
69
+ "packaging>=20.0",
70
+ "psutil",
71
+ "pyyaml",
72
+ "torch>=1.13.0",
73
+ "transformers",
74
+ "tqdm",
75
+ "accelerate>=0.21.0",
76
+ "safetensors",
77
+ "huggingface_hub>=0.25.0",
78
+ ],
79
+ extras_require=extras,
80
+ classifiers=[
81
+ "Development Status :: 5 - Production/Stable",
82
+ "Intended Audience :: Developers",
83
+ "Intended Audience :: Education",
84
+ "Intended Audience :: Science/Research",
85
+ "License :: OSI Approved :: Apache Software License",
86
+ "Operating System :: OS Independent",
87
+ "Programming Language :: Python :: 3",
88
+ "Programming Language :: Python :: 3.10",
89
+ "Programming Language :: Python :: 3.11",
90
+ "Programming Language :: Python :: 3.12",
91
+ "Programming Language :: Python :: 3.13",
92
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
93
+ ],
94
+ )
95
+
96
+ # Release checklist
97
+ # 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"
98
+ # 2. Check if there are any deprecations that need to be addressed for this release by searching for "# TODO" in the code
99
+ # 3. Commit these changes with the message: "Release: VERSION", create a PR and merge it.
100
+ # 4. Add a tag in git to mark the release: "git tag -a v<VERSION> -m 'Adds tag <VERSION> for pypi' "
101
+ # Push the tag to git:
102
+ # git push --tags origin main
103
+ # It is necessary to work on the original repository, not on a fork.
104
+ # 5. Run the following commands in the top-level directory:
105
+ # python setup.py bdist_wheel
106
+ # python setup.py sdist
107
+ # Ensure that you are on the clean and up-to-date main branch (git status --untracked-files=no should not list any
108
+ # files and show the main branch)
109
+ # 6. Upload the package to the pypi test server first:
110
+ # twine upload dist/* -r pypitest
111
+ # 7. Check that you can install it in a virtualenv by running:
112
+ # pip install -i https://testpypi.python.org/pypi --extra-index-url https://pypi.org/simple peft
113
+ # 8. Upload the final version to actual pypi:
114
+ # twine upload dist/* -r pypi
115
+ # 9. Add release notes to the tag on https://github.com/huggingface/peft/releases once everything is looking hunky-dory.
116
+ # Check the notes here: https://docs.google.com/document/d/1k-sOIfykuKjWcOIALqjhFKz4amFEp-myeJUJEzNgjoU/edit?usp=sharing
117
+ # 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")
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/__init__.py ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ __version__ = "0.19.2.dev0"
16
+
17
+ from .auto import (
18
+ MODEL_TYPE_TO_PEFT_MODEL_MAPPING,
19
+ AutoPeftModel,
20
+ AutoPeftModelForCausalLM,
21
+ AutoPeftModelForFeatureExtraction,
22
+ AutoPeftModelForQuestionAnswering,
23
+ AutoPeftModelForSeq2SeqLM,
24
+ AutoPeftModelForSequenceClassification,
25
+ AutoPeftModelForTokenClassification,
26
+ )
27
+ from .config import PeftConfig, PromptLearningConfig
28
+ from .helpers import find_kappa_target_modules
29
+ from .mapping import (
30
+ PEFT_TYPE_TO_CONFIG_MAPPING,
31
+ PEFT_TYPE_TO_MIXED_MODEL_MAPPING,
32
+ PEFT_TYPE_TO_TUNER_MAPPING,
33
+ get_peft_config,
34
+ inject_adapter_in_model,
35
+ )
36
+ from .mapping_func import get_peft_model
37
+ from .mixed_model import PeftMixedModel
38
+ from .peft_model import (
39
+ PeftModel,
40
+ PeftModelForCausalLM,
41
+ PeftModelForFeatureExtraction,
42
+ PeftModelForQuestionAnswering,
43
+ PeftModelForSeq2SeqLM,
44
+ PeftModelForSequenceClassification,
45
+ PeftModelForTokenClassification,
46
+ get_layer_status,
47
+ get_model_status,
48
+ )
49
+ from .tuners import (
50
+ AdaLoraConfig,
51
+ AdaLoraModel,
52
+ AdamssConfig,
53
+ AdamssModel,
54
+ AdaptionPromptConfig,
55
+ AdaptionPromptModel,
56
+ ArrowConfig,
57
+ BdLoraConfig,
58
+ BeftConfig,
59
+ BeftModel,
60
+ BOFTConfig,
61
+ BOFTModel,
62
+ C3AConfig,
63
+ C3AModel,
64
+ CartridgeConfig,
65
+ CartridgeEncoder,
66
+ CPTConfig,
67
+ CPTEmbedding,
68
+ DeloraConfig,
69
+ DeloraModel,
70
+ EvaConfig,
71
+ FourierFTConfig,
72
+ FourierFTModel,
73
+ GraloraConfig,
74
+ GraloraModel,
75
+ HiraConfig,
76
+ HiraModel,
77
+ HRAConfig,
78
+ HRAModel,
79
+ IA3Config,
80
+ IA3Model,
81
+ LilyConfig,
82
+ LilyModel,
83
+ LNTuningConfig,
84
+ LNTuningModel,
85
+ LoftQConfig,
86
+ LoHaConfig,
87
+ LoHaModel,
88
+ LoKrConfig,
89
+ LoKrModel,
90
+ LoraConfig,
91
+ LoraGAConfig,
92
+ LoraModel,
93
+ LoraRuntimeConfig,
94
+ MissConfig,
95
+ MissModel,
96
+ MontecloraConfig,
97
+ MultitaskPromptTuningConfig,
98
+ MultitaskPromptTuningInit,
99
+ OFTConfig,
100
+ OFTModel,
101
+ OSFConfig,
102
+ OSFModel,
103
+ PeanutConfig,
104
+ PeanutModel,
105
+ PolyConfig,
106
+ PolyModel,
107
+ PrefixEncoder,
108
+ PrefixTuningConfig,
109
+ PromptEmbedding,
110
+ PromptEncoder,
111
+ PromptEncoderConfig,
112
+ PromptEncoderReparameterizationType,
113
+ PromptTuningConfig,
114
+ PromptTuningInit,
115
+ PsoftConfig,
116
+ PsoftModel,
117
+ PveraConfig,
118
+ PveraModel,
119
+ RandLoraConfig,
120
+ RandLoraModel,
121
+ RoadConfig,
122
+ RoadModel,
123
+ ShiraConfig,
124
+ ShiraModel,
125
+ TinyLoraConfig,
126
+ TinyLoraModel,
127
+ TrainableTokensConfig,
128
+ TrainableTokensModel,
129
+ VBLoRAConfig,
130
+ VBLoRAModel,
131
+ VeloraConfig,
132
+ VeraConfig,
133
+ VeraModel,
134
+ WaveFTConfig,
135
+ WaveFTModel,
136
+ XLoraConfig,
137
+ XLoraModel,
138
+ convert_to_lora,
139
+ create_arrow_model,
140
+ get_eva_state_dict,
141
+ initialize_lora_eva_weights,
142
+ preprocess_loraga,
143
+ save_as_lora,
144
+ )
145
+ from .tuners.cartridge.utils import (
146
+ compose_cartridge_adapters,
147
+ initialize_kv_prefix_from_past_key_values,
148
+ initialize_kv_prefix_from_text,
149
+ prompt_embeddings_from_past_key_values,
150
+ )
151
+ from .utils import (
152
+ TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING,
153
+ PeftType,
154
+ PeftWarning,
155
+ TaskType,
156
+ bloom_model_postprocess_past_key_value,
157
+ cast_mixed_precision_params,
158
+ get_peft_model_state_dict,
159
+ load_peft_weights,
160
+ prepare_model_for_kbit_training,
161
+ replace_lora_weights_loftq,
162
+ set_peft_model_state_dict,
163
+ shift_tokens_right,
164
+ )
165
+
166
+
167
+ __all__ = [
168
+ "MODEL_TYPE_TO_PEFT_MODEL_MAPPING",
169
+ "PEFT_TYPE_TO_CONFIG_MAPPING",
170
+ "PEFT_TYPE_TO_MIXED_MODEL_MAPPING",
171
+ "PEFT_TYPE_TO_TUNER_MAPPING",
172
+ "TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING",
173
+ "AdaLoraConfig",
174
+ "AdaLoraModel",
175
+ "AdamssConfig",
176
+ "AdamssModel",
177
+ "AdaptionPromptConfig",
178
+ "AdaptionPromptModel",
179
+ "ArrowConfig",
180
+ "AutoPeftModel",
181
+ "AutoPeftModelForCausalLM",
182
+ "AutoPeftModelForFeatureExtraction",
183
+ "AutoPeftModelForQuestionAnswering",
184
+ "AutoPeftModelForSeq2SeqLM",
185
+ "AutoPeftModelForSequenceClassification",
186
+ "AutoPeftModelForTokenClassification",
187
+ "BOFTConfig",
188
+ "BOFTModel",
189
+ "BdLoraConfig",
190
+ "BeftConfig",
191
+ "BeftModel",
192
+ "C3AConfig",
193
+ "C3AModel",
194
+ "CPTConfig",
195
+ "CPTEmbedding",
196
+ "CartridgeConfig",
197
+ "CartridgeEncoder",
198
+ "DeloraConfig",
199
+ "DeloraModel",
200
+ "EvaConfig",
201
+ "FourierFTConfig",
202
+ "FourierFTModel",
203
+ "GraloraConfig",
204
+ "GraloraModel",
205
+ "HRAConfig",
206
+ "HRAModel",
207
+ "HiraConfig",
208
+ "HiraModel",
209
+ "IA3Config",
210
+ "IA3Model",
211
+ "LNTuningConfig",
212
+ "LNTuningModel",
213
+ "LilyConfig",
214
+ "LilyModel",
215
+ "LoHaConfig",
216
+ "LoHaModel",
217
+ "LoKrConfig",
218
+ "LoKrModel",
219
+ "LoftQConfig",
220
+ "LoraConfig",
221
+ "LoraGAConfig",
222
+ "LoraModel",
223
+ "LoraRuntimeConfig",
224
+ "MissConfig",
225
+ "MissModel",
226
+ "MontecloraConfig",
227
+ "MultitaskPromptTuningConfig",
228
+ "MultitaskPromptTuningInit",
229
+ "OFTConfig",
230
+ "OFTModel",
231
+ "OSFConfig",
232
+ "OSFModel",
233
+ "PeanutConfig",
234
+ "PeanutModel",
235
+ "PeftConfig",
236
+ "PeftMixedModel",
237
+ "PeftModel",
238
+ "PeftModelForCausalLM",
239
+ "PeftModelForFeatureExtraction",
240
+ "PeftModelForQuestionAnswering",
241
+ "PeftModelForSeq2SeqLM",
242
+ "PeftModelForSequenceClassification",
243
+ "PeftModelForTokenClassification",
244
+ "PeftType",
245
+ "PeftWarning",
246
+ "PolyConfig",
247
+ "PolyModel",
248
+ "PrefixEncoder",
249
+ "PrefixTuningConfig",
250
+ "PromptEmbedding",
251
+ "PromptEncoder",
252
+ "PromptEncoderConfig",
253
+ "PromptEncoderReparameterizationType",
254
+ "PromptLearningConfig",
255
+ "PromptTuningConfig",
256
+ "PromptTuningInit",
257
+ "PsoftConfig",
258
+ "PsoftModel",
259
+ "PveraConfig",
260
+ "PveraModel",
261
+ "RandLoraConfig",
262
+ "RandLoraModel",
263
+ "RoadConfig",
264
+ "RoadModel",
265
+ "ShiraConfig",
266
+ "ShiraModel",
267
+ "TaskType",
268
+ "TinyLoraConfig",
269
+ "TinyLoraModel",
270
+ "TrainableTokensConfig",
271
+ "TrainableTokensModel",
272
+ "VBLoRAConfig",
273
+ "VBLoRAConfig",
274
+ "VBLoRAModel",
275
+ "VeloraConfig",
276
+ "VeraConfig",
277
+ "VeraModel",
278
+ "WaveFTConfig",
279
+ "WaveFTModel",
280
+ "XLoraConfig",
281
+ "XLoraModel",
282
+ "bloom_model_postprocess_past_key_value",
283
+ "cast_mixed_precision_params",
284
+ "compose_cartridge_adapters",
285
+ "convert_to_lora",
286
+ "create_arrow_model",
287
+ "find_kappa_target_modules",
288
+ "get_eva_state_dict",
289
+ "get_layer_status",
290
+ "get_model_status",
291
+ "get_peft_config",
292
+ "get_peft_model",
293
+ "get_peft_model_state_dict",
294
+ "initialize_kv_prefix_from_past_key_values",
295
+ "initialize_kv_prefix_from_text",
296
+ "initialize_lora_eva_weights",
297
+ "inject_adapter_in_model",
298
+ "load_peft_weights",
299
+ "prepare_model_for_kbit_training",
300
+ "preprocess_loraga",
301
+ "prompt_embeddings_from_past_key_values",
302
+ "replace_lora_weights_loftq",
303
+ "save_as_lora",
304
+ "set_peft_model_state_dict",
305
+ "shift_tokens_right",
306
+ ]
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/auto.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ import importlib
18
+ import os
19
+ from typing import Optional
20
+
21
+ from transformers import (
22
+ AutoModel,
23
+ AutoModelForCausalLM,
24
+ AutoModelForQuestionAnswering,
25
+ AutoModelForSeq2SeqLM,
26
+ AutoModelForSequenceClassification,
27
+ AutoModelForTokenClassification,
28
+ AutoTokenizer,
29
+ )
30
+
31
+ from .config import PeftConfig
32
+ from .peft_model import (
33
+ PeftModel,
34
+ PeftModelForCausalLM,
35
+ PeftModelForFeatureExtraction,
36
+ PeftModelForQuestionAnswering,
37
+ PeftModelForSeq2SeqLM,
38
+ PeftModelForSequenceClassification,
39
+ PeftModelForTokenClassification,
40
+ )
41
+ from .utils.constants import TOKENIZER_CONFIG_NAME
42
+ from .utils.other import check_file_exists_on_hf_hub
43
+
44
+
45
+ MODEL_TYPE_TO_PEFT_MODEL_MAPPING: dict[str, type[PeftModel]] = {
46
+ "SEQ_CLS": PeftModelForSequenceClassification,
47
+ "SEQ_2_SEQ_LM": PeftModelForSeq2SeqLM,
48
+ "CAUSAL_LM": PeftModelForCausalLM,
49
+ "TOKEN_CLS": PeftModelForTokenClassification,
50
+ "QUESTION_ANS": PeftModelForQuestionAnswering,
51
+ "FEATURE_EXTRACTION": PeftModelForFeatureExtraction,
52
+ }
53
+
54
+
55
+ def get_default_import_allowlist():
56
+ return [
57
+ "diffusers",
58
+ "lerobot",
59
+ "megatron-core",
60
+ "transformers",
61
+ ]
62
+
63
+
64
+ def check_import_allowlist(allowlist, parent_name):
65
+ """Ensure that the parent_name is in the allowlist or, at least, the prefix (e.g., "transformers.").
66
+ This is done because PEFT uses importlib.import_module on adapter config values. To prevent PEFT being used as a
67
+ means to execute code by importing a potentially malicious package (i.e. as a means to execute planted code), we
68
+ limit the possible packages to a known value.
69
+ """
70
+ if parent_name in allowlist:
71
+ return True
72
+
73
+ return any(parent_name.startswith(f"{allowed}.") for allowed in allowlist)
74
+
75
+
76
+ class _BaseAutoPeftModel:
77
+ _target_class = None
78
+ _target_peft_class = None
79
+
80
+ def __init__(self, *args, **kwargs):
81
+ # For consistency with transformers: https://github.com/huggingface/transformers/blob/91d7df58b6537d385e90578dac40204cb550f706/src/transformers/models/auto/auto_factory.py#L400
82
+ raise EnvironmentError( # noqa: UP024
83
+ f"{self.__class__.__name__} is designed to be instantiated "
84
+ f"using the `{self.__class__.__name__}.from_pretrained(pretrained_model_name_or_path)` or "
85
+ f"`{self.__class__.__name__}.from_config(config)` methods."
86
+ )
87
+
88
+ @classmethod
89
+ def from_pretrained(
90
+ cls,
91
+ pretrained_model_name_or_path,
92
+ adapter_name: str = "default",
93
+ is_trainable: bool = False,
94
+ config: Optional[PeftConfig] = None,
95
+ revision: Optional[str] = None,
96
+ import_allowlist: Optional[list[str]] = None,
97
+ **kwargs,
98
+ ):
99
+ r"""
100
+ A wrapper around all the preprocessing steps a user needs to perform in order to load a PEFT model. The kwargs
101
+ are passed along to `PeftConfig` that automatically takes care of filtering the kwargs of the Hub methods and
102
+ the config object init.
103
+
104
+ The parameters are equivalent to the ones of [`PeftModel.from_pretrained`]. Differences are documented below.
105
+
106
+ Args:
107
+ import_allowlist (`list[str]`, *optional*, defaults to `{get_default_import_allowlist()}`)
108
+ AutoPeftModel will attempt to instantiate the base model that is configured in the adapter config.
109
+ Since this operation needs to potentially import other packages, this allowlist is a safe-guard to
110
+ prevent importing malicious packages. You may need to specify your package's import name here if it is
111
+ not in the defaults.
112
+ """
113
+ peft_config = PeftConfig.from_pretrained(pretrained_model_name_or_path, revision=revision, **kwargs)
114
+ base_model_path = peft_config.base_model_name_or_path
115
+ base_model_revision = peft_config.revision
116
+
117
+ if import_allowlist is None:
118
+ import_allowlist = get_default_import_allowlist()
119
+
120
+ task_type = getattr(peft_config, "task_type", None)
121
+
122
+ if cls._target_class is not None:
123
+ target_class = cls._target_class
124
+ elif cls._target_class is None and task_type is not None:
125
+ # this is only in the case where we use `AutoPeftModel`
126
+ raise ValueError(
127
+ "Cannot use `AutoPeftModel` with a task type, please use a specific class for your task type. (e.g. `AutoPeftModelForCausalLM` for `task_type='CAUSAL_LM'`)"
128
+ )
129
+
130
+ if task_type is not None:
131
+ expected_target_class = MODEL_TYPE_TO_PEFT_MODEL_MAPPING[task_type]
132
+ if cls._target_peft_class.__name__ != expected_target_class.__name__:
133
+ raise ValueError(
134
+ f"Expected target PEFT class: {expected_target_class.__name__}, but you have asked for: {cls._target_peft_class.__name__}"
135
+ " make sure that you are loading the correct model for your task type."
136
+ )
137
+ elif task_type is None and getattr(peft_config, "auto_mapping", None) is not None:
138
+ auto_mapping = getattr(peft_config, "auto_mapping", None)
139
+ base_model_class = auto_mapping["base_model_class"]
140
+ parent_library_name = auto_mapping["parent_library"]
141
+
142
+ if not check_import_allowlist(import_allowlist, parent_library_name):
143
+ raise ValueError(
144
+ f"The auto mapping wants to import '{parent_library_name}' which is not in the import allowlist. "
145
+ "If you are sure that importing this library is safe, specify "
146
+ f"`import_allowlist=['{parent_library_name}']` in `from_pretrained()`."
147
+ )
148
+
149
+ parent_library = importlib.import_module(parent_library_name)
150
+ target_class = getattr(parent_library, base_model_class)
151
+ else:
152
+ raise ValueError(
153
+ "Cannot infer the auto class from the config, please make sure that you are loading the correct model for your task type."
154
+ )
155
+
156
+ base_model = target_class.from_pretrained(base_model_path, revision=base_model_revision, **kwargs)
157
+
158
+ tokenizer_exists = False
159
+ if os.path.exists(os.path.join(pretrained_model_name_or_path, TOKENIZER_CONFIG_NAME)):
160
+ tokenizer_exists = True
161
+ else:
162
+ token = kwargs.get("token", None)
163
+ if token is None:
164
+ token = kwargs.get("use_auth_token", None)
165
+
166
+ tokenizer_exists = check_file_exists_on_hf_hub(
167
+ repo_id=pretrained_model_name_or_path,
168
+ filename=TOKENIZER_CONFIG_NAME,
169
+ revision=revision,
170
+ repo_type=kwargs.get("repo_type", None),
171
+ token=token,
172
+ )
173
+
174
+ if tokenizer_exists and hasattr(base_model, "get_input_embeddings"):
175
+ tokenizer = AutoTokenizer.from_pretrained(
176
+ pretrained_model_name_or_path, trust_remote_code=kwargs.get("trust_remote_code", False)
177
+ )
178
+ embedding_size = base_model.get_input_embeddings().weight.shape[0]
179
+ if len(tokenizer) > embedding_size:
180
+ # only resize if the tokenizer has a larger vocab size than there are embeddings
181
+ base_model.resize_token_embeddings(len(tokenizer))
182
+
183
+ return cls._target_peft_class.from_pretrained(
184
+ base_model,
185
+ pretrained_model_name_or_path,
186
+ adapter_name=adapter_name,
187
+ is_trainable=is_trainable,
188
+ config=config,
189
+ **kwargs,
190
+ )
191
+
192
+
193
+ class AutoPeftModel(_BaseAutoPeftModel):
194
+ _target_class = None
195
+ _target_peft_class = PeftModel
196
+
197
+
198
+ class AutoPeftModelForCausalLM(_BaseAutoPeftModel):
199
+ _target_class = AutoModelForCausalLM
200
+ _target_peft_class = PeftModelForCausalLM
201
+
202
+
203
+ class AutoPeftModelForSeq2SeqLM(_BaseAutoPeftModel):
204
+ _target_class = AutoModelForSeq2SeqLM
205
+ _target_peft_class = PeftModelForSeq2SeqLM
206
+
207
+
208
+ class AutoPeftModelForSequenceClassification(_BaseAutoPeftModel):
209
+ _target_class = AutoModelForSequenceClassification
210
+ _target_peft_class = PeftModelForSequenceClassification
211
+
212
+
213
+ class AutoPeftModelForTokenClassification(_BaseAutoPeftModel):
214
+ _target_class = AutoModelForTokenClassification
215
+ _target_peft_class = PeftModelForTokenClassification
216
+
217
+
218
+ class AutoPeftModelForQuestionAnswering(_BaseAutoPeftModel):
219
+ _target_class = AutoModelForQuestionAnswering
220
+ _target_peft_class = PeftModelForQuestionAnswering
221
+
222
+
223
+ class AutoPeftModelForFeatureExtraction(_BaseAutoPeftModel):
224
+ _target_class = AutoModel
225
+ _target_peft_class = PeftModelForFeatureExtraction
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/config.py ADDED
@@ -0,0 +1,408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from __future__ import annotations
15
+
16
+ import importlib.metadata
17
+ import inspect
18
+ import json
19
+ import os
20
+ import warnings
21
+ from dataclasses import asdict, dataclass, field
22
+ from typing import Optional, Union
23
+
24
+ import packaging.version
25
+ from huggingface_hub import hf_hub_download
26
+ from transformers.utils import PushToHubMixin, http_user_agent
27
+
28
+ from peft import __version__
29
+
30
+ from .utils import CONFIG_NAME, PeftType, TaskType
31
+
32
+
33
+ # we expect at least these keys to be present in a PEFT adapter_config.json
34
+ MIN_EXPECTED_CONFIG_KEYS = {"peft_type"}
35
+
36
+
37
+ def _check_and_remove_unused_kwargs(cls, kwargs):
38
+ """Make PEFT configs forward-compatible by removing unused kwargs that were added in later PEFT versions.
39
+
40
+ This assumes that removing the unused kwargs will not affect the default behavior.
41
+
42
+ Returns the filtered kwargs and the set of removed keys.
43
+ """
44
+ # it's not pretty but eh
45
+ signature_parameters = inspect.signature(cls.__init__).parameters
46
+ unexpected_kwargs = set(kwargs.keys()) - set(signature_parameters.keys())
47
+ for key in unexpected_kwargs:
48
+ del kwargs[key]
49
+ return kwargs, unexpected_kwargs
50
+
51
+
52
+ def _is_dev_version(version: str) -> bool:
53
+ # check if the given version is a dev version
54
+ return packaging.version.Version(version).dev is not None
55
+
56
+
57
+ def _get_commit_hash(pkg_name: str) -> str | None:
58
+ # If PEFT was installed from a specific commit hash, try to get it. This works e.g. when installing PEFT with `pip
59
+ # install git+https://github.com/huggingface/peft.git@<HASH>`. This works not for other means, like editable
60
+ # installs.
61
+ try:
62
+ dist = importlib.metadata.distribution(pkg_name)
63
+ except importlib.metadata.PackageNotFoundError:
64
+ return None
65
+
66
+ # See: https://packaging.python.org/en/latest/specifications/direct-url/
67
+ for path in dist.files or []:
68
+ if path.name == "direct_url.json":
69
+ direct_url = json.loads((dist.locate_file(path)).read_text())
70
+ vcs_info = direct_url.get("vcs_info")
71
+ if vcs_info and "commit_id" in vcs_info:
72
+ return vcs_info["commit_id"]
73
+ return None
74
+
75
+
76
+ @dataclass
77
+ class PeftConfigMixin(PushToHubMixin):
78
+ r"""
79
+ This is the base configuration class for PEFT adapter models. It contains all the methods that are common to all
80
+ PEFT adapter models. This class inherits from [`~transformers.utils.PushToHubMixin`] which contains the methods to
81
+ push your model to the Hub. The method `save_pretrained` will save the configuration of your adapter model in a
82
+ directory. The method `from_pretrained` will load the configuration of your adapter model from a directory.
83
+
84
+ Args:
85
+ peft_type (Union[[`~peft.utils.config.PeftType`], `str`]): The type of Peft method to use.
86
+ """
87
+
88
+ task_type: Optional[TaskType] = field(default=None, metadata={"help": "The type of task."})
89
+ peft_type: Optional[PeftType] = field(default=None, metadata={"help": "The type of PEFT model."})
90
+ auto_mapping: Optional[dict] = field(
91
+ default=None, metadata={"help": "An auto mapping dict to help retrieve the base model class if needed."}
92
+ )
93
+ peft_version: Optional[str] = field(default=None, metadata={"help": "PEFT version, leave empty to auto-fill."})
94
+
95
+ def __post_init__(self):
96
+ # check for invalid task type
97
+ if (self.task_type is not None) and (self.task_type not in list(TaskType)):
98
+ raise ValueError(
99
+ f"Invalid task type: '{self.task_type}'. Must be one of the following task types: {', '.join(TaskType)}."
100
+ )
101
+ if self.peft_version is None:
102
+ self.peft_version = self._get_peft_version()
103
+
104
+ @staticmethod
105
+ def _get_peft_version() -> str:
106
+ # gets the current peft version; if it's a dev version, try to get the commit hash too, as the dev version is
107
+ # ambiguous
108
+ version = __version__
109
+ if not _is_dev_version(version):
110
+ return version
111
+
112
+ try:
113
+ git_hash = _get_commit_hash("peft")
114
+ if git_hash is None:
115
+ git_hash = "UNKNOWN"
116
+ except Exception:
117
+ # Broad exception: We never want to break user code just because the git_hash could not be determined
118
+ warnings.warn(
119
+ "A dev version of PEFT is used but there was an error while trying to determine the commit hash. "
120
+ "Please open an issue: https://github.com/huggingface/peft/issues"
121
+ )
122
+ git_hash = "UNKNOWN"
123
+ version = version + f"@{git_hash}"
124
+ return version
125
+
126
+ def to_dict(self) -> dict:
127
+ r"""
128
+ Returns the configuration for your adapter model as a dictionary.
129
+ """
130
+ return asdict(self)
131
+
132
+ def save_pretrained(self, save_directory: str, **kwargs) -> None:
133
+ r"""
134
+ This method saves the configuration of your adapter model in a directory.
135
+
136
+ Args:
137
+ save_directory (`str`):
138
+ The directory where the configuration will be saved.
139
+ kwargs (additional keyword arguments, *optional*):
140
+ Additional keyword arguments passed along to the [`~transformers.utils.PushToHubMixin.push_to_hub`]
141
+ method.
142
+ """
143
+ if os.path.isfile(save_directory):
144
+ raise AssertionError(f"Provided path ({save_directory}) should be a directory, not a file")
145
+
146
+ os.makedirs(save_directory, exist_ok=True)
147
+ auto_mapping_dict = kwargs.pop("auto_mapping_dict", None)
148
+
149
+ output_dict = self.to_dict()
150
+ # converting set type to list
151
+ for key, value in output_dict.items():
152
+ if isinstance(value, set):
153
+ output_dict[key] = list(value)
154
+
155
+ output_path = os.path.join(save_directory, CONFIG_NAME)
156
+
157
+ # Add auto mapping details for custom models.
158
+ if auto_mapping_dict is not None:
159
+ output_dict["auto_mapping"] = auto_mapping_dict
160
+
161
+ # save it
162
+ with open(output_path, "w") as writer:
163
+ writer.write(json.dumps(output_dict, indent=2, sort_keys=True))
164
+
165
+ @classmethod
166
+ def from_peft_type(cls, **kwargs):
167
+ r"""
168
+ This method loads the configuration of your adapter model from a set of kwargs.
169
+
170
+ The appropriate configuration type is determined by the `peft_type` argument. If `peft_type` is not provided,
171
+ the calling class type is instantiated.
172
+
173
+ Args:
174
+ kwargs (configuration keyword arguments):
175
+ Keyword arguments passed along to the configuration initialization.
176
+ """
177
+ # Avoid circular dependency .. TODO: fix this with a larger refactor
178
+ from peft.mapping import PEFT_TYPE_TO_CONFIG_MAPPING
179
+
180
+ # TODO: this hack is needed to fix the following issue (on commit 702f937):
181
+ # if someone saves a default config and loads it back with `PeftConfig` class it yields to
182
+ # not loading the correct config class.
183
+ #
184
+ # from peft import AdaLoraConfig, PeftConfig
185
+ # peft_config = AdaLoraConfig()
186
+ # print(peft_config)
187
+ # >>> AdaLoraConfig(peft_type=<PeftType.ADALORA: 'ADALORA'>, auto_mapping=None, base_model_name_or_path=None,
188
+ # revision=None, task_type=None, inference_mode=False, r=8, target_modules=None, lora_alpha=8, lora_dropout=0.0, ...
189
+ #
190
+ # peft_config.save_pretrained("./test_config")
191
+ # peft_config = PeftConfig.from_pretrained("./test_config")
192
+ # print(peft_config)
193
+ # >>> PeftConfig(peft_type='ADALORA', auto_mapping=None, base_model_name_or_path=None, revision=None, task_type=None, inference_mode=False)
194
+
195
+ if "peft_type" in kwargs:
196
+ peft_type = kwargs["peft_type"]
197
+ config_cls = PEFT_TYPE_TO_CONFIG_MAPPING[peft_type]
198
+ else:
199
+ config_cls = cls
200
+
201
+ try:
202
+ config = config_cls(**kwargs)
203
+ except TypeError as exc:
204
+ # Here we potentially handle forward compatibility. Sometimes new keywords are added to configs, which makes
205
+ # new configs incompatible with older PEFT versions. We catch these and remove them to allow the program to
206
+ # continue, but warn the user about it.
207
+
208
+ # First check if the error is due to unexpected keyword arguments, we don't want to accidentally catch
209
+ # other TypeErrors.
210
+ if "got an unexpected keyword argument" not in str(exc):
211
+ raise
212
+
213
+ filtered_kwargs, unexpected_kwargs = _check_and_remove_unused_kwargs(config_cls, kwargs)
214
+ if not MIN_EXPECTED_CONFIG_KEYS.issubset(set(filtered_kwargs.keys())):
215
+ raise TypeError(
216
+ f"The {cls.__name__} config that is trying to be loaded is missing required keys: "
217
+ f"{MIN_EXPECTED_CONFIG_KEYS}."
218
+ )
219
+
220
+ warnings.warn(
221
+ f"Unexpected keyword arguments {sorted(unexpected_kwargs)} for class {config_cls.__name__}, these are "
222
+ "ignored. This probably means that you're loading a configuration file that was saved using a "
223
+ "higher version of the library and additional parameters have been introduced since. It is "
224
+ "highly recommended to upgrade the PEFT version before continuing (e.g. by running `pip install "
225
+ "-U peft`)."
226
+ )
227
+ config = config_cls.from_peft_type(**filtered_kwargs)
228
+ return config
229
+
230
+ @classmethod
231
+ def from_pretrained(cls, pretrained_model_name_or_path: str, subfolder: Optional[str] = None, **kwargs):
232
+ r"""
233
+ This method loads the configuration of your adapter model from a directory.
234
+
235
+ Args:
236
+ pretrained_model_name_or_path (`str`):
237
+ The directory or the Hub repository id where the configuration is saved.
238
+ kwargs (additional keyword arguments, *optional*):
239
+ Additional keyword arguments passed along to the child class initialization.
240
+ """
241
+ path = (
242
+ os.path.join(pretrained_model_name_or_path, subfolder)
243
+ if subfolder is not None
244
+ else pretrained_model_name_or_path
245
+ )
246
+
247
+ hf_hub_download_kwargs, class_kwargs, _ = cls._split_kwargs(kwargs)
248
+ if "user_agent" not in hf_hub_download_kwargs:
249
+ hf_hub_download_kwargs["user_agent"] = http_user_agent()
250
+
251
+ if os.path.isfile(os.path.join(path, CONFIG_NAME)):
252
+ config_file = os.path.join(path, CONFIG_NAME)
253
+ else:
254
+ try:
255
+ config_file = hf_hub_download(
256
+ pretrained_model_name_or_path, CONFIG_NAME, subfolder=subfolder, **hf_hub_download_kwargs
257
+ )
258
+ except Exception as exc:
259
+ raise ValueError(f"Can't find '{CONFIG_NAME}' at '{pretrained_model_name_or_path}'") from exc
260
+
261
+ loaded_attributes = cls.from_json_file(config_file)
262
+ kwargs = {**class_kwargs, **loaded_attributes}
263
+ kwargs = cls.check_kwargs(**kwargs)
264
+ return cls.from_peft_type(**kwargs)
265
+
266
+ @classmethod
267
+ def from_json_file(cls, path_json_file: str, **kwargs):
268
+ r"""
269
+ Loads a configuration file from a json file.
270
+
271
+ Args:
272
+ path_json_file (`str`):
273
+ The path to the json file.
274
+ """
275
+ with open(path_json_file) as file:
276
+ json_object = json.load(file)
277
+
278
+ # Sanity check that config does not contain a runtime_config
279
+ if "runtime_config" in json_object:
280
+ warnings.warn(
281
+ "The configuration file contains a `runtime_config` key. This is ignored. Runtime configurations are only valid at runtime."
282
+ )
283
+ del json_object["runtime_config"]
284
+
285
+ return json_object
286
+
287
+ @classmethod
288
+ def _split_kwargs(cls, kwargs):
289
+ hf_hub_download_kwargs = {}
290
+ class_kwargs = {}
291
+ other_kwargs = {}
292
+
293
+ for key, value in kwargs.items():
294
+ if key in inspect.signature(hf_hub_download).parameters:
295
+ hf_hub_download_kwargs[key] = value
296
+ elif key in list(cls.__annotations__):
297
+ class_kwargs[key] = value
298
+ else:
299
+ other_kwargs[key] = value
300
+
301
+ return hf_hub_download_kwargs, class_kwargs, other_kwargs
302
+
303
+ @classmethod
304
+ def _get_peft_type(
305
+ cls,
306
+ model_id: str,
307
+ **hf_hub_download_kwargs,
308
+ ):
309
+ subfolder = hf_hub_download_kwargs.get("subfolder", None)
310
+
311
+ path = os.path.join(model_id, subfolder) if subfolder is not None else model_id
312
+
313
+ if os.path.isfile(os.path.join(path, CONFIG_NAME)):
314
+ config_file = os.path.join(path, CONFIG_NAME)
315
+ else:
316
+ try:
317
+ config_file = hf_hub_download(
318
+ model_id,
319
+ CONFIG_NAME,
320
+ **hf_hub_download_kwargs,
321
+ )
322
+ except Exception:
323
+ raise ValueError(f"Can't find '{CONFIG_NAME}' at '{model_id}'")
324
+
325
+ loaded_attributes = cls.from_json_file(config_file)
326
+ return loaded_attributes["peft_type"]
327
+
328
+ @classmethod
329
+ def check_kwargs(cls, **kwargs):
330
+ """Check kwargs before initializing the config instance.
331
+
332
+ Subclasses can override this method to add specific checks.
333
+
334
+ """
335
+ return kwargs
336
+
337
+ @property
338
+ def is_prompt_learning(self) -> bool:
339
+ r"""
340
+ Utility method to check if the configuration is for prompt learning.
341
+ """
342
+ return False
343
+
344
+ @property
345
+ def is_adaption_prompt(self) -> bool:
346
+ """Return True if this is an adaption prompt config."""
347
+ return False
348
+
349
+
350
+ @dataclass
351
+ class PeftConfig(PeftConfigMixin):
352
+ """
353
+ This is the base configuration class to store the configuration of a [`PeftModel`].
354
+
355
+ Args:
356
+ peft_type (Union[[`~peft.utils.config.PeftType`], `str`]): The type of Peft method to use.
357
+ task_type (Union[[`~peft.utils.config.TaskType`], `str`]): The type of task to perform.
358
+ inference_mode (`bool`, defaults to `False`): Whether to use the Peft model in inference mode.
359
+ """
360
+
361
+ base_model_name_or_path: Optional[str] = field(
362
+ default=None, metadata={"help": "The name of the base model to use."}
363
+ )
364
+ revision: Optional[str] = field(default=None, metadata={"help": "The specific base model version to use."})
365
+ peft_type: Optional[Union[str, PeftType]] = field(default=None, metadata={"help": "Peft type"})
366
+ task_type: Optional[Union[str, TaskType]] = field(default=None, metadata={"help": "Task type"})
367
+ inference_mode: bool = field(default=False, metadata={"help": "Whether to use inference mode"})
368
+
369
+
370
+ @dataclass
371
+ class PromptLearningConfig(PeftConfig):
372
+ """
373
+ This is the base configuration class to store the configuration of [`PrefixTuning`], [`PromptEncoder`], or
374
+ [`PromptTuning`].
375
+
376
+ Args:
377
+ num_virtual_tokens (`int`): The number of virtual tokens to use.
378
+ token_dim (`int`): The hidden embedding dimension of the base transformer model.
379
+ num_transformer_submodules (`int`): The number of transformer submodules in the base transformer model.
380
+ num_attention_heads (`int`): The number of attention heads in the base transformer model.
381
+ num_layers (`int`): The number of layers in the base transformer model.
382
+ """
383
+
384
+ num_virtual_tokens: int = field(default=None, metadata={"help": "Number of virtual tokens"})
385
+ token_dim: int = field(
386
+ default=None, metadata={"help": "The hidden embedding dimension of the base transformer model"}
387
+ )
388
+ num_transformer_submodules: Optional[int] = field(
389
+ default=None, metadata={"help": "Number of transformer submodules"}
390
+ )
391
+ num_attention_heads: Optional[int] = field(default=None, metadata={"help": "Number of attention heads"})
392
+ num_layers: Optional[int] = field(default=None, metadata={"help": "Number of transformer layers"})
393
+ modules_to_save: Optional[list[str]] = field(
394
+ default=None,
395
+ metadata={
396
+ "help": "List of extra modules to be set as trainable and saved in the final checkpoint. "
397
+ "For example, in Sequence Classification or Token Classification tasks, "
398
+ "the final layer `classifier/score` are randomly initialized and as such need to be trainable and saved. "
399
+ "The module(s) will be fully fine-tuned."
400
+ },
401
+ )
402
+
403
+ @property
404
+ def is_prompt_learning(self) -> bool:
405
+ r"""
406
+ Utility method to check if the configuration is for prompt learning.
407
+ """
408
+ return True
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/functional.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """
15
+ Functions that are useful for integration with non-PeftModel models, e.g. transformers or diffusers.
16
+
17
+ The functions provided here can be considered "public API" of PEFT and hence are safe to be used by packages that
18
+ provide PEFT integrations.
19
+ """
20
+
21
+ from peft.mapping import inject_adapter_in_model
22
+ from peft.tuners.tuners_utils import cast_adapter_dtype, delete_adapter, set_adapter, set_requires_grad
23
+ from peft.utils import get_peft_model_state_dict, set_peft_model_state_dict
24
+
25
+
26
+ __all__ = [
27
+ "cast_adapter_dtype",
28
+ "delete_adapter",
29
+ "get_peft_model_state_dict",
30
+ "inject_adapter_in_model",
31
+ "set_adapter",
32
+ "set_peft_model_state_dict",
33
+ "set_requires_grad",
34
+ ]
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/helpers.py ADDED
@@ -0,0 +1,577 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from contextlib import contextmanager
17
+ from copy import deepcopy
18
+ from functools import update_wrapper
19
+ from types import MethodType
20
+ from typing import Optional
21
+
22
+ import torch
23
+ from torch import nn
24
+
25
+
26
+ try:
27
+ import bitsandbytes as bnb
28
+ except ImportError:
29
+ bnb = None
30
+
31
+ from tqdm.auto import tqdm
32
+
33
+ from .peft_model import PeftConfig, PeftModel
34
+ from .tuners.lora import LoraLayer, LoraModel, dora
35
+ from .tuners.tuners_utils import BaseTunerLayer
36
+
37
+
38
+ def update_forward_signature(model: PeftModel) -> None:
39
+ """
40
+ Updates the forward signature of the PeftModel to include parents class signature
41
+ model (`PeftModel`): Peft model to update the forward signature
42
+
43
+ Example:
44
+
45
+ ```python
46
+ >>> from transformers import WhisperForConditionalGeneration
47
+ >>> from peft import get_peft_model, LoraConfig
48
+ >>> from peft.helpers import update_forward_signature
49
+
50
+ >>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en")
51
+ >>> peft_config = LoraConfig(r=8, lora_alpha=32, lora_dropout=0.1, target_modules=["q_proj", "v_proj"])
52
+
53
+ >>> peft_model = get_peft_model(model, peft_config)
54
+ >>> update_forward_signature(peft_model)
55
+ ```
56
+ """
57
+
58
+ # Only update signature when the current forward signature only has *args and **kwargs
59
+ current_signature = inspect.signature(model.forward)
60
+ if (
61
+ len(current_signature.parameters) == 2
62
+ and "args" in current_signature.parameters
63
+ and "kwargs" in current_signature.parameters
64
+ ):
65
+ forward = deepcopy(model.forward.__func__)
66
+ update_wrapper(
67
+ forward, type(model.get_base_model()).forward, assigned=("__doc__", "__name__", "__annotations__")
68
+ )
69
+ model.forward = MethodType(forward, model)
70
+
71
+
72
+ def update_generate_signature(model: PeftModel) -> None:
73
+ """
74
+ Updates the generate signature of a PeftModel with overriding generate to include parents class signature
75
+ model (`PeftModel`): Peft model to update the generate signature
76
+
77
+ Example:
78
+
79
+ ```python
80
+ >>> from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
81
+ >>> from peft import get_peft_model, LoraConfig, TaskType
82
+ >>> from peft.helpers import update_generate_signature
83
+
84
+ >>> model_name_or_path = "bigscience/mt0-large"
85
+ >>> tokenizer = AutoTokenizer.from_pretrained(model_name_or_path)
86
+ >>> model = AutoModelForSeq2SeqLM.from_pretrained(model_name_or_path)
87
+
88
+ >>> peft_config = LoraConfig(
89
+ ... task_type=TaskType.SEQ_2_SEQ_LM, inference_mode=False, r=8, lora_alpha=32, lora_dropout=0.1
90
+ ... )
91
+ >>> peft_model = get_peft_model(model, peft_config)
92
+ >>> update_generate_signature(peft_model)
93
+ >>> help(peft_model.generate)
94
+ ```
95
+ """
96
+ if not hasattr(model, "generate"):
97
+ return
98
+ current_signature = inspect.signature(model.generate)
99
+ if (
100
+ len(current_signature.parameters) == 2
101
+ and "args" in current_signature.parameters
102
+ and "kwargs" in current_signature.parameters
103
+ ) or (len(current_signature.parameters) == 1 and "kwargs" in current_signature.parameters):
104
+ generate = deepcopy(model.generate.__func__)
105
+ update_wrapper(
106
+ generate,
107
+ type(model.get_base_model()).generate,
108
+ assigned=("__doc__", "__name__", "__annotations__"),
109
+ )
110
+ model.generate = MethodType(generate, model)
111
+
112
+
113
+ def update_signature(model: PeftModel, method: str = "all") -> None:
114
+ """
115
+ Updates the signature of a PeftModel include parents class signature for forward or generate method
116
+ model (`PeftModel`): Peft model to update generate or forward signature method (`str`): method to update
117
+ signature choose one of "forward", "generate", "all"
118
+
119
+ Example:
120
+ ```python
121
+ >>> from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
122
+ >>> from peft import get_peft_model, LoraConfig, TaskType
123
+ >>> from peft.helpers import update_signature
124
+
125
+ >>> model_name_or_path = "bigscience/mt0-large"
126
+ >>> tokenizer = AutoTokenizer.from_pretrained(model_name_or_path)
127
+ >>> model = AutoModelForSeq2SeqLM.from_pretrained(model_name_or_path)
128
+
129
+ >>> peft_config = LoraConfig(
130
+ ... task_type=TaskType.SEQ_2_SEQ_LM, inference_mode=False, r=8, lora_alpha=32, lora_dropout=0.1
131
+ ... )
132
+ >>> peft_model = get_peft_model(model, peft_config)
133
+ >>> update_signature(peft_model)
134
+ >>> help(peft_model.generate)
135
+ ```
136
+ """
137
+ if method == "forward":
138
+ update_forward_signature(model)
139
+ elif method == "generate":
140
+ update_generate_signature(model)
141
+ elif method == "all":
142
+ update_forward_signature(model)
143
+ update_generate_signature(model)
144
+ else:
145
+ raise ValueError(f"method {method} is not supported please choose one of ['forward', 'generate', 'all']")
146
+
147
+
148
+ def check_if_peft_model(model_name_or_path: str) -> bool:
149
+ """
150
+ Check if the model is a PEFT model.
151
+
152
+ Args:
153
+ model_name_or_path (`str`):
154
+ Model id to check, can be local or on the Hugging Face Hub.
155
+
156
+ Returns:
157
+ `bool`: True if the model is a PEFT model, False otherwise.
158
+ """
159
+ is_peft_model = True
160
+ try:
161
+ PeftConfig.from_pretrained(model_name_or_path)
162
+ except Exception:
163
+ # allow broad exceptions so that this works even if new exceptions are added on HF Hub side
164
+ is_peft_model = False
165
+
166
+ return is_peft_model
167
+
168
+
169
+ @contextmanager
170
+ def rescale_adapter_scale(model, multiplier):
171
+ """
172
+ Context manager to temporarily rescale the scaling of the LoRA adapter in a model.
173
+
174
+ The original scaling values are restored when the context manager exits. This context manager works with the
175
+ transformers and diffusers models that have directly loaded LoRA adapters.
176
+
177
+ For LoRA, applying this context manager with multiplier in [0, 1] is strictly equivalent to applying
178
+ [wise-ft](https://huggingface.co/papers/2109.01903) (see [#1940](https://github.com/huggingface/peft/issues/1940)
179
+ for details). It can improve the performances of the model if there is a distribution shiftbetween the training
180
+ data used for fine-tuning, and the test data used during inference.
181
+
182
+ Warning: It has been reported that when using Apple's MPS backend for PyTorch, it is necessary to add a short sleep
183
+ time after exiting the context before the scales are fully restored.
184
+
185
+ Args:
186
+ model: The model containing `LoraLayer` modules whose scaling is to be adjusted.
187
+ multiplier (float or int):
188
+ The multiplier that rescales the `scaling` attribute. Must be of type float or int.
189
+
190
+ Raises:
191
+ ValueError: If the model does not contain any `LoraLayer`
192
+ instances, indicating that the model does not support scaling.
193
+
194
+ Example:
195
+
196
+ ```python
197
+ >>> model = ModelWithLoraLayer()
198
+ >>> multiplier = 0.5
199
+ >>> with rescale_adapter_scale(model, multiplier):
200
+ ... outputs = model(**inputs) # Perform operations with the scaled model
201
+ >>> outputs = model(**inputs) # The original scaling values are restored here
202
+ ```
203
+ """
204
+ # check if multiplier has a valid data type
205
+ if not isinstance(multiplier, (float, int)):
206
+ raise TypeError(f"Argument multiplier should be of type float, got {type(multiplier)}")
207
+
208
+ # iterate on the model's modules and grab the original scaling attribute
209
+ # from the lora layers if present
210
+ original_scaling = {}
211
+ for module in model.modules():
212
+ if isinstance(module, LoraLayer):
213
+ original_scaling[module] = module.scaling.copy()
214
+ module.scaling = {k: v * multiplier for k, v in module.scaling.items()}
215
+
216
+ # check whether scaling is prohibited on model
217
+ # the original scaling dictionary should be empty
218
+ # if there were no lora layers
219
+ if not original_scaling:
220
+ raise ValueError("scaling is only supported for models with `LoraLayer`s")
221
+ try:
222
+ yield
223
+
224
+ finally:
225
+ # restore original scaling values after exiting the context
226
+ for module, scaling in original_scaling.items():
227
+ module.scaling = scaling
228
+
229
+
230
+ @contextmanager
231
+ def disable_input_dtype_casting(model: nn.Module, active: bool = True):
232
+ """
233
+ Context manager disables input dtype casting to the dtype of the weight.
234
+
235
+ Parameters:
236
+ model (nn.Module):
237
+ The model containing PEFT modules whose input dtype casting is to be adjusted.
238
+ active (bool):
239
+ Whether the context manager is active (default) or inactive.
240
+
241
+ """
242
+ # Additional info: Normally, the dtype of the weight and input need to match, which is why the dtype is cast.
243
+ # However, in certain circumustances, this is handled by forward hooks, e.g. when using layerwise casting in
244
+ # diffusers. In that case, PEFT casting the dtype interferes with the layerwise casting, which is why the option to
245
+ # disable it is given.
246
+ if not active:
247
+ yield
248
+ return
249
+
250
+ original_values = {}
251
+ for name, module in model.named_modules():
252
+ if not isinstance(module, BaseTunerLayer):
253
+ continue
254
+ original_values[name] = module.cast_input_dtype_enabled
255
+ module.cast_input_dtype_enabled = False
256
+
257
+ try:
258
+ yield
259
+ finally:
260
+ for name, module in model.named_modules():
261
+ if not isinstance(module, BaseTunerLayer):
262
+ continue
263
+ if name in original_values:
264
+ module.cast_input_dtype_enabled = original_values[name]
265
+
266
+
267
+ class MontecloraTrainerMixin:
268
+ """
269
+ Mixin class for adding Monteclora variational loss to the Trainer's compute_loss method.
270
+
271
+ This mixin can be used with any Trainer class (e.g., Trainer, SFTTrainer) to add support for Monteclora's
272
+ variational regularization during training.
273
+
274
+ Example:
275
+ ```python
276
+ from transformers import Trainer
277
+ from peft import get_peft_model, LoraConfig
278
+ from peft.helpers import MontecloraTrainerMixin
279
+
280
+
281
+ # custom trainer that supports Monteclora
282
+ class MontecloraTrainer(MontecloraTrainerMixin, Trainer):
283
+ pass
284
+
285
+
286
+ # Configure LoRA with Monteclora
287
+ monteclora_config = MontecloraConfig(
288
+ num_samples=8,
289
+ sample_scaler=1e-4,
290
+ kl_loss_weight=1e-5,
291
+ )
292
+ lora_config = LoraConfig(
293
+ r=16,
294
+ lora_alpha=32,
295
+ target_modules=["q_proj", "v_proj"],
296
+ monteclora_config=monteclora_config,
297
+ )
298
+
299
+ # Get PEFT model and train
300
+ model = get_peft_model(base_model, lora_config)
301
+ trainer = MontecloraTrainer(model=model, args=training_args, ...)
302
+ trainer.train()
303
+ ```
304
+ """
305
+
306
+ def compute_loss(self, model, inputs, return_outputs=False, **kwargs):
307
+ """
308
+ Compute loss with Monteclora variational regularization.
309
+
310
+ This method extends the standard compute_loss by adding the variational loss (KL divergence + entropy) from
311
+ Monteclora samplers to the task loss.
312
+
313
+ Args:
314
+ model: The model being trained
315
+ inputs: Input batch
316
+ return_outputs: Whether to return model outputs along with loss
317
+ **kwargs: Additional arguments
318
+
319
+ Returns:
320
+ loss or (loss, outputs) depending on return_outputs
321
+ """
322
+ if return_outputs:
323
+ task_loss, outputs = super().compute_loss(model, inputs, return_outputs=True, **kwargs)
324
+ else:
325
+ task_loss = super().compute_loss(model, inputs, return_outputs=False, **kwargs)
326
+ outputs = None
327
+
328
+ # `_get_monteclora_loss` already normalizes by the number of samplers within a single LoraModel.
329
+ # In the typical case there is exactly one LoraModel (PeftModel.base_model) so this loop runs once
330
+ # and matches the original behavior. For unusual setups with multiple tuners we additionally average
331
+ # across the LoraModels so the regularization magnitude does not scale with the number of tuners.
332
+ # `_get_monteclora_loss` returns 0.0 when no MonteCLoRA samplers are present, so this is a no-op
333
+ # for plain LoRA training.
334
+ monteclora_loss = 0.0
335
+ num_lora_models = 0
336
+ for module in model.modules():
337
+ if isinstance(module, LoraModel):
338
+ monteclora_loss = monteclora_loss + module._get_monteclora_loss()
339
+ num_lora_models += 1
340
+ if num_lora_models > 1:
341
+ monteclora_loss = monteclora_loss / num_lora_models
342
+
343
+ total_loss = task_loss + monteclora_loss
344
+
345
+ return (total_loss, outputs) if return_outputs else total_loss
346
+
347
+
348
+ class DoraCaching:
349
+ """Context manager to enable DoRA caching, which improves speed of DoRA inference at the expense of memory.
350
+
351
+ With active caching, the materialized LoRA weight (B @ A) and the weight norm (base weight + LoRA weight) are
352
+ cached.
353
+
354
+ Even within the caching context, if the model is in training mode, caching is disabled. When the model switches to
355
+ training mode, the cache will be cleared.
356
+
357
+ Example:
358
+
359
+ ```py
360
+ >>> from peft.helpers import DoraCaching
361
+
362
+ >>> model.eval() # put in eval model for caching to work
363
+
364
+ >>> with DoraCaching(): # use as a context manager
365
+ ... output = model(inputs)
366
+
367
+ >>> dora_caching = DoraCaching()
368
+ >>> dora_caching(enabled=True) # permanently enable caching
369
+ >>> output = model(inputs)
370
+ >>> dora_caching(enabled=False) # permanently disable caching
371
+ >>> output = model(inputs)
372
+ ```
373
+
374
+ """
375
+
376
+ def __init__(self, enabled: bool = True) -> None:
377
+ self.enabled = enabled
378
+ self.prev_value = None
379
+
380
+ def __enter__(self):
381
+ self.prev_value = dora.ENABLE_DORA_CACHING
382
+ dora.ENABLE_DORA_CACHING = self.enabled
383
+
384
+ def __exit__(self, type, value, traceback):
385
+ dora.ENABLE_DORA_CACHING = self.prev_value
386
+ self.prev_value = None
387
+
388
+ def __call__(self, enabled: bool = True):
389
+ dora.ENABLE_DORA_CACHING = enabled
390
+
391
+
392
+ class KappaTuneSelector:
393
+ """
394
+ Lightweight utility to compute per-module / per-parameter condition numbers and return the best LoRA targets.
395
+
396
+ Supports:
397
+ - Classic nn.Linear modules (target_modules in LoraConfig)
398
+ - Modern fused MoE weights stored as 3D nn.Parameter (gate_up_proj / down_proj, gate_proj / up_proj, etc.) used in
399
+ Llama-4, Qwen2_MoE, Qwen3_MoE, Mixtral, OLMoE and similar models. These are returned via target_parameters.
400
+
401
+ Notes:
402
+ - Condition-number computation requires running SVD and can take several minutes on very large models. A progress
403
+ bar can be shown/disabled via `show_progress`.
404
+
405
+ """
406
+
407
+ def __init__(
408
+ self,
409
+ model: nn.Module,
410
+ max_dim_size_to_analyze: int = 16384,
411
+ moe_param_suffixes: Optional[tuple[str, ...]] = None,
412
+ show_progress: bool = True,
413
+ ):
414
+ self.model = model
415
+ self.max_dim_size_to_analyze = max_dim_size_to_analyze
416
+ self.show_progress = show_progress
417
+ self.moe_param_suffixes = moe_param_suffixes or (
418
+ ".gate_up_proj",
419
+ ".down_proj",
420
+ ".gate_proj",
421
+ ".up_proj",
422
+ )
423
+ self._condition_numbers: Optional[dict[str, float]] = None
424
+ self._parameter_condition_numbers: Optional[dict[str, float]] = None
425
+
426
+ def _compute_kappas(self) -> None:
427
+ if self._condition_numbers is not None:
428
+ return
429
+
430
+ # === 1. nn.Linear modules ===
431
+ condition_numbers: dict[str, float] = {}
432
+ linear_modules = [
433
+ (module_name, module)
434
+ for module_name, module in self.model.named_modules()
435
+ if isinstance(module, nn.Linear)
436
+ ]
437
+ linear_iter = (
438
+ tqdm(linear_modules, desc="Computing SVD (linear layers)", unit="layer")
439
+ if self.show_progress
440
+ else linear_modules
441
+ )
442
+ for module_name, module in linear_iter:
443
+ weight = module.weight
444
+ if bnb is not None:
445
+ if hasattr(weight, "quant_state"): # 4-bit
446
+ w = bnb.functional.dequantize_4bit(weight.data, weight.quant_state).float()
447
+ elif hasattr(weight, "state") and hasattr(weight.state, "CB"): # int8
448
+ w = bnb.functional.int8_vectorwise_dequant(weight.state.CB, weight.state.SCB).float()
449
+ else:
450
+ w = weight.data.detach().float()
451
+ else:
452
+ w = weight.data.detach().float()
453
+
454
+ if any(dim > self.max_dim_size_to_analyze for dim in w.shape):
455
+ continue
456
+
457
+ S = torch.linalg.svdvals(w.view(w.size(0), -1))
458
+ kappa = (S[0] / (S[-1] + 1e-8)).item()
459
+ condition_numbers[module_name] = kappa
460
+
461
+ self._condition_numbers = condition_numbers
462
+
463
+ # === 2. fused MoE parameters (3D nn.Parameter) ===
464
+ parameter_condition_numbers: dict[str, float] = {}
465
+ moe_params = [
466
+ (param_name, param)
467
+ for param_name, param in self.model.named_parameters()
468
+ if any(param_name.endswith(s) for s in self.moe_param_suffixes) and param.dim() == 3
469
+ ]
470
+ moe_iter = (
471
+ tqdm(moe_params, desc="Computing SVD (MoE parameters)", unit="param") if self.show_progress else moe_params
472
+ )
473
+ for param_name, param in moe_iter:
474
+ w = param.data.detach().float()
475
+ num_experts, *expert_shape = w.shape
476
+
477
+ if any(dim > self.max_dim_size_to_analyze for dim in expert_shape):
478
+ continue
479
+
480
+ kappas = []
481
+ for expert_idx in range(num_experts):
482
+ expert_w = w[expert_idx]
483
+ S = torch.linalg.svdvals(expert_w)
484
+ kappa = (S[0] / (S[-1] + 1e-8)).item()
485
+ kappas.append(kappa)
486
+ kappa = sum(kappas) / len(kappas)
487
+ parameter_condition_numbers[param_name] = kappa
488
+
489
+ self._parameter_condition_numbers = parameter_condition_numbers
490
+
491
+ def get_best_targets(
492
+ self, top_p: Optional[float] = None, num_modules: Optional[int] = None, threshold: Optional[float] = None
493
+ ) -> list[str]:
494
+ self._compute_kappas()
495
+ if not self._condition_numbers:
496
+ return []
497
+
498
+ sorted_modules = sorted(self._condition_numbers.items(), key=lambda x: x[1])
499
+
500
+ if num_modules is not None:
501
+ k = min(num_modules, len(sorted_modules))
502
+ return [name for name, _ in sorted_modules[:k]]
503
+
504
+ if top_p is not None:
505
+ k = max(1, int(len(sorted_modules) * top_p))
506
+ return [name for name, _ in sorted_modules[:k]]
507
+
508
+ if threshold is not None:
509
+ return [name for name, kappa in sorted_modules if kappa <= threshold]
510
+
511
+ return [name for name, _ in sorted_modules]
512
+
513
+ def get_best_target_parameters(
514
+ self, top_p: Optional[float] = None, num_modules: Optional[int] = None, threshold: Optional[float] = None
515
+ ) -> list[str]:
516
+ self._compute_kappas()
517
+ if not self._parameter_condition_numbers:
518
+ return []
519
+
520
+ sorted_params = sorted(self._parameter_condition_numbers.items(), key=lambda x: x[1])
521
+
522
+ if num_modules is not None:
523
+ k = min(num_modules, len(sorted_params))
524
+ return [name for name, _ in sorted_params[:k]]
525
+
526
+ if top_p is not None:
527
+ k = max(1, int(len(sorted_params) * top_p))
528
+ return [name for name, _ in sorted_params[:k]]
529
+
530
+ if threshold is not None:
531
+ return [name for name, kappa in sorted_params if kappa <= threshold]
532
+
533
+ return [name for name, _ in sorted_params]
534
+
535
+
536
+ def find_kappa_target_modules(
537
+ model: nn.Module,
538
+ top_p: float = 0.2,
539
+ max_dim_size_to_analyze: int = 16384,
540
+ moe_param_suffixes: Optional[tuple[str, ...]] = None,
541
+ show_progress: bool = True,
542
+ ) -> dict[str, Optional[list[str]]]:
543
+ """
544
+ One-liner convenience function for KappaTune target selection. Returns both target_modules and target_parameters.
545
+
546
+ Args:
547
+ model (nn.Module):
548
+ Base model whose weights will be analyzed for condition numbers.
549
+ top_p (float, optional):
550
+ Select the top fraction of candidate modules/parameters with the lowest condition numbers.
551
+ max_dim_size_to_analyze (int, optional):
552
+ Upper bound on the maximum matrix dimension analyzed via SVD. Defaults to 16384.
553
+ moe_param_suffixes (Optional[tuple[str, ...]], optional):
554
+ Parameter-name suffixes used to identify fused MoE tensors that should be returned via `target_parameters`.
555
+ If None, sensible defaults are used.
556
+ show_progress (bool, optional):
557
+ Whether to display a progress bar while computing condition numbers (SVD-based) across candidate
558
+ tensors/modules. Disable in CI or other non-interactive environments. Defaults to True.
559
+ """
560
+ selector = KappaTuneSelector(
561
+ model,
562
+ max_dim_size_to_analyze=max_dim_size_to_analyze,
563
+ moe_param_suffixes=moe_param_suffixes,
564
+ show_progress=show_progress,
565
+ )
566
+
567
+ target_modules = selector.get_best_targets(top_p=top_p)
568
+ target_parameters = selector.get_best_target_parameters(top_p=top_p)
569
+
570
+ # Return None when there are no MoE layers (PEFT convention)
571
+ if not target_parameters:
572
+ target_parameters = None
573
+
574
+ return {
575
+ "target_modules": target_modules,
576
+ "target_parameters": target_parameters,
577
+ }
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/import_utils.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import importlib
15
+ import importlib.metadata as importlib_metadata
16
+ import platform
17
+ from functools import lru_cache
18
+
19
+ import packaging.version
20
+ import torch
21
+ import transformers
22
+
23
+
24
+ is_transformers_ge_v5 = packaging.version.parse(transformers.__version__) >= packaging.version.parse("5.0.0.dev0")
25
+
26
+ is_transformers_ge_v5_1_0 = packaging.version.parse(transformers.__version__) >= packaging.version.parse("5.1.0")
27
+
28
+ is_transformers_ge_v5_4_0 = packaging.version.parse(transformers.__version__) >= packaging.version.parse("5.4.0")
29
+
30
+ is_transformers_ge_v5_6_0 = packaging.version.parse(transformers.__version__) >= packaging.version.parse("5.6.0.dev0")
31
+
32
+ is_transformers_le_4_53 = packaging.version.parse(transformers.__version__) < packaging.version.parse("4.54.0.dev0")
33
+
34
+
35
+ @lru_cache
36
+ def is_bnb_available() -> bool:
37
+ return importlib.util.find_spec("bitsandbytes") is not None
38
+
39
+
40
+ @lru_cache
41
+ def is_bnb_4bit_available() -> bool:
42
+ if not is_bnb_available():
43
+ return False
44
+
45
+ import bitsandbytes as bnb
46
+
47
+ return hasattr(bnb.nn, "Linear4bit")
48
+
49
+
50
+ @lru_cache
51
+ def is_gptqmodel_available() -> bool:
52
+ if importlib.util.find_spec("gptqmodel") is not None:
53
+ GPTQMODEL_MINIMUM_VERSION = packaging.version.parse("7.0.0")
54
+ OPTIMUM_MINIMUM_VERSION = packaging.version.parse("1.24.0")
55
+ version_gptqmodel = packaging.version.parse(importlib_metadata.version("gptqmodel"))
56
+ if GPTQMODEL_MINIMUM_VERSION <= version_gptqmodel:
57
+ if is_optimum_available():
58
+ try:
59
+ version_optimum = packaging.version.parse(importlib_metadata.version("optimum"))
60
+ except importlib_metadata.PackageNotFoundError:
61
+ # Same idea as in diffusers:
62
+ # https://github.com/huggingface/diffusers/blob/9f06a0d1a4a998ac6a463c5be728c892f95320a8/src/diffusers/utils/import_utils.py#L351-L357
63
+ # It's not clear under what circumstances `importlib_metadata.version("optimum")` can raise an error
64
+ # even though `importlib.util.find_spec("optimum") is not None` but it has been observed, so adding
65
+ # this for precaution. If we cannot detect it, we just optimistically assume it's high enough.
66
+ return True
67
+
68
+ if OPTIMUM_MINIMUM_VERSION <= version_optimum:
69
+ return True
70
+ else:
71
+ raise ImportError(
72
+ f"gptqmodel requires optimum version `{OPTIMUM_MINIMUM_VERSION}` or higher. Found version `{version_optimum}`, "
73
+ f"but only versions above `{OPTIMUM_MINIMUM_VERSION}` are supported"
74
+ )
75
+ else:
76
+ raise ImportError(
77
+ f"gptqmodel requires optimum version `{OPTIMUM_MINIMUM_VERSION}` or higher to be installed."
78
+ )
79
+ else:
80
+ raise ImportError(
81
+ f"Found an incompatible version of gptqmodel. Found version `{version_gptqmodel}`, "
82
+ f"but only versions `{GPTQMODEL_MINIMUM_VERSION}` or higher are supported"
83
+ )
84
+
85
+
86
+ @lru_cache
87
+ def is_optimum_available() -> bool:
88
+ return importlib.util.find_spec("optimum") is not None
89
+
90
+
91
+ @lru_cache
92
+ def is_torch_tpu_available(check_device=True) -> bool:
93
+ "Checks if `torch_xla` is installed and potentially if a TPU is in the environment"
94
+ if importlib.util.find_spec("torch_xla") is not None:
95
+ if check_device:
96
+ # We need to check if `xla_device` can be found, will raise a RuntimeError if not
97
+ try:
98
+ import torch_xla.core.xla_model as xm
99
+
100
+ _ = xm.xla_device()
101
+ return True
102
+ except RuntimeError:
103
+ return False
104
+ return True
105
+ return False
106
+
107
+
108
+ @lru_cache
109
+ def is_aqlm_available() -> bool:
110
+ return importlib.util.find_spec("aqlm") is not None
111
+
112
+
113
+ @lru_cache
114
+ def is_eetq_available() -> bool:
115
+ return importlib.util.find_spec("eetq") is not None
116
+
117
+
118
+ @lru_cache
119
+ def is_hqq_available() -> bool:
120
+ return importlib.util.find_spec("hqq") is not None
121
+
122
+
123
+ @lru_cache
124
+ def is_inc_available() -> bool:
125
+ return importlib.util.find_spec("neural_compressor") is not None
126
+
127
+
128
+ @lru_cache
129
+ def is_torchao_available() -> bool:
130
+ if importlib.util.find_spec("torchao") is None:
131
+ return False
132
+
133
+ TORCHAO_MINIMUM_VERSION = packaging.version.parse("0.16.0")
134
+ try:
135
+ torchao_version = packaging.version.parse(importlib_metadata.version("torchao"))
136
+ except importlib_metadata.PackageNotFoundError:
137
+ # Same idea as in diffusers:
138
+ # https://github.com/huggingface/diffusers/blob/9f06a0d1a4a998ac6a463c5be728c892f95320a8/src/diffusers/utils/import_utils.py#L351-L357
139
+ # It's not clear under what circumstances `importlib_metadata.version("torchao")` can raise an error even
140
+ # though `importlib.util.find_spec("torchao") is not None` but it has been observed, so adding this for
141
+ # precaution.
142
+ return False
143
+
144
+ if torchao_version < TORCHAO_MINIMUM_VERSION:
145
+ raise ImportError(
146
+ f"Found an incompatible version of torchao. Found version {torchao_version}, "
147
+ f"but only versions above {TORCHAO_MINIMUM_VERSION} are supported"
148
+ )
149
+ return True
150
+
151
+
152
+ @lru_cache
153
+ def is_xpu_available(check_device=False) -> bool:
154
+ """
155
+ Checks if XPU acceleration is available and potentially if a XPU is in the environment
156
+ """
157
+
158
+ system = platform.system()
159
+ if system == "Darwin":
160
+ return False
161
+ else:
162
+ if check_device:
163
+ try:
164
+ # Will raise a RuntimeError if no XPU is found
165
+ _ = torch.xpu.device_count()
166
+ return torch.xpu.is_available()
167
+ except RuntimeError:
168
+ return False
169
+ return hasattr(torch, "xpu") and torch.xpu.is_available()
170
+
171
+
172
+ @lru_cache
173
+ def is_diffusers_available() -> bool:
174
+ return importlib.util.find_spec("diffusers") is not None
175
+
176
+
177
+ @lru_cache
178
+ def is_te_available() -> bool:
179
+ return importlib.util.find_spec("transformer_engine") is not None
180
+
181
+
182
+ @lru_cache
183
+ def is_te_pytorch_available() -> bool:
184
+ if not is_te_available():
185
+ return False
186
+
187
+ import transformer_engine
188
+
189
+ return hasattr(transformer_engine, "pytorch")
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/mapping.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ from typing import TYPE_CHECKING, Any, Optional
18
+
19
+ import torch
20
+
21
+ from .utils import PeftType
22
+
23
+
24
+ if TYPE_CHECKING:
25
+ from .config import PeftConfig
26
+ from .tuners.tuners_utils import BaseTuner
27
+
28
+
29
+ # these will be filled by the register_peft_method function
30
+ PEFT_TYPE_TO_CONFIG_MAPPING: dict[PeftType, type[PeftConfig]] = {}
31
+ PEFT_TYPE_TO_TUNER_MAPPING: dict[PeftType, type[BaseTuner]] = {}
32
+ PEFT_TYPE_TO_MIXED_MODEL_MAPPING: dict[PeftType, type[BaseTuner]] = {}
33
+ PEFT_TYPE_TO_PREFIX_MAPPING: dict[PeftType, str] = {}
34
+
35
+
36
+ def get_peft_config(config_dict: dict[str, Any]) -> PeftConfig:
37
+ """
38
+ Returns a Peft config object from a dictionary.
39
+
40
+ Args:
41
+ config_dict (`Dict[str, Any]`): Dictionary containing the configuration parameters.
42
+ """
43
+
44
+ return PEFT_TYPE_TO_CONFIG_MAPPING[config_dict["peft_type"]](**config_dict)
45
+
46
+
47
+ def inject_adapter_in_model(
48
+ peft_config: PeftConfig,
49
+ model: torch.nn.Module,
50
+ adapter_name: str = "default",
51
+ low_cpu_mem_usage: bool = False,
52
+ state_dict: Optional[dict[str, torch.Tensor]] = None,
53
+ ) -> torch.nn.Module:
54
+ r"""
55
+ Create PEFT layers and inject them into the model in-place.
56
+
57
+ Currently the API does not support prompt learning methods and adaption prompt.
58
+
59
+ This function is similar to [`get_peft_model`] but it does not return a [`PeftModel`] instance. Instead, it returns
60
+ the original, mutated instance of the passed model.
61
+
62
+ Args:
63
+ peft_config (`PeftConfig`):
64
+ Configuration object containing the parameters of the PEFT model.
65
+ model (`torch.nn.Module`):
66
+ The input model where the adapter will be injected.
67
+ adapter_name (`str`, `optional`, defaults to `"default"`):
68
+ The name of the adapter to be injected, if not provided, the default adapter name is used ("default").
69
+ low_cpu_mem_usage (`bool`, `optional`, defaults to `False`):
70
+ Create empty adapter weights on meta device. Useful to speed up the loading process.
71
+ state_dict (`dict`, *optional*, defaults to `None`)
72
+ If a `state_dict` is passed here, the adapters will be injected based on the entries of the state_dict.
73
+ This can be useful when the exact `target_modules` of the PEFT method is unknown, for instance because the
74
+ checkpoint was created without meta data. Note that the values from the `state_dict` are not used, only the
75
+ keys are used to determine the correct layers that should be adapted.
76
+ """
77
+ if peft_config.is_prompt_learning or peft_config.is_adaption_prompt:
78
+ raise ValueError("`create_and_replace` does not support prompt learning and adaption prompt yet.")
79
+
80
+ if peft_config.peft_type not in PEFT_TYPE_TO_TUNER_MAPPING.keys():
81
+ raise ValueError(
82
+ f"`inject_adapter_in_model` does not support {peft_config.peft_type} yet. Please use `get_peft_model`."
83
+ )
84
+
85
+ tuner_cls = PEFT_TYPE_TO_TUNER_MAPPING[peft_config.peft_type]
86
+
87
+ # By instantiating a peft model we are injecting randomly initialized LoRA layers into the model's modules.
88
+ peft_model = tuner_cls(
89
+ model, peft_config, adapter_name=adapter_name, low_cpu_mem_usage=low_cpu_mem_usage, state_dict=state_dict
90
+ )
91
+
92
+ return peft_model.model
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/mapping_func.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ import warnings
18
+ from typing import Optional
19
+
20
+ from transformers import PreTrainedModel
21
+
22
+ from .auto import MODEL_TYPE_TO_PEFT_MODEL_MAPPING
23
+ from .config import PeftConfig
24
+ from .mapping import PEFT_TYPE_TO_CONFIG_MAPPING, PEFT_TYPE_TO_PREFIX_MAPPING
25
+ from .mixed_model import PeftMixedModel
26
+ from .peft_model import PeftModel
27
+ from .tuners.tuners_utils import BaseTuner, BaseTunerLayer
28
+
29
+
30
+ def get_peft_model(
31
+ model: PreTrainedModel,
32
+ peft_config: PeftConfig,
33
+ adapter_name: str = "default",
34
+ mixed: bool = False,
35
+ autocast_adapter_dtype: bool = True,
36
+ revision: Optional[str] = None,
37
+ low_cpu_mem_usage: bool = False,
38
+ ) -> PeftModel | PeftMixedModel:
39
+ """
40
+ Returns a Peft model object from a model and a config, where the model will be modified in-place.
41
+
42
+ Args:
43
+ model ([`transformers.PreTrainedModel`]):
44
+ Model to be wrapped.
45
+ peft_config ([`PeftConfig`]):
46
+ Configuration object containing the parameters of the Peft model.
47
+ adapter_name (`str`, `optional`, defaults to `"default"`):
48
+ The name of the adapter to be injected, if not provided, the default adapter name is used ("default").
49
+ mixed (`bool`, `optional`, defaults to `False`):
50
+ Whether to allow mixing different (compatible) adapter types.
51
+ autocast_adapter_dtype (`bool`, *optional*):
52
+ Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter weights
53
+ using float16 or bfloat16 to float32, as this is typically required for stable training, and only affect
54
+ select PEFT tuners.
55
+ revision (`str`, `optional`, defaults to `main`):
56
+ The revision of the base model. If this isn't set, the saved peft model will load the `main` revision for
57
+ the base model
58
+ low_cpu_mem_usage (`bool`, `optional`, defaults to `False`):
59
+ Create empty adapter weights on meta device. Useful to speed up the loading process. Leave this setting as
60
+ False if you intend on training the model, unless the adapter weights will be replaced by different weights
61
+ before training starts.
62
+ """
63
+ model_config = BaseTuner.get_model_config(model)
64
+ old_name = peft_config.base_model_name_or_path
65
+ new_name = model.__dict__.get("name_or_path", None)
66
+ peft_config.base_model_name_or_path = new_name
67
+
68
+ # Especially in notebook environments there could be a case that a user wants to experiment with different
69
+ # configuration values. However, it is likely that there won't be any changes for new configs on an already
70
+ # initialized PEFT model. The best we can do is warn the user about it.
71
+ if any(isinstance(module, BaseTunerLayer) for module in model.modules()):
72
+ warnings.warn(
73
+ "You are trying to modify a model with PEFT for a second time. If you want to reload the model with a "
74
+ "different config, make sure to call `.unload()` before."
75
+ )
76
+
77
+ if (old_name is not None) and (old_name != new_name):
78
+ warnings.warn(
79
+ f"The PEFT config's `base_model_name_or_path` was renamed from '{old_name}' to '{new_name}'. "
80
+ "Please ensure that the correct base model is loaded when loading this checkpoint."
81
+ )
82
+
83
+ if revision is not None:
84
+ if peft_config.revision is not None and peft_config.revision != revision:
85
+ warnings.warn(
86
+ f"peft config has already set base model revision to {peft_config.revision}, overwriting with revision {revision}"
87
+ )
88
+ peft_config.revision = revision
89
+
90
+ if (
91
+ (isinstance(peft_config, PEFT_TYPE_TO_CONFIG_MAPPING["LORA"]))
92
+ and (peft_config.init_lora_weights == "eva")
93
+ and not low_cpu_mem_usage
94
+ ):
95
+ warnings.warn(
96
+ "lora with eva initialization used with low_cpu_mem_usage=False. "
97
+ "Setting low_cpu_mem_usage=True can improve the maximum batch size possible for eva initialization."
98
+ )
99
+
100
+ prefix = PEFT_TYPE_TO_PREFIX_MAPPING.get(peft_config.peft_type)
101
+ if prefix and adapter_name in prefix:
102
+ warnings.warn(
103
+ f"Adapter name '{adapter_name}' should not be contained in the prefix '{prefix}'. "
104
+ "This may lead to reinitialization of the adapter weights during loading."
105
+ )
106
+
107
+ if mixed:
108
+ # note: PeftMixedModel does not support autocast_adapter_dtype, so don't pass it
109
+ return PeftMixedModel(model, peft_config, adapter_name=adapter_name)
110
+
111
+ # We explicitly exclude prompt learning here since prompt learning is specific to the task and needs special
112
+ # handling in the PEFT model's forward method.
113
+ if peft_config.task_type not in MODEL_TYPE_TO_PEFT_MODEL_MAPPING.keys() and not peft_config.is_prompt_learning:
114
+ return PeftModel(
115
+ model,
116
+ peft_config,
117
+ adapter_name=adapter_name,
118
+ autocast_adapter_dtype=autocast_adapter_dtype,
119
+ low_cpu_mem_usage=low_cpu_mem_usage,
120
+ )
121
+
122
+ return MODEL_TYPE_TO_PEFT_MODEL_MAPPING[peft_config.task_type](
123
+ model,
124
+ peft_config,
125
+ adapter_name=adapter_name,
126
+ autocast_adapter_dtype=autocast_adapter_dtype,
127
+ low_cpu_mem_usage=low_cpu_mem_usage,
128
+ )
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/mixed_model.py ADDED
@@ -0,0 +1,473 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ import os
18
+ from contextlib import contextmanager
19
+ from typing import Any, Optional, Union
20
+
21
+ import torch
22
+ from accelerate.hooks import remove_hook_from_submodules
23
+ from torch import nn
24
+ from transformers.utils import PushToHubMixin
25
+
26
+ from peft.utils.constants import DUMMY_MODEL_CONFIG
27
+
28
+ from .config import PeftConfig
29
+ from .peft_model import PeftModel
30
+ from .tuners import MixedModel
31
+ from .utils import _set_adapter, _set_trainable
32
+
33
+
34
+ def _prepare_model_for_gradient_checkpointing(model: nn.Module) -> None:
35
+ r"""
36
+ Prepares the model for gradient checkpointing if necessary
37
+ """
38
+ # Note: same as PeftModel._prepare_model_for_gradient_checkpointing
39
+ if not getattr(model, "is_gradient_checkpointing", True):
40
+ return model
41
+
42
+ if not (
43
+ getattr(model, "is_loaded_in_8bit", False)
44
+ or getattr(model, "is_loaded_in_4bit", False)
45
+ or getattr(model, "is_quantized", False)
46
+ ):
47
+ if hasattr(model, "enable_input_require_grads"):
48
+ model.enable_input_require_grads()
49
+ elif hasattr(model, "get_input_embeddings"):
50
+
51
+ def make_inputs_require_grad(module, input, output):
52
+ output.requires_grad_(True)
53
+
54
+ model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
55
+
56
+
57
+ def _check_config_compatible(peft_config: PeftConfig) -> None:
58
+ from .tuners.mixed import COMPATIBLE_TUNER_TYPES
59
+
60
+ if peft_config.peft_type not in COMPATIBLE_TUNER_TYPES:
61
+ raise ValueError(
62
+ f"The provided `peft_type` '{peft_config.peft_type.value}' is not compatible with the `PeftMixedModel`. "
63
+ f"Compatible types are: {COMPATIBLE_TUNER_TYPES}"
64
+ )
65
+
66
+
67
+ class PeftMixedModel(PushToHubMixin, torch.nn.Module):
68
+ """
69
+ PeftMixedModel for loading mixing different types of adapters for inference.
70
+
71
+ This class does not support loading/saving, and it shouldn't usually be initialized directly. Instead, use
72
+ `get_peft_model` with the argument `mixed=True`.
73
+
74
+ > [!TIP] > Read the [Mixed adapter types](https://huggingface.co/docs/peft/en/developer_guides/mixed_models) guide
75
+ to learn > more about using different adapter types.
76
+
77
+ Example:
78
+
79
+ ```py
80
+ >>> base_model = ... # load the base model, e.g. from transformers
81
+ >>> peft_model = PeftMixedModel.from_pretrained(base_model, path_to_adapter1, "adapter1").eval()
82
+ >>> peft_model.load_adapter(path_to_adapter2, "adapter2")
83
+ >>> peft_model.set_adapter(["adapter1", "adapter2"]) # activate both adapters
84
+ >>> peft_model(data) # forward pass using both adapters
85
+ ```
86
+
87
+ Args:
88
+ model (`torch.nn.Module`):
89
+ The model to be tuned.
90
+ config (`PeftConfig`):
91
+ The config of the model to be tuned. The adapter type must be compatible.
92
+ adapter_name (`str`, `optional`, defaults to `"default"`):
93
+ The name of the first adapter.
94
+ low_cpu_mem_usage (`bool`, `optional`, defaults to `False`):
95
+ Create empty adapter weights on meta device. Useful to speed up the loading process.
96
+ """
97
+
98
+ def __init__(self, model: nn.Module, peft_config: PeftConfig, adapter_name: str = "default") -> None:
99
+ super().__init__()
100
+ _check_config_compatible(peft_config)
101
+ _prepare_model_for_gradient_checkpointing(model)
102
+ self.modules_to_save = None
103
+ self.base_model = MixedModel(model, {adapter_name: peft_config}, adapter_name)
104
+ self.set_modules_to_save(peft_config, adapter_name)
105
+
106
+ self.config = getattr(model, "config", DUMMY_MODEL_CONFIG)
107
+
108
+ # the `pretraining_tp` is set for some models to simulate Tensor Parallelism during inference to avoid
109
+ # numerical differences, https://github.com/pytorch/pytorch/issues/76232 - to avoid any unexpected
110
+ # behavior we disable that in this line.
111
+ if hasattr(self.base_model, "config") and hasattr(self.base_model.config, "pretraining_tp"):
112
+ self.base_model.config.pretraining_tp = 1
113
+
114
+ @property
115
+ def peft_config(self) -> dict[str, PeftConfig]:
116
+ return self.base_model.peft_config
117
+
118
+ @property
119
+ def active_adapter(self) -> str:
120
+ return self.base_model.active_adapter
121
+
122
+ @property
123
+ def active_adapters(self) -> list[str]:
124
+ return self.base_model.active_adapters
125
+
126
+ def get_nb_trainable_parameters(self):
127
+ r"""
128
+ Returns the number of trainable parameters and number of all parameters in the model.
129
+ """
130
+ # note: same as PeftModel.get_nb_trainable_parameters
131
+ trainable_params = 0
132
+ all_param = 0
133
+ for _, param in self.named_parameters():
134
+ num_params = param.numel()
135
+ # if using DS Zero 3 and the weights are initialized empty
136
+ if num_params == 0 and hasattr(param, "ds_numel"):
137
+ num_params = param.ds_numel
138
+
139
+ # Due to the design of 4bit linear layers from bitsandbytes
140
+ # one needs to multiply the number of parameters by 2 to get
141
+ # the correct number of parameters
142
+ if param.__class__.__name__ == "Params4bit":
143
+ num_params = num_params * 2
144
+
145
+ all_param += num_params
146
+ if param.requires_grad:
147
+ trainable_params += num_params
148
+
149
+ return trainable_params, all_param
150
+
151
+ def print_trainable_parameters(self):
152
+ """
153
+ Prints the number of trainable parameters in the model.
154
+
155
+ Note: print_trainable_parameters() uses get_nb_trainable_parameters() which is different from
156
+ num_parameters(only_trainable=True) from huggingface/transformers. get_nb_trainable_parameters() returns
157
+ (trainable parameters, all parameters) of the Peft Model which includes modified backbone transformer model.
158
+ For techniques like LoRA, the backbone transformer model is modified in place with LoRA modules. However, for
159
+ prompt tuning, the backbone transformer model is unmodified. num_parameters(only_trainable=True) returns number
160
+ of trainable parameters of the backbone transformer model which can be different.
161
+ """
162
+ # note: same as PeftModel.print_trainable_parameters
163
+ trainable_params, all_param = self.get_nb_trainable_parameters()
164
+
165
+ print(
166
+ f"trainable params: {trainable_params:,d} || "
167
+ f"all params: {all_param:,d} || "
168
+ f"trainable%: {100 * trainable_params / all_param:.4f}"
169
+ )
170
+
171
+ def __getattr__(self, name: str):
172
+ """Forward missing attributes to the wrapped module."""
173
+ try:
174
+ return super().__getattr__(name) # defer to nn.Module's logic
175
+ except AttributeError:
176
+ if name == "base_model": # see #1892: prevent infinite recursion if class is not initialized
177
+ raise
178
+ return getattr(self.base_model, name)
179
+
180
+ def forward(self, *args: Any, **kwargs: Any):
181
+ """
182
+ Forward pass of the model.
183
+ """
184
+ return self.base_model(*args, **kwargs)
185
+
186
+ def generate(self, *args: Any, **kwargs: Any):
187
+ """
188
+ Generate output.
189
+ """
190
+ return self.base_model.generate(*args, **kwargs)
191
+
192
+ @contextmanager
193
+ def disable_adapter(self):
194
+ """
195
+ Disables the adapter module.
196
+ """
197
+ try:
198
+ self.base_model.disable_adapter_layers()
199
+ yield
200
+ finally:
201
+ self.base_model.enable_adapter_layers()
202
+
203
+ def add_adapter(
204
+ self,
205
+ adapter_name: str,
206
+ peft_config: PeftConfig,
207
+ low_cpu_mem_usage: bool = False,
208
+ autocast_adapter_dtype: bool = True,
209
+ ) -> None:
210
+ """
211
+ Add an adapter to the model based on the passed configuration.
212
+
213
+ This adapter is not trained. To load a trained adapter, check out [`PeftModel.load_adapter`].
214
+
215
+ The name for the new adapter should be unique.
216
+
217
+ The new adapter is not automatically set as the active adapter. Use [`PeftModel.set_adapter`] to set the active
218
+ adapter.
219
+
220
+ Args:
221
+ adapter_name (`str`):
222
+ The name of the adapter to be added.
223
+ peft_config ([`PeftConfig`]):
224
+ The configuration of the adapter to be added.
225
+ low_cpu_mem_usage (`bool`, `optional`, defaults to `False`):
226
+ Create empty adapter weights on meta device. Useful to speed up the process when loading saved
227
+ adapters.
228
+
229
+ > [!TIP] > Don't use `low_cpu_mem_usage=True` when creating a new PEFT adapter for training (training
230
+ is untested > and discouraged for PeftMixedModel in general).
231
+ autocast_adapter_dtype (`bool`, *optional*, defaults to `True`):
232
+ Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter
233
+ weights using float16 and bfloat16 to float32, as this is typically required for stable training, and
234
+ only affect select PEFT tuners. If set to `False`, the dtypes will stay the same as those of the
235
+ corresponding layer.
236
+ """
237
+ _check_config_compatible(peft_config)
238
+
239
+ try:
240
+ self.peft_config[adapter_name] = peft_config
241
+ self.base_model.inject_adapter(self, adapter_name, low_cpu_mem_usage=low_cpu_mem_usage)
242
+ except Exception: # something went wrong, roll back
243
+ if adapter_name in self.peft_config:
244
+ del self.peft_config[adapter_name]
245
+ raise
246
+
247
+ self.base_model._cast_adapter_dtype(adapter_name=adapter_name, autocast_adapter_dtype=autocast_adapter_dtype)
248
+
249
+ self.set_modules_to_save(peft_config, adapter_name)
250
+
251
+ def set_modules_to_save(self, peft_config: PeftConfig, adapter_name: str) -> None:
252
+ if (modules_to_save := getattr(peft_config, "modules_to_save", None)) is None:
253
+ return
254
+
255
+ if self.modules_to_save is None:
256
+ self.modules_to_save = set(modules_to_save)
257
+ else:
258
+ self.modules_to_save.update(modules_to_save)
259
+ _set_trainable(
260
+ self,
261
+ adapter_name,
262
+ module_names=getattr(peft_config, "modules_to_save", None),
263
+ inference_mode=peft_config.inference_mode,
264
+ )
265
+
266
+ def set_adapter(self, adapter_name: Union[str, list[str]], inference_mode: bool = False) -> None:
267
+ """
268
+ Sets the active adapter(s) for the model.
269
+
270
+ Note that the order in which the adapters are applied during the forward pass may not be the same as the order
271
+ in which they are passed to this function. Instead, the order during the forward pass is determined by the
272
+ order in which the adapters were loaded into the model. The active adapters only determine which adapters are
273
+ active during the forward pass, but not the order in which they are applied.
274
+
275
+ Additionally, this function will set the specified adapter to trainable (i.e., requires_grad=True) unless
276
+ inference_mode is True.
277
+
278
+ Args:
279
+ adapter_name (str, list[str]):
280
+ The name(s) of the adapter(s) to set as active
281
+ inference_mode (bool, optional):
282
+ Whether the activated adapter should be frozen (i.e. `requires_grad=False`). Default is False.
283
+ """
284
+ if isinstance(adapter_name, str):
285
+ adapter_name = [adapter_name]
286
+
287
+ mismatched = set(adapter_name) - set(self.peft_config.keys())
288
+ if mismatched:
289
+ raise ValueError(
290
+ f"Adapter(s) {sorted(mismatched)} not found, available adapters: {sorted(self.peft_config.keys())}"
291
+ )
292
+
293
+ self.base_model.set_adapter(adapter_name, inference_mode=inference_mode)
294
+ _set_adapter(self, adapter_name, inference_mode=inference_mode)
295
+
296
+ def delete_adapter(self, adapter_name: Union[str, list[str]]) -> None:
297
+ if isinstance(adapter_name, str):
298
+ adapter_name = [adapter_name]
299
+
300
+ mismatched = set(adapter_name) - set(self.peft_config.keys())
301
+ if mismatched:
302
+ raise ValueError(
303
+ f"Adapter(s) {sorted(mismatched)} not found, available adapters: {sorted(self.peft_config.keys())}"
304
+ )
305
+
306
+ self.base_model.delete_adapter(adapter_name)
307
+
308
+ def merge_and_unload(self, *args: Any, **kwargs: Any):
309
+ r"""
310
+ This method merges the adapter layers into the base model. This is needed if someone wants to use the base
311
+ model as a standalone model.
312
+
313
+ Args:
314
+ progressbar (`bool`):
315
+ whether to show a progressbar indicating the unload and merge process
316
+ safe_merge (`bool`):
317
+ whether to activate the safe merging check to check if there is any potential Nan in the adapter
318
+ weights
319
+ adapter_names (`List[str]`, *optional*):
320
+ The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults
321
+ to `None`.
322
+ """
323
+ return self.base_model.merge_and_unload(*args, **kwargs)
324
+
325
+ def unload(self, *args: Any, **kwargs: Any):
326
+ """
327
+ Gets back the base model by removing all the adapter modules without merging. This gives back the original base
328
+ model.
329
+ """
330
+ return self.base_model.unload(*args, **kwargs)
331
+
332
+ def get_layer_status(self):
333
+ raise TypeError(f"get_layer_status is not supported for {self.__class__.__name__}.")
334
+
335
+ def get_model_status(self):
336
+ raise TypeError(f"get_model_status is not supported for {self.__class__.__name__}.")
337
+
338
+ @classmethod
339
+ def _split_kwargs(cls, kwargs: dict[str, Any]):
340
+ return PeftModel._split_kwargs(kwargs)
341
+
342
+ def _check_new_adapter_config(self, peft_config: PeftConfig, is_trainable: bool) -> None:
343
+ return PeftModel._check_new_adapter_config(self, peft_config, is_trainable=is_trainable)
344
+
345
+ def load_adapter(self, model_id: str, adapter_name: str, *args: Any, **kwargs: Any):
346
+ """
347
+ Load a trained adapter into the model.
348
+
349
+ The name for the new adapter should be unique.
350
+
351
+ The new adapter is not automatically set as the active adapter. Use [`PeftModel.set_adapter`] to set the active
352
+ adapter.
353
+
354
+ Args:
355
+ adapter_name (`str`):
356
+ The name of the adapter to be added.
357
+ peft_config ([`PeftConfig`]):
358
+ The configuration of the adapter to be added.
359
+ is_trainable (`bool`, *optional*, defaults to `False`):
360
+ Whether the adapter should be trainable or not. If `False`, the adapter will be frozen and can only be
361
+ used for inference.
362
+ torch_device (`str`, *optional*, defaults to None):
363
+ The device to load the adapter on. If `None`, the device will be inferred.
364
+ autocast_adapter_dtype (`bool`, *optional*, defaults to `True`):
365
+ Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter
366
+ weights using float16 and bfloat16 to float32, as this is typically required for stable training, and
367
+ only affect select PEFT tuners.
368
+ ephemeral_gpu_offload (`bool`, *optional*, defaults to `False`):
369
+ Whether to use ephemeral GPU offloading for partially loaded modules. Defaults to `False`.
370
+ low_cpu_mem_usage (`bool`, `optional`, defaults to `False`):
371
+ Create empty adapter weights on meta device before loading the saved weights. Useful to speed up the
372
+ process.
373
+ kwargs: (`optional`):
374
+ Additional arguments to modify the way the adapter is loaded, e.g. the token for Hugging Face Hub.
375
+ """
376
+ # the low_cpu_mem_usage option is handled through kwargs
377
+ output = PeftModel.load_adapter(self, model_id, adapter_name, *args, **kwargs)
378
+ # TODO: not quite clear why this is necessary but tests fail without it
379
+ self.set_adapter(self.active_adapters)
380
+ return output
381
+
382
+ def create_or_update_model_card(self, output_dir: str):
383
+ raise NotImplementedError(f"Model card creation is not supported for {self.__class__.__name__} (yet).")
384
+
385
+ def save_pretrained(
386
+ self,
387
+ save_directory: str,
388
+ safe_serialization: bool = False,
389
+ selected_adapters: Optional[list[str]] = None,
390
+ **kwargs: Any,
391
+ ):
392
+ raise NotImplementedError(f"Saving is not supported for {self.__class__.__name__} (yet).")
393
+
394
+ @classmethod
395
+ def from_pretrained(
396
+ cls,
397
+ model: nn.Module,
398
+ model_id: str | os.PathLike,
399
+ adapter_name: str = "default",
400
+ is_trainable: bool = False,
401
+ config: Optional[PeftConfig] = None,
402
+ **kwargs: Any,
403
+ ):
404
+ r"""
405
+ Instantiate a PEFT mixed model from a pretrained model and loaded PEFT weights.
406
+
407
+ Note that the passed `model` may be modified inplace.
408
+
409
+ Args:
410
+ model (`nn.Module`):
411
+ The model to be adapted.
412
+ model_id (`str` or `os.PathLike`):
413
+ The name of the PEFT configuration to use. Can be either:
414
+ - A string, the `model id` of a PEFT configuration hosted inside a model repo on the Hugging Face
415
+ Hub.
416
+ - A path to a directory containing a PEFT configuration file saved using the `save_pretrained`
417
+ method (`./my_peft_config_directory/`).
418
+ adapter_name (`str`, *optional*, defaults to `"default"`):
419
+ The name of the adapter to be loaded. This is useful for loading multiple adapters.
420
+ is_trainable (`bool`, *optional*, defaults to `False`):
421
+ Whether the adapter should be trainable or not. If `False`, the adapter will be frozen and use for
422
+ inference
423
+ config ([`~peft.PeftConfig`], *optional*):
424
+ The configuration object to use instead of an automatically loaded configuration. This configuration
425
+ object is mutually exclusive with `model_id` and `kwargs`. This is useful when configuration is already
426
+ loaded before calling `from_pretrained`.
427
+ low_cpu_mem_usage (`bool`, `optional`, defaults to `False`):
428
+ Create empty adapter weights on meta device before loading the saved weights. Useful to speed up the
429
+ process.
430
+ kwargs: (`optional`):
431
+ Additional keyword arguments passed along to the specific PEFT configuration class.
432
+ """
433
+ # note: adapted from PeftModel.from_pretrained
434
+ from .mapping import PEFT_TYPE_TO_CONFIG_MAPPING, PEFT_TYPE_TO_MIXED_MODEL_MAPPING
435
+
436
+ # load the config
437
+ if config is None:
438
+ hf_kwargs = {
439
+ "subfolder": kwargs.get("subfolder", None),
440
+ "revision": kwargs.get("revision", None),
441
+ "cache_dir": kwargs.get("cache_dir", None),
442
+ "token": kwargs.get("token", None),
443
+ }
444
+ if use_auth_token := kwargs.get("use_auth_token", None):
445
+ hf_kwargs["use_auth_token"] = use_auth_token
446
+ config = PEFT_TYPE_TO_CONFIG_MAPPING[PeftConfig._get_peft_type(model_id, **hf_kwargs)].from_pretrained(
447
+ model_id, **kwargs
448
+ )
449
+ elif isinstance(config, PeftConfig):
450
+ config.inference_mode = not is_trainable
451
+ else:
452
+ raise ValueError(f"The input config must be a PeftConfig, got {config.__class__}")
453
+
454
+ # note: this is different from PeftModel.from_pretrained
455
+ if config.peft_type not in PEFT_TYPE_TO_MIXED_MODEL_MAPPING:
456
+ raise ValueError(f"Adapter of type {config.peft_type} is not supported for mixed models.")
457
+
458
+ if (getattr(model, "hf_device_map", None) is not None) and len(
459
+ set(model.hf_device_map.values()).intersection({"cpu", "disk"})
460
+ ) > 0:
461
+ remove_hook_from_submodules(model)
462
+
463
+ if config.is_prompt_learning and is_trainable:
464
+ # note: should not be possible to reach, but just in case
465
+ raise ValueError("Cannot set a prompt learning adapter to trainable when loading pretrained adapter.")
466
+ else:
467
+ config.inference_mode = not is_trainable
468
+
469
+ # note: this is different from PeftModel.from_pretrained, we always return a PeftMixedModel
470
+ model = cls(model, config, adapter_name)
471
+ # the low_cpu_mem_usage option is handled through kwargs
472
+ model.load_adapter(model_id, adapter_name, is_trainable=is_trainable, **kwargs)
473
+ return model
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/optimizers/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from .lorafa import create_lorafa_optimizer
16
+ from .loraplus import create_loraplus_optimizer
17
+
18
+
19
+ __all__ = ["create_lorafa_optimizer", "create_loraplus_optimizer"]
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/optimizers/lorafa.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ This module contains the implementation of the LoRA-FA optimizer.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import math
22
+ from collections.abc import Callable, Iterable
23
+
24
+ import torch
25
+ from accelerate.utils.imports import is_bf16_available
26
+ from torch import autocast, nn
27
+ from torch.optim import Optimizer
28
+
29
+ from ..peft_model import PeftModel
30
+ from ..utils.other import infer_device
31
+
32
+
33
+ class LoraFAOptimizer(Optimizer):
34
+ """
35
+ Implements the LoRA-FA optimizer designed specifically for training Low-Rank Adaptation (LoRA) parameters
36
+ efficiently. Note that LoraFAOptimizer is based on adamw-hf in transformers, with only LoRA part modified. Without
37
+ LoRA it will fall back to adamw-hf.
38
+
39
+ Args:
40
+ params (Iterable[nn.parameter.Parameter]): Parameters to optimize.
41
+ lr (float, optional): Learning rate (default: 1e-3).
42
+ betas (Tuple[float, float], optional):
43
+ Coefficients for computing running averages of gradient and squared gradient (default: (0.9, 0.999)).
44
+ eps (float, optional): Term added to denominator to improve numerical stability (default: 1e-6).
45
+ weight_decay (float, optional): Weight decay (L2 penalty) (default: 0.0).
46
+ correct_bias (bool, optional): Whether to apply bias correction as in original Adam (default: True).
47
+
48
+ Args in sub-function step:
49
+ closure (Callable, optional): A closure that reevaluates the model and returns the loss.
50
+
51
+ Reference:
52
+ - LoRA-FA: https://huggingface.co/papers/2308.03303
53
+ """
54
+
55
+ def __init__(
56
+ self,
57
+ params: Iterable[nn.parameter.Parameter],
58
+ lr: float = 1e-3,
59
+ betas: tuple[float, float] = (0.9, 0.999),
60
+ eps: float = 1e-6,
61
+ weight_decay: float = 0.0,
62
+ correct_bias: bool = True,
63
+ ):
64
+ if lr < 0.0:
65
+ raise ValueError(f"Invalid learning rate: {lr} - should be >= 0.0")
66
+ if not 0.0 <= betas[0] < 1.0:
67
+ raise ValueError(f"Invalid beta parameter: {betas[0]} - should be in [0.0, 1.0)")
68
+ if not 0.0 <= betas[1] < 1.0:
69
+ raise ValueError(f"Invalid beta parameter: {betas[1]} - should be in [0.0, 1.0)")
70
+ if not 0.0 <= eps:
71
+ raise ValueError(f"Invalid epsilon value: {eps} - should be >= 0.0")
72
+ defaults = {
73
+ "lr": lr,
74
+ "betas": betas,
75
+ "eps": eps,
76
+ "weight_decay": weight_decay,
77
+ "correct_bias": correct_bias,
78
+ }
79
+ super().__init__(params, defaults)
80
+
81
+ @torch.no_grad()
82
+ def step(self, closure: Callable | None = None):
83
+ """
84
+ Performs a single optimization step.
85
+
86
+ Arguments:
87
+ closure (`Callable`, *optional*): A closure that reevaluates the model and returns the loss.
88
+ """
89
+ loss = None
90
+ if closure is not None:
91
+ loss = closure()
92
+
93
+ for group in self.param_groups:
94
+ scaling_factor = group["scaling_factor"]
95
+ param_list = []
96
+ name_list = []
97
+ for p, n in zip(group["params"], group["names"]):
98
+ # Skip non-lora no-grad module, since we need lora_A which is no-grad.
99
+ if "lora" not in n and p.grad is None:
100
+ continue
101
+ grad = p.grad
102
+
103
+ if "lora" in n:
104
+ param_list.append(p)
105
+ name_list.append(n)
106
+ if len(param_list) == 2:
107
+ name = n[: n.find("lora")] + "lora"
108
+ elif len(param_list) == 1:
109
+ continue
110
+ else:
111
+ name = n
112
+ # param_list contains a pair of A and B adapters
113
+ # i.e., param_list -> [A,B]
114
+
115
+ state = self.state[name]
116
+ # State initialization
117
+ if len(state) == 0:
118
+ if len(param_list) == 2:
119
+ state["step"] = 0
120
+ # Exponential moving average of gradient values
121
+ state["exp_avg_B"] = torch.zeros_like(param_list[1])
122
+ # Exponential moving average of squared gradient values
123
+ state["exp_avg_sq_B"] = torch.zeros_like(param_list[1])
124
+ else:
125
+ state["step"] = 0
126
+ # Exponential moving average of gradient values
127
+ state["exp_avg"] = torch.zeros_like(p)
128
+ # Exponential moving average of squared gradient values
129
+ state["exp_avg_sq"] = torch.zeros_like(p)
130
+
131
+ # Below is the LoRA-FA part
132
+ # 1. In this part, we optimize the gradient of B as:
133
+ # g^B = \left(\frac{r}{\alpha}\right)^2 (A^\top A)^{-1} g_{\text{LoRA-FA}}^B
134
+ # to min the func as described below:
135
+ # \min_{g^B} \|\hat{g}_\text{LoRA-FA} - g\|_F^2
136
+ # 2. After the gradient of B is ready, update the optimizer state
137
+ if len(param_list) == 2:
138
+ A = param_list[0]
139
+ B = param_list[1]
140
+ grad_B_orin = B.grad
141
+
142
+ # projection
143
+ delta = 1e-8
144
+
145
+ # computing the inverse matrix
146
+ AA_T = A @ A.T
147
+ AA_T_inv = torch.linalg.pinv(AA_T + delta * torch.eye(A.shape[0]).to(A.device))
148
+
149
+ device_type = infer_device()
150
+
151
+ if is_bf16_available():
152
+ with autocast(device_type=device_type, dtype=torch.bfloat16):
153
+ grad_B = (1 / scaling_factor**2) * (grad_B_orin @ AA_T_inv)
154
+ else:
155
+ grad_B = (1 / scaling_factor**2) * (grad_B_orin @ AA_T_inv)
156
+
157
+ if grad_B.dtype != B.grad.dtype:
158
+ grad_B = grad_B.to(B.grad.dtype)
159
+
160
+ exp_avg_B, exp_avg_sq_B = state["exp_avg_B"], state["exp_avg_sq_B"]
161
+ beta1, beta2 = group["betas"]
162
+ state["step"] += 1
163
+ exp_avg_B.mul_(beta1).add_(grad_B, alpha=(1.0 - beta1))
164
+ exp_avg_sq_B.mul_(beta2).addcmul_(grad_B, grad_B, value=1.0 - beta2)
165
+
166
+ denom_B = exp_avg_sq_B.sqrt().add_(group["eps"])
167
+ step_size = group["lr"]
168
+ if group["correct_bias"]: # No bias correction for Bert
169
+ bias_correction1 = 1.0 - beta1 ** state["step"]
170
+ bias_correction2 = 1.0 - beta2 ** state["step"]
171
+ step_size = step_size * math.sqrt(bias_correction2) / bias_correction1
172
+ B.addcdiv_(exp_avg_B, denom_B, value=-step_size)
173
+ if group["weight_decay"] > 0.0:
174
+ B.add_(B, alpha=(-group["lr"] * group["weight_decay"]))
175
+ param_list = []
176
+ name_list = []
177
+
178
+ # Below is the original AdamW
179
+ else:
180
+ exp_avg, exp_avg_sq = state["exp_avg"], state["exp_avg_sq"]
181
+ beta1, beta2 = group["betas"]
182
+
183
+ state["step"] += 1
184
+
185
+ # Decay the first and second moment running average coefficient
186
+ # In-place operations to update the averages at the same time
187
+ exp_avg.mul_(beta1).add_(grad, alpha=(1.0 - beta1))
188
+ exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=1.0 - beta2)
189
+ denom = exp_avg_sq.sqrt().add_(group["eps"])
190
+
191
+ step_size = group["lr"]
192
+ if group["correct_bias"]: # No bias correction for Bert
193
+ bias_correction1 = 1.0 - beta1 ** state["step"]
194
+ bias_correction2 = 1.0 - beta2 ** state["step"]
195
+ step_size = step_size * math.sqrt(bias_correction2) / bias_correction1
196
+
197
+ p.addcdiv_(exp_avg, denom, value=-step_size)
198
+
199
+ # Just adding the square of the weights to the loss function is *not*
200
+ # the correct way of using L2 regularization/weight decay with Adam,
201
+ # since that will interact with the m and v parameters in strange ways.
202
+ #
203
+ # Instead we want to decay the weights in a manner that doesn't interact
204
+ # with the m/v parameters. This is equivalent to adding the square
205
+ # of the weights to the loss with plain (non-momentum) SGD.
206
+ # Add weight decay at the end (fixed version)
207
+ if group["weight_decay"] > 0.0:
208
+ p.add_(p, alpha=(-group["lr"] * group["weight_decay"]))
209
+
210
+ return loss
211
+
212
+
213
+ def create_lorafa_optimizer(
214
+ model: PeftModel, r: int, lora_alpha: int, lr: float, weight_decay: float = 0.0, use_rslora: bool = False
215
+ ) -> Optimizer:
216
+ """
217
+ Helper function to instantiate a lorafa optimizer specifically configured for a given model using the LoRA method.
218
+
219
+ This function will:
220
+ - Disable gradient updates for the "lora_A" parameters (these are typically frozen during LoRA training).
221
+ - Compute the scaling factor based on provided `lora_alpha` and rank `r` for proper gradient projection.
222
+ - Create and configure parameter groups for the optimizer including specified learning rate, weight decay, and
223
+ additional optimizer options.
224
+
225
+ For hyper-params, LoRA-FA uses the same hyper-params as AdamW, except for the LoRA hyper-params (r, lora_alpha,
226
+ use_rslora). One can always use the same hyper-params such as lr and weight_decay, as AdamW in LoRA tuning.
227
+
228
+ Args:
229
+ model (PeftModel): The model containing LoRA-adapted parameters.
230
+ r (int): Rank of the LoRA decomposition.
231
+ lora_alpha (int): Scaling factor for LoRA parameterization.
232
+ lr (float): Learning rate for optimizer updates.
233
+ weight_decay (float): Weight decay for AdamW.
234
+ use_rslora (bool):
235
+ whether to use rslora. In rslora, the lora scaling factor becomes to lora_alpha / math.sqrt(r) instead of
236
+ lora_alpha / r.
237
+
238
+ Returns:
239
+ Optimizer: Configured lorafa optimizer instance ready for training.
240
+ """
241
+ for name, param in model.named_parameters():
242
+ if "lora_A" in name:
243
+ param.requires_grad_(False)
244
+ lora_scaling = lora_alpha / math.sqrt(r) if use_rslora else lora_alpha / r
245
+ param_groups = [
246
+ {
247
+ "params": model.parameters(),
248
+ "lr": lr,
249
+ "names": [name for name, _ in model.named_parameters()],
250
+ "scaling_factor": lora_scaling,
251
+ "betas": (0.9, 0.999),
252
+ "weight_decay": weight_decay,
253
+ }
254
+ ]
255
+ return LoraFAOptimizer(param_groups)
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/optimizers/loraplus.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ This module contains the implementation of the LoraPlus optimizer.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from operator import attrgetter
22
+
23
+ from torch import nn
24
+ from torch.optim import Optimizer
25
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
26
+ from transformers.trainer_pt_utils import get_parameter_names
27
+
28
+ from ..peft_model import PeftModel
29
+ from ..tuners.lora.layer import Embedding
30
+
31
+
32
+ def create_loraplus_optimizer(
33
+ model: PeftModel, optimizer_cls: type[Optimizer], *, lr: float, loraplus_lr_ratio: float, **kwargs
34
+ ) -> Optimizer:
35
+ """
36
+ Creates a LoraPlus optimizer.
37
+
38
+ Efficient Low Rank Adaptation of Large Models: https://huggingface.co/papers/2402.12354
39
+
40
+ Reference: https://github.com/nikhil-ghosh-berkeley/loraplus/
41
+
42
+ Args:
43
+ model (`torch.nn.Module`): The model to be optimized.
44
+ optimizer_cls (`torch.optim.Optimizer`): The optimizer class to be used.
45
+ lr (`float`): The learning rate to be used for the optimizer.
46
+ loraplus_lr_ratio (`float`):
47
+ The ratio of learning ηB/ηA where ηA (lr) is passed in as the optimizer learning rate. Should be ≥1. Should
48
+ be set in tandem with the optimizer learning rate (lr); should be larger when the task is more difficult
49
+ and the model needs to update its features to learn well. In this case, it helps to make the learning rate
50
+ slightly smaller (e.g., by a factor of 2) than typical vanilla LoRA learning rates
51
+ loraplus_lr_embedding (optional `float`):
52
+ If LoRA modules are added to embedding layers your can specify a different learning rate for them. Default
53
+ value 1e-6.
54
+ kwargs (`dict`): Additional keyword arguments to be passed to the optimizer.
55
+
56
+ Returns:
57
+ `torch.optim.Optimizer`: An instance of the specified optimizer class configured with the model's parameters
58
+ organized into groups with custom learning rates.
59
+ """
60
+
61
+ decay_parameters = get_parameter_names(model, ALL_LAYERNORM_LAYERS)
62
+ decay_parameters = [name for name in decay_parameters if "bias" not in name]
63
+ param_groups = {
64
+ "groupA": {},
65
+ "groupB": {},
66
+ "groupB_no_decay": {},
67
+ "embedding": {},
68
+ }
69
+
70
+ for name, param in model.named_parameters():
71
+ if not param.requires_grad:
72
+ continue
73
+
74
+ module = attrgetter(name)(model)
75
+ if isinstance(module, Embedding):
76
+ param_groups["embedding"][name] = param
77
+ elif "lora_B" in name or param.ndim == 1:
78
+ if name in decay_parameters:
79
+ param_groups["groupB"][name] = param
80
+ else:
81
+ param_groups["groupB_no_decay"][name] = param
82
+ else:
83
+ param_groups["groupA"][name] = param
84
+
85
+ kwargs["lr"] = lr
86
+ loraplus_weight_decay = kwargs.pop("loraplus_weight_decay", 0.0)
87
+ loraplus_lr_embedding = kwargs.pop("loraplus_lr_embedding", 1e-6)
88
+
89
+ optimizer_grouped_parameters = [
90
+ {
91
+ "params": list(param_groups["groupA"].values()),
92
+ "weight_decay": loraplus_weight_decay,
93
+ "lr": lr,
94
+ },
95
+ {
96
+ "params": list(param_groups["embedding"].values()),
97
+ "weight_decay": loraplus_weight_decay,
98
+ "lr": loraplus_lr_embedding,
99
+ },
100
+ {
101
+ "params": list(param_groups["groupB"].values()),
102
+ "weight_decay": loraplus_weight_decay,
103
+ "lr": lr * loraplus_lr_ratio,
104
+ },
105
+ {
106
+ "params": list(param_groups["groupB_no_decay"].values()),
107
+ "weight_decay": 0.0,
108
+ "lr": lr * loraplus_lr_ratio,
109
+ },
110
+ ]
111
+
112
+ optimizer = optimizer_cls(optimizer_grouped_parameters, **kwargs)
113
+ eight_bit_names = ["Adam8bit", "AdamW8bit", "PagedAdam8bit", "PagedAdamW8bit"]
114
+ if optimizer_cls.__name__ in eight_bit_names:
115
+ import bitsandbytes
116
+
117
+ manager = bitsandbytes.optim.GlobalOptimManager.get_instance()
118
+ for module in model.modules():
119
+ if isinstance(module, nn.Embedding):
120
+ manager.register_module_override(module, "weight", {"optim_bits": 32})
121
+ return optimizer
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/peft_model.py ADDED
The diff for this file is too large to render. See raw diff
 
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/py.typed ADDED
File without changes
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/__init__.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from .adalora import AdaLoraConfig, AdaLoraModel
16
+ from .adamss import AdamssConfig, AdamssModel
17
+ from .adaption_prompt import AdaptionPromptConfig, AdaptionPromptModel
18
+ from .beft import BeftConfig, BeftModel
19
+ from .boft import BOFTConfig, BOFTModel
20
+ from .c3a import C3AConfig, C3AModel
21
+ from .cartridge import CartridgeConfig, CartridgeEncoder
22
+ from .cpt import CPTConfig, CPTEmbedding
23
+ from .delora import DeloraConfig, DeloraModel
24
+ from .fourierft import FourierFTConfig, FourierFTModel
25
+ from .gralora import GraloraConfig, GraloraModel
26
+ from .hira import HiraConfig, HiraModel
27
+ from .hra import HRAConfig, HRAModel
28
+ from .ia3 import IA3Config, IA3Model
29
+ from .lily import LilyConfig, LilyModel
30
+ from .ln_tuning import LNTuningConfig, LNTuningModel
31
+ from .loha import LoHaConfig, LoHaModel
32
+ from .lokr import LoKrConfig, LoKrModel
33
+ from .lora import (
34
+ ArrowConfig,
35
+ BdLoraConfig,
36
+ EvaConfig,
37
+ LoftQConfig,
38
+ LoraConfig,
39
+ LoraGAConfig,
40
+ LoraModel,
41
+ LoraRuntimeConfig,
42
+ MontecloraConfig,
43
+ VeloraConfig,
44
+ convert_to_lora,
45
+ create_arrow_model,
46
+ get_eva_state_dict,
47
+ initialize_lora_eva_weights,
48
+ preprocess_loraga,
49
+ save_as_lora,
50
+ )
51
+ from .miss import MissConfig, MissModel
52
+ from .mixed import MixedModel
53
+ from .multitask_prompt_tuning import MultitaskPromptEmbedding, MultitaskPromptTuningConfig, MultitaskPromptTuningInit
54
+ from .oft import OFTConfig, OFTModel
55
+ from .osf import OSFConfig, OSFModel
56
+ from .p_tuning import PromptEncoder, PromptEncoderConfig, PromptEncoderReparameterizationType
57
+ from .peanut import PeanutConfig, PeanutModel
58
+ from .poly import PolyConfig, PolyModel
59
+ from .prefix_tuning import PrefixEncoder, PrefixTuningConfig
60
+ from .prompt_tuning import PromptEmbedding, PromptTuningConfig, PromptTuningInit
61
+ from .psoft import PsoftConfig, PsoftModel
62
+ from .pvera import PveraConfig, PveraModel
63
+ from .randlora import RandLoraConfig, RandLoraModel
64
+ from .road import RoadConfig, RoadModel
65
+ from .shira import ShiraConfig, ShiraModel
66
+ from .tinylora import TinyLoraConfig, TinyLoraModel
67
+ from .trainable_tokens import TrainableTokensConfig, TrainableTokensModel
68
+ from .vblora import VBLoRAConfig, VBLoRAModel
69
+ from .vera import VeraConfig, VeraModel
70
+ from .waveft import WaveFTConfig, WaveFTModel
71
+ from .xlora import XLoraConfig, XLoraModel
72
+
73
+
74
+ __all__ = [
75
+ "AdaLoraConfig",
76
+ "AdaLoraModel",
77
+ "AdamssConfig",
78
+ "AdamssModel",
79
+ "AdaptionPromptConfig",
80
+ "AdaptionPromptModel",
81
+ "ArrowConfig",
82
+ "BOFTConfig",
83
+ "BOFTModel",
84
+ "BdLoraConfig",
85
+ "BeftConfig",
86
+ "BeftModel",
87
+ "C3AConfig",
88
+ "C3AModel",
89
+ "CPTConfig",
90
+ "CPTEmbedding",
91
+ "CartridgeConfig",
92
+ "CartridgeEncoder",
93
+ "DeloraConfig",
94
+ "DeloraModel",
95
+ "EvaConfig",
96
+ "FourierFTConfig",
97
+ "FourierFTModel",
98
+ "GraloraConfig",
99
+ "GraloraModel",
100
+ "HRAConfig",
101
+ "HRAModel",
102
+ "HiraConfig",
103
+ "HiraModel",
104
+ "IA3Config",
105
+ "IA3Model",
106
+ "LNTuningConfig",
107
+ "LNTuningModel",
108
+ "LilyConfig",
109
+ "LilyModel",
110
+ "LoHaConfig",
111
+ "LoHaModel",
112
+ "LoKrConfig",
113
+ "LoKrModel",
114
+ "LoftQConfig",
115
+ "LoraConfig",
116
+ "LoraGAConfig",
117
+ "LoraModel",
118
+ "LoraRuntimeConfig",
119
+ "MissConfig",
120
+ "MissModel",
121
+ "MixedModel",
122
+ "MontecloraConfig",
123
+ "MultitaskPromptEmbedding",
124
+ "MultitaskPromptTuningConfig",
125
+ "MultitaskPromptTuningInit",
126
+ "OFTConfig",
127
+ "OFTModel",
128
+ "OSFConfig",
129
+ "OSFModel",
130
+ "PeanutConfig",
131
+ "PeanutModel",
132
+ "PolyConfig",
133
+ "PolyModel",
134
+ "PrefixEncoder",
135
+ "PrefixTuningConfig",
136
+ "PromptEmbedding",
137
+ "PromptEncoder",
138
+ "PromptEncoderConfig",
139
+ "PromptEncoderReparameterizationType",
140
+ "PromptTuningConfig",
141
+ "PromptTuningInit",
142
+ "PsoftConfig",
143
+ "PsoftModel",
144
+ "PveraConfig",
145
+ "PveraModel",
146
+ "RandLoraConfig",
147
+ "RandLoraModel",
148
+ "RoadConfig",
149
+ "RoadModel",
150
+ "ShiraConfig",
151
+ "ShiraModel",
152
+ "TinyLoraConfig",
153
+ "TinyLoraModel",
154
+ "TrainableTokensConfig",
155
+ "TrainableTokensModel",
156
+ "VBLoRAConfig",
157
+ "VBLoRAModel",
158
+ "VeloraConfig",
159
+ "VeraConfig",
160
+ "VeraModel",
161
+ "WaveFTConfig",
162
+ "WaveFTModel",
163
+ "XLoraConfig",
164
+ "XLoraModel",
165
+ "convert_to_lora",
166
+ "create_arrow_model",
167
+ "get_eva_state_dict",
168
+ "initialize_lora_eva_weights",
169
+ "preprocess_loraga",
170
+ "save_as_lora",
171
+ ]
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/_buffer_dict.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ # Adapted from https://botorch.org/api/_modules/botorch/utils/torch.html
7
+
8
+ # TODO: To be removed once (if) https://github.com/pytorch/pytorch/pull/37385 lands
9
+
10
+ from __future__ import annotations
11
+
12
+ import collections
13
+ from collections import OrderedDict
14
+
15
+ import torch
16
+ from torch.nn import Module
17
+
18
+
19
+ class BufferDict(Module):
20
+ r"""
21
+ Holds buffers in a dictionary.
22
+
23
+ BufferDict can be indexed like a regular Python dictionary, but buffers it contains are properly registered, and
24
+ will be visible by all Module methods. `torch.nn.BufferDict` is an **ordered** dictionary that respects
25
+
26
+ * the order of insertion, and
27
+ * in `torch.nn.BufferDict.update`, the order of the merged `OrderedDict` or another `torch.nn.BufferDict` (the
28
+ argument to `torch.nn.BufferDict.update`).
29
+
30
+ Note that `torch.nn.BufferDict.update` with other unordered mapping types (e.g., Python's plain `dict`) does not
31
+ preserve the order of the merged mapping.
32
+
33
+ Args:
34
+ buffers (iterable, optional):
35
+ a mapping (dictionary) of (string : `torch.Tensor`) or an iterable of key-value pairs of type (string,
36
+ `torch.Tensor`)
37
+
38
+ ```python
39
+ class MyModule(nn.Module):
40
+ def __init__(self):
41
+ super().__init__()
42
+ self.buffers = nn.BufferDict({"left": torch.randn(5, 10), "right": torch.randn(5, 10)})
43
+
44
+ def forward(self, x, choice):
45
+ x = self.buffers[choice].mm(x)
46
+ return x
47
+ ```
48
+ """
49
+
50
+ def __init__(self, buffers=None, persistent: bool = False):
51
+ r"""
52
+ Args:
53
+ buffers (`dict`):
54
+ A mapping (dictionary) from string to `torch.Tensor`, or an iterable of key-value pairs of type
55
+ (string, `torch.Tensor`).
56
+ """
57
+ super().__init__()
58
+ self.persistent = persistent
59
+
60
+ if buffers is not None:
61
+ self.update(buffers)
62
+
63
+ def __getitem__(self, key):
64
+ return self._buffers[key]
65
+
66
+ def __setitem__(self, key, buffer):
67
+ self.register_buffer(key, buffer, persistent=self.persistent)
68
+
69
+ def __delitem__(self, key):
70
+ del self._buffers[key]
71
+
72
+ def __len__(self):
73
+ return len(self._buffers)
74
+
75
+ def __iter__(self):
76
+ return iter(self._buffers.keys())
77
+
78
+ def __contains__(self, key):
79
+ return key in self._buffers
80
+
81
+ def clear(self):
82
+ """Remove all items from the BufferDict."""
83
+ self._buffers.clear()
84
+
85
+ def pop(self, key):
86
+ r"""Remove key from the BufferDict and return its buffer.
87
+
88
+ Args:
89
+ key (`str`):
90
+ Key to pop from the BufferDict
91
+ """
92
+ v = self[key]
93
+ del self[key]
94
+ return v
95
+
96
+ def keys(self):
97
+ r"""Return an iterable of the BufferDict keys."""
98
+ return self._buffers.keys()
99
+
100
+ def items(self):
101
+ r"""Return an iterable of the BufferDict key/value pairs."""
102
+ return self._buffers.items()
103
+
104
+ def values(self):
105
+ r"""Return an iterable of the BufferDict values."""
106
+ return self._buffers.values()
107
+
108
+ def update(self, buffers):
109
+ r"""
110
+ Update the `torch.nn.BufferDict` with the key-value pairs from a mapping or an iterable, overwriting existing
111
+ keys.
112
+
113
+ Note:
114
+ If `buffers` is an `OrderedDict`, a `torch.nn.BufferDict`, or an iterable of key-value pairs, the order of
115
+ new elements in it is preserved.
116
+
117
+ Args:
118
+ buffers (iterable):
119
+ a mapping (dictionary) from string to `torch.Tensor`, or an iterable of key-value pairs of type
120
+ (string, `torch.Tensor`).
121
+ """
122
+ if not isinstance(buffers, collections.abc.Iterable):
123
+ raise TypeError(
124
+ "BuffersDict.update should be called with an "
125
+ "iterable of key/value pairs, but got " + type(buffers).__name__
126
+ )
127
+
128
+ if isinstance(buffers, (OrderedDict, BufferDict)):
129
+ for key, buffer in buffers.items():
130
+ self[key] = buffer
131
+ elif isinstance(buffers, collections.abc.Mapping):
132
+ for key, buffer in sorted(buffers.items()):
133
+ self[key] = buffer
134
+ else:
135
+ for j, p in enumerate(buffers):
136
+ if not isinstance(p, collections.abc.Iterable):
137
+ raise TypeError(
138
+ "BufferDict update sequence element #" + str(j) + " should be Iterable; is" + type(p).__name__
139
+ )
140
+ if not len(p) == 2:
141
+ raise ValueError(
142
+ "BufferDict update sequence element "
143
+ "#" + str(j) + " has length " + str(len(p)) + "; 2 is required"
144
+ )
145
+ self[p[0]] = p[1]
146
+
147
+ def extra_repr(self):
148
+ child_lines = []
149
+ for k, p in self._buffers.items():
150
+ size_str = "x".join(str(size) for size in p.size())
151
+ device_type = p.device.type
152
+ device_str = "" if device_type == "cpu" else f" ({device_type.upper()} {p.get_device()})"
153
+ parastr = f"Buffer containing: [{torch.typename(p)} of size {size_str}{device_str}]"
154
+ child_lines.append(" (" + k + "): " + parastr)
155
+ tmpstr = "\n".join(child_lines)
156
+ return tmpstr
157
+
158
+ def __call__(self, input):
159
+ raise RuntimeError("BufferDict should not be called.")
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adalora/__init__.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from peft.import_utils import is_bnb_4bit_available, is_bnb_available
16
+ from peft.utils import register_peft_method
17
+
18
+ from .config import AdaLoraConfig
19
+ from .gptq import SVDQuantLinear
20
+ from .layer import AdaLoraLayer, RankAllocator, SVDConv2d, SVDLinear
21
+ from .model import AdaLoraModel
22
+
23
+
24
+ __all__ = [
25
+ "AdaLoraConfig",
26
+ "AdaLoraLayer",
27
+ "AdaLoraModel",
28
+ "RankAllocator",
29
+ "SVDConv2d",
30
+ "SVDLinear",
31
+ "SVDQuantLinear",
32
+ ]
33
+
34
+
35
+ register_peft_method(
36
+ name="adalora", config_cls=AdaLoraConfig, model_cls=AdaLoraModel, prefix="lora_", is_mixed_compatible=True
37
+ )
38
+
39
+
40
+ def __getattr__(name):
41
+ if (name == "SVDLinear8bitLt") and is_bnb_available():
42
+ from .bnb import SVDLinear8bitLt
43
+
44
+ return SVDLinear8bitLt
45
+
46
+ if (name == "SVDLinear4bit") and is_bnb_4bit_available():
47
+ from .bnb import SVDLinear4bit
48
+
49
+ return SVDLinear4bit
50
+
51
+ raise AttributeError(f"module {__name__} has no attribute {name}")
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adalora/bnb.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import Any
16
+
17
+ import torch
18
+
19
+ from peft.import_utils import is_bnb_4bit_available, is_bnb_available
20
+
21
+ from .config import AdaLoraConfig
22
+ from .layer import AdaLoraLayer
23
+
24
+
25
+ if is_bnb_available():
26
+
27
+ class SVDLinear8bitLt(torch.nn.Module, AdaLoraLayer):
28
+ # Low-rank matrix for SVD-based adaptation
29
+ def __init__(
30
+ self,
31
+ base_layer: torch.nn.Module,
32
+ adapter_name: str,
33
+ config: AdaLoraConfig,
34
+ r: int = 0,
35
+ lora_alpha: int = 1,
36
+ **kwargs,
37
+ ) -> None:
38
+ super().__init__()
39
+ AdaLoraLayer.__init__(self, base_layer)
40
+ # Freezing the pre-trained weight matrix
41
+ self.get_base_layer().weight.requires_grad = False
42
+
43
+ self._active_adapter = adapter_name
44
+ self.update_layer(adapter_name, r, lora_alpha, config=config)
45
+
46
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
47
+ # note: no check for self.merged because merging is not supported (yet)
48
+ result = self.base_layer(x)
49
+
50
+ if self.disable_adapters:
51
+ return result
52
+
53
+ for active_adapter in self.active_adapters:
54
+ if active_adapter not in self.lora_A.keys():
55
+ continue
56
+ requires_conversion = not torch.is_autocast_enabled()
57
+ if requires_conversion:
58
+ expected_dtype = result.dtype
59
+ if x.dtype != torch.float32:
60
+ x = x.float()
61
+
62
+ lora_A = self.lora_A[active_adapter]
63
+ lora_B = self.lora_B[active_adapter]
64
+ lora_E = self.lora_E[active_adapter]
65
+ dropout = self.lora_dropout[active_adapter]
66
+ scaling = self.scaling[active_adapter]
67
+ ranknum = self.ranknum[active_adapter] + 1e-5
68
+
69
+ output = dropout(x) @ (lora_A * lora_E).T @ lora_B.T
70
+ if requires_conversion:
71
+ output = output.to(expected_dtype)
72
+ output = output * scaling / ranknum
73
+ # inplace operation on view is forbidden for MatMul8bitLtBackward, so avoid it
74
+ result = result + output
75
+ return result
76
+
77
+ def __repr__(self) -> str:
78
+ rep = super().__repr__()
79
+ return "adalora." + rep
80
+
81
+
82
+ if is_bnb_4bit_available():
83
+
84
+ class SVDLinear4bit(torch.nn.Module, AdaLoraLayer):
85
+ # Low-rank matrix for SVD-based adaptation
86
+ def __init__(
87
+ self,
88
+ base_layer: torch.nn.Module,
89
+ adapter_name: str,
90
+ config: AdaLoraConfig,
91
+ r: int = 0,
92
+ lora_alpha: int = 1,
93
+ **kwargs,
94
+ ) -> None:
95
+ super().__init__()
96
+ AdaLoraLayer.__init__(self, base_layer)
97
+ # Freezing the pre-trained weight matrix
98
+ self.get_base_layer().weight.requires_grad = False
99
+
100
+ self._active_adapter = adapter_name
101
+ self.update_layer(adapter_name, r, lora_alpha, config=config)
102
+
103
+ def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor:
104
+ # note: no check for self.merged because merging is not supported (yet)
105
+ result = self.base_layer(x, *args, **kwargs)
106
+
107
+ if self.disable_adapters:
108
+ return result
109
+
110
+ # As per Tim Dettmers, for 4bit, we need to defensively clone here.
111
+ # The reason is that in some cases, an error can occur that backprop
112
+ # does not work on a manipulated view. This issue may be solved with
113
+ # newer PyTorch versions but this would need extensive testing to be
114
+ # sure.
115
+ result = result.clone()
116
+
117
+ for active_adapter in self.active_adapters:
118
+ if active_adapter not in self.lora_A.keys():
119
+ continue
120
+
121
+ lora_A = self.lora_A[active_adapter]
122
+ lora_B = self.lora_B[active_adapter]
123
+ lora_E = self.lora_E[active_adapter]
124
+ dropout = self.lora_dropout[active_adapter]
125
+ scaling = self.scaling[active_adapter]
126
+ ranknum = self.ranknum[active_adapter] + 1e-5
127
+
128
+ requires_conversion = not torch.is_autocast_enabled()
129
+ if requires_conversion:
130
+ expected_dtype = result.dtype
131
+ x = self._cast_input_dtype(x, lora_A.dtype)
132
+
133
+ output = dropout(x) @ (lora_A * lora_E).T @ lora_B.T
134
+ if requires_conversion:
135
+ output = output.to(expected_dtype)
136
+ output = output * scaling / ranknum
137
+ result += output
138
+ return result
139
+
140
+ def __repr__(self) -> str:
141
+ rep = super().__repr__()
142
+ return "adalora." + rep
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adalora/config.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import warnings
16
+ from dataclasses import dataclass, field
17
+ from typing import Optional
18
+
19
+ from peft.tuners.lora import LoraConfig
20
+ from peft.utils import PeftType
21
+
22
+
23
+ @dataclass
24
+ class AdaLoraConfig(LoraConfig):
25
+ """
26
+ This is the configuration class to store the configuration of a [`AdaLoraModel`].
27
+
28
+ AdaLoRA has three phases defined by `tinit`, `tfinal` and `total_step`.
29
+
30
+ The initial phase can be understood as a step for pre-training the adapters so that when reducing their rank, there
31
+ is already some information encoded that can be reduced instead of random matrices. This phase is defined by
32
+ supplying `tinit`.
33
+
34
+ After the initial phase is over (`tinit` steps have passed) and the final phase has not begun, AdaLoRA reduces the
35
+ budget of how much rank each layer is allowed to have with each step. This is where the reduction of rank is
36
+ happening. This goes on until `total_step - tfinal` steps are reached.
37
+
38
+ The last phase, beginning once `total_step - tfinal` steps are reached, does not change the layer ranks anymore but
39
+ fine-tunes the reduced-rank layers that resulted from the previous phase.
40
+
41
+ A practical example: `tinit` is 10, `tfinal` is 20, `total_step` is 100. We spend 10 steps doing pre-training
42
+ without rank reduction because our budget is constant (init phase), then we spend 80 (100-20) steps in the
43
+ reduction phase where our budget decreases step-wise and, finally, 20 steps in the final fine-tuning stage without
44
+ reduction.
45
+
46
+ Args:
47
+ target_r (`int`): The target average rank of incremental matrix.
48
+ init_r (`int`): The initial rank for each incremental matrix.
49
+ tinit (`int`): The steps of initial fine-tuning warmup.
50
+ tfinal (`int`): The number of steps of final fine-tuning.
51
+ deltaT (`int`): The time internval between two budget allocations.
52
+ beta1 (`float`): The hyperparameter of EMA for sensitivity smoothing.
53
+ beta2 (`float`): The hyperparameter of EMA for undertainty quantification.
54
+ orth_reg_weight (`float`): The coefficient of orthogonal regularization.
55
+ total_step (`int`): The total training steps that should be specified before training.
56
+ rank_pattern (`list`): The allocated rank for each weight matrix by RankAllocator.
57
+ """
58
+
59
+ target_r: int = field(default=8, metadata={"help": "Target Lora matrix dimension."})
60
+ init_r: int = field(default=12, metadata={"help": "Initial Lora matrix dimension."})
61
+ tinit: int = field(default=0, metadata={"help": "The steps of initial warmup."})
62
+ tfinal: int = field(default=0, metadata={"help": "The steps of final warmup."})
63
+ deltaT: int = field(default=1, metadata={"help": "Step interval of rank allocation."})
64
+ beta1: float = field(default=0.85, metadata={"help": "Hyperparameter of EMA."})
65
+ beta2: float = field(default=0.85, metadata={"help": "Hyperparameter of EMA."})
66
+ orth_reg_weight: float = field(default=0.5, metadata={"help": "The orthogonal regularization coefficient."})
67
+ total_step: Optional[int] = field(default=None, metadata={"help": "The total training steps."})
68
+ rank_pattern: Optional[dict] = field(default=None, metadata={"help": "The saved rank pattern."})
69
+
70
+ def __post_init__(self):
71
+ super().__post_init__()
72
+ self.peft_type = PeftType.ADALORA
73
+
74
+ if self.use_dora:
75
+ raise ValueError(f"{self.peft_type} does not support DoRA.")
76
+
77
+ if self.loftq_config:
78
+ raise ValueError(f"{self.peft_type} does not support LOFTQ.")
79
+
80
+ self.target_modules = (
81
+ set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules
82
+ )
83
+ self.exclude_modules = (
84
+ set(self.exclude_modules) if isinstance(self.exclude_modules, list) else self.exclude_modules
85
+ )
86
+ # if target_modules is a regex expression, then layers_to_transform should be None
87
+ if isinstance(self.target_modules, str) and self.layers_to_transform is not None:
88
+ raise ValueError("`layers_to_transform` cannot be used when `target_modules` is a str.")
89
+
90
+ # check for layers_to_transform and layers_pattern
91
+ if self.layers_pattern and not self.layers_to_transform:
92
+ raise ValueError("When `layers_pattern` is specified, `layers_to_transform` must also be specified. ")
93
+
94
+ # Check if 'r' has been set to a non-default value
95
+ if self.r != 8: # 8 is the default value for 'r' in LoraConfig
96
+ warnings.warn(
97
+ "Note that `r` is not used in AdaLora and will be ignored."
98
+ "If you intended to set the initial rank, use `init_r` instead."
99
+ )
100
+
101
+ if self.total_step is None or self.total_step <= 0:
102
+ raise ValueError("AdaLoRA does not work when `total_step` is None, supply a value > 0.")
103
+
104
+ if self.tinit >= (self.total_step - self.tfinal):
105
+ raise ValueError(
106
+ "The supplied schedule values don't allow for a budgeting phase. Decrease `tfinal`/`tinit` or "
107
+ "increase `total_step`."
108
+ )
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adalora/gptq.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import torch
15
+
16
+ from .config import AdaLoraConfig
17
+ from .layer import AdaLoraLayer
18
+
19
+
20
+ class SVDQuantLinear(torch.nn.Module, AdaLoraLayer):
21
+ def __init__(
22
+ self,
23
+ base_layer,
24
+ adapter_name,
25
+ config: AdaLoraConfig,
26
+ r: int = 0,
27
+ lora_alpha: int = 1,
28
+ **kwargs,
29
+ ) -> None:
30
+ super().__init__()
31
+ AdaLoraLayer.__init__(self, base_layer)
32
+
33
+ # self.base_layer and self.quant_linear_module are the same; we need the former for consistency and the latter
34
+ # for backwards compatibility
35
+ self.quant_linear_module = base_layer
36
+ self._active_adapter = adapter_name
37
+ self.update_layer(adapter_name, r, lora_alpha=lora_alpha, config=config)
38
+
39
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
40
+ result = self.quant_linear_module(x)
41
+
42
+ if self.disable_adapters:
43
+ return result
44
+
45
+ for active_adapter in self.active_adapters:
46
+ if active_adapter not in self.lora_A.keys():
47
+ continue
48
+ lora_A = self.lora_A[active_adapter]
49
+ lora_B = self.lora_B[active_adapter]
50
+ lora_E = self.lora_E[active_adapter]
51
+ dropout = self.lora_dropout[active_adapter]
52
+ scaling = self.scaling[active_adapter]
53
+ ranknum = self.ranknum[active_adapter] + 1e-5
54
+
55
+ requires_conversion = not torch.is_autocast_enabled()
56
+ if requires_conversion:
57
+ expected_dtype = result.dtype
58
+ x = self._cast_input_dtype(x, torch.float32)
59
+
60
+ output = (dropout(x) @ (lora_A * lora_E).T @ lora_B.T) * scaling / ranknum
61
+ # TODO: here, the dtype conversion is applied on the *whole expression*,
62
+ # not the intermediate result, unlike for SVDLinear8bitLT and
63
+ # SVDLinear4bit, is that correct?
64
+ if requires_conversion:
65
+ output = output.to(expected_dtype)
66
+ result += output
67
+ return result
68
+
69
+ def __repr__(self) -> str:
70
+ rep = super().__repr__()
71
+ return "adalora." + rep
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adalora/layer.py ADDED
@@ -0,0 +1,515 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import warnings
16
+ from typing import Any, Optional
17
+
18
+ import packaging
19
+ import torch
20
+ import transformers
21
+ from torch import nn
22
+
23
+ from peft.tuners.lora import LoraLayer
24
+ from peft.tuners.tuners_utils import check_adapters_to_merge
25
+ from peft.utils import transpose
26
+ from peft.utils.integrations import _skip_init_on_device
27
+
28
+ from .config import AdaLoraConfig
29
+
30
+
31
+ if packaging.version.parse(transformers.__version__) >= packaging.version.parse("4.33.0"):
32
+ from transformers.integrations import deepspeed_config
33
+ else:
34
+ from transformers.deepspeed import deepspeed_config
35
+
36
+
37
+ class AdaLoraLayer(LoraLayer):
38
+ # List all names of layers that may contain adapter weights
39
+ # Note: ranknum doesn't need to be included as it is not an nn.Module
40
+ adapter_layer_names = ("lora_A", "lora_B", "lora_E", "lora_embedding_A", "lora_embedding_B")
41
+ # All names of other parameters that may contain adapter-related parameters
42
+ other_param_names = ("r", "lora_alpha", "scaling", "lora_dropout", "ranknum")
43
+
44
+ def __init__(self, base_layer: nn.Module) -> None:
45
+ super().__init__(base_layer)
46
+ self.lora_E = nn.ParameterDict({})
47
+ self.lora_A = nn.ParameterDict({})
48
+ self.lora_B = nn.ParameterDict({})
49
+ self.ranknum = nn.ParameterDict({})
50
+
51
+ def update_layer(self, adapter_name: str, r: int, lora_alpha: int, config: AdaLoraConfig, **kwargs) -> None:
52
+ lora_dropout = config.lora_dropout
53
+ init_lora_weights = config.init_lora_weights
54
+ inference_mode = config.inference_mode
55
+ if r < 0:
56
+ # note: r == 0 is allowed for AdaLora, see #1539
57
+ raise ValueError(f"`r` should be a positive integer or 0, but the value passed is {r}")
58
+
59
+ self.r[adapter_name] = r
60
+ self.lora_alpha[adapter_name] = lora_alpha
61
+ if lora_dropout > 0.0:
62
+ lora_dropout_layer = nn.Dropout(p=lora_dropout)
63
+ else:
64
+ lora_dropout_layer = nn.Identity()
65
+
66
+ self.lora_dropout[adapter_name] = lora_dropout_layer
67
+ # Actual trainable parameters
68
+ # Right singular vectors
69
+ self.lora_A[adapter_name] = nn.Parameter(torch.randn(r, self.in_features))
70
+ # Singular values
71
+ self.lora_E[adapter_name] = nn.Parameter(torch.randn(r, 1))
72
+ # Left singular vectors
73
+ self.lora_B[adapter_name] = nn.Parameter(torch.randn(self.out_features, r))
74
+ # The current rank. ranknum is deterministic (always set to float(r)) and is not saved
75
+ # in the adapter state_dict, so under low_cpu_mem_usage=True it can't be restored from a
76
+ # checkpoint and must stay off the meta device. Two places need to skip the meta dispatch:
77
+ # 1) creation, otherwise the Parameter is registered on meta from the start;
78
+ # 2) the subsequent _move_adapter_to_device_of_base_layer call, because moving the
79
+ # ParameterDict entry re-registers it via Module.__setattr__ → register_parameter,
80
+ # which inside init_empty_weights would send the tensor back to meta.
81
+ with _skip_init_on_device():
82
+ self.ranknum[adapter_name] = nn.Parameter(torch.randn(1), requires_grad=False)
83
+ self.ranknum[adapter_name].data.fill_(float(r))
84
+ self.ranknum[adapter_name].requires_grad = False
85
+ self.scaling[adapter_name] = lora_alpha if lora_alpha > 0 else float(r)
86
+ if init_lora_weights:
87
+ self.reset_lora_parameters(adapter_name)
88
+
89
+ self._move_adapter_to_device_of_base_layer(adapter_name)
90
+ self.set_adapter(self.active_adapters, inference_mode=inference_mode)
91
+
92
+ def reset_lora_parameters(self, adapter_name):
93
+ if adapter_name in self.lora_A.keys():
94
+ nn.init.zeros_(self.lora_E[adapter_name])
95
+ nn.init.normal_(self.lora_A[adapter_name], mean=0.0, std=0.02)
96
+ nn.init.normal_(self.lora_B[adapter_name], mean=0.0, std=0.02)
97
+
98
+
99
+ class SVDLinear(nn.Module, AdaLoraLayer):
100
+ # SVD-based adaptation by a dense layer
101
+ def __init__(
102
+ self,
103
+ base_layer: nn.Module,
104
+ adapter_name: str,
105
+ config: AdaLoraConfig,
106
+ r: int = 0,
107
+ lora_alpha: int = 1,
108
+ **kwargs,
109
+ ) -> None:
110
+ super().__init__()
111
+ AdaLoraLayer.__init__(self, base_layer)
112
+ # Freezing the pre-trained weight matrix
113
+ self.get_base_layer().weight.requires_grad = False
114
+
115
+ self.fan_in_fan_out = config.fan_in_fan_out
116
+ self._active_adapter = adapter_name
117
+ self.update_layer(adapter_name, r, lora_alpha, config=config)
118
+
119
+ def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None:
120
+ """
121
+ Merge the active adapter weights into the base weights
122
+
123
+ Args:
124
+ safe_merge (`bool`, *optional*):
125
+ If True, the merge operation will be performed in a copy of the original weights and check for NaNs
126
+ before merging the weights. This is useful if you want to check if the merge operation will produce
127
+ NaNs. Defaults to `False`.
128
+ adapter_names (`List[str]`, *optional*):
129
+ The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults
130
+ to `None`.
131
+ """
132
+ adapter_names = check_adapters_to_merge(self, adapter_names)
133
+ if not adapter_names:
134
+ # no adapter to merge
135
+ return
136
+
137
+ for active_adapter in adapter_names:
138
+ base_layer = self.get_base_layer()
139
+ if active_adapter in self.lora_A.keys():
140
+ if safe_merge:
141
+ # Note that safe_merge will be slower than the normal merge
142
+ # because of the copy operation.
143
+ orig_weights = base_layer.weight.data.clone()
144
+ orig_weights += self.get_delta_weight(active_adapter)
145
+
146
+ if not torch.isfinite(orig_weights).all():
147
+ raise ValueError(
148
+ f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken"
149
+ )
150
+
151
+ base_layer.weight.data = orig_weights
152
+ else:
153
+ base_layer.weight.data += self.get_delta_weight(active_adapter)
154
+ self.merged_adapters.append(active_adapter)
155
+
156
+ def unmerge(self) -> None:
157
+ """
158
+ This method unmerges all merged adapter layers from the base weights.
159
+ """
160
+ if not self.merged:
161
+ warnings.warn("Already unmerged. Nothing to do.")
162
+ return
163
+ while len(self.merged_adapters) > 0:
164
+ active_adapter = self.merged_adapters.pop()
165
+ if active_adapter in self.lora_A.keys():
166
+ self.get_base_layer().weight.data -= self.get_delta_weight(active_adapter)
167
+
168
+ def get_delta_weight(self, adapter) -> torch.Tensor:
169
+ return (
170
+ transpose(self.lora_B[adapter] @ (self.lora_A[adapter] * self.lora_E[adapter]), self.fan_in_fan_out)
171
+ * self.scaling[adapter]
172
+ / (self.ranknum[adapter] + 1e-5)
173
+ )
174
+
175
+ def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor:
176
+ if self.disable_adapters:
177
+ if self.merged:
178
+ self.unmerge()
179
+ result = self.base_layer(x, *args, **kwargs)
180
+ elif self.merged:
181
+ result = self.base_layer(x, *args, **kwargs)
182
+ else:
183
+ result = self.base_layer(x, *args, **kwargs)
184
+ for active_adapter in self.active_adapters:
185
+ if active_adapter not in self.lora_A.keys():
186
+ continue
187
+ lora_A = self.lora_A[active_adapter]
188
+ lora_B = self.lora_B[active_adapter]
189
+ lora_E = self.lora_E[active_adapter]
190
+ dropout = self.lora_dropout[active_adapter]
191
+ scaling = self.scaling[active_adapter]
192
+ ranknum = self.ranknum[active_adapter] + 1e-5
193
+
194
+ x = self._cast_input_dtype(x, lora_A.dtype)
195
+ result += (dropout(x) @ (lora_A * lora_E).T @ lora_B.T) * scaling / ranknum
196
+
197
+ return result
198
+
199
+ def __repr__(self) -> str:
200
+ rep = super().__repr__()
201
+ return "adalora." + rep
202
+
203
+
204
+ class SVDConv2d(nn.Module, AdaLoraLayer):
205
+ # SVD-based adaptation by a Conv2d layer
206
+ def __init__(
207
+ self,
208
+ base_layer: nn.Module,
209
+ adapter_name: str,
210
+ config: AdaLoraConfig,
211
+ r: int = 0,
212
+ lora_alpha: int = 1,
213
+ **kwargs,
214
+ ) -> None:
215
+ super().__init__()
216
+ AdaLoraLayer.__init__(self, base_layer)
217
+ self.get_base_layer().weight.requires_grad = False
218
+ self._active_adapter = adapter_name
219
+ self.update_layer(adapter_name, r, lora_alpha, config=config)
220
+
221
+ def update_layer(self, adapter_name: str, r: int, lora_alpha: int, config: AdaLoraConfig, **kwargs) -> None:
222
+ lora_dropout = config.lora_dropout
223
+ init_lora_weights = config.init_lora_weights
224
+ inference_mode = config.inference_mode
225
+ if r < 0:
226
+ raise ValueError(f"`r` should be a positive integer or 0, but the value passed is {r}")
227
+
228
+ self.r[adapter_name] = r
229
+ self.lora_alpha[adapter_name] = lora_alpha
230
+ if lora_dropout > 0.0:
231
+ lora_dropout_layer = nn.Dropout(p=lora_dropout)
232
+ else:
233
+ lora_dropout_layer = nn.Identity()
234
+ self.lora_dropout[adapter_name] = lora_dropout_layer
235
+
236
+ base = self.get_base_layer()
237
+ k = base.kernel_size[0] * base.kernel_size[1]
238
+ # Right singular vectors: (r, in_channels * kH * kW)
239
+ self.lora_A[adapter_name] = nn.Parameter(torch.randn(r, self.in_features * k))
240
+ # Singular values: (r, 1)
241
+ self.lora_E[adapter_name] = nn.Parameter(torch.randn(r, 1))
242
+ # Left singular vectors: (out_channels, r)
243
+ self.lora_B[adapter_name] = nn.Parameter(torch.randn(self.out_features, r))
244
+ # Current rank — see note in AdaLoraLayer.update_layer about _skip_init_on_device.
245
+ with _skip_init_on_device():
246
+ self.ranknum[adapter_name] = nn.Parameter(torch.randn(1), requires_grad=False)
247
+ self.ranknum[adapter_name].data.fill_(float(r))
248
+ self.ranknum[adapter_name].requires_grad = False
249
+ self.scaling[adapter_name] = lora_alpha if lora_alpha > 0 else float(r)
250
+ if init_lora_weights:
251
+ self.reset_lora_parameters(adapter_name)
252
+
253
+ self._move_adapter_to_device_of_base_layer(adapter_name)
254
+ self.set_adapter(self.active_adapters, inference_mode=inference_mode)
255
+
256
+ def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None:
257
+ """
258
+ Merge the active adapter weights into the base weights
259
+
260
+ Args:
261
+ safe_merge (`bool`, *optional*):
262
+ If True, the merge operation will be performed in a copy of the original weights and check for NaNs
263
+ before merging the weights. This is useful if you want to check if the merge operation will produce
264
+ NaNs. Defaults to `False`.
265
+ adapter_names (`List[str]`, *optional*):
266
+ The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults
267
+ to `None`.
268
+ """
269
+ adapter_names = check_adapters_to_merge(self, adapter_names)
270
+ if not adapter_names:
271
+ return
272
+
273
+ for active_adapter in adapter_names:
274
+ base_layer = self.get_base_layer()
275
+ if active_adapter in self.lora_A.keys():
276
+ if safe_merge:
277
+ orig_weights = base_layer.weight.data.clone()
278
+ orig_weights += self.get_delta_weight(active_adapter)
279
+
280
+ if not torch.isfinite(orig_weights).all():
281
+ raise ValueError(
282
+ f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken"
283
+ )
284
+
285
+ base_layer.weight.data = orig_weights
286
+ else:
287
+ base_layer.weight.data += self.get_delta_weight(active_adapter)
288
+ self.merged_adapters.append(active_adapter)
289
+
290
+ def unmerge(self) -> None:
291
+ """
292
+ This method unmerges all merged adapter layers from the base weights.
293
+ """
294
+ if not self.merged:
295
+ warnings.warn("Already unmerged. Nothing to do.")
296
+ return
297
+ while len(self.merged_adapters) > 0:
298
+ active_adapter = self.merged_adapters.pop()
299
+ if active_adapter in self.lora_A.keys():
300
+ self.get_base_layer().weight.data -= self.get_delta_weight(active_adapter)
301
+
302
+ def get_delta_weight(self, adapter) -> torch.Tensor:
303
+ delta = (
304
+ self.lora_B[adapter]
305
+ @ (self.lora_A[adapter] * self.lora_E[adapter])
306
+ * self.scaling[adapter]
307
+ / (self.ranknum[adapter] + 1e-5)
308
+ )
309
+ return delta.reshape(self.get_base_layer().weight.shape)
310
+
311
+ def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor:
312
+ if self.disable_adapters:
313
+ if self.merged:
314
+ self.unmerge()
315
+ result = self.base_layer(x, *args, **kwargs)
316
+ elif self.merged:
317
+ result = self.base_layer(x, *args, **kwargs)
318
+ else:
319
+ result = self.base_layer(x, *args, **kwargs)
320
+ for active_adapter in self.active_adapters:
321
+ if active_adapter not in self.lora_A.keys():
322
+ continue
323
+ lora_A = self.lora_A[active_adapter]
324
+ lora_B = self.lora_B[active_adapter]
325
+ lora_E = self.lora_E[active_adapter]
326
+ dropout = self.lora_dropout[active_adapter]
327
+ scaling = self.scaling[active_adapter]
328
+ ranknum = self.ranknum[active_adapter] + 1e-5
329
+
330
+ x = self._cast_input_dtype(x, lora_A.dtype)
331
+ base = self.get_base_layer()
332
+ delta_w = (lora_B @ (lora_A * lora_E) * scaling / ranknum).reshape(base.weight.shape)
333
+ # Use in-place add so result keeps its original dtype (matches SVDLinear);
334
+ # otherwise result would be upcast to lora_A.dtype and break subsequent fp16/bf16 ops.
335
+ result += nn.functional.conv2d(
336
+ dropout(x),
337
+ delta_w,
338
+ stride=base.stride,
339
+ padding=base.padding,
340
+ dilation=base.dilation,
341
+ groups=base.groups,
342
+ )
343
+ return result
344
+
345
+ def __repr__(self) -> str:
346
+ rep = super().__repr__()
347
+ return "adalora." + rep
348
+
349
+
350
+ class RankAllocator:
351
+ """
352
+ The RankAllocator for AdaLoraModel. Paper: https://openreview.net/pdf?id=lq62uWRJjiY
353
+
354
+ Args:
355
+ config ([`AdaLoraConfig`]): The configuration of the AdaLora model.
356
+ model: the model that we apply AdaLoRA to.
357
+
358
+ """
359
+
360
+ def __init__(self, model, peft_config, adapter_name):
361
+ self.peft_config = peft_config
362
+ self.adapter_name = adapter_name
363
+ self.beta1 = peft_config.beta1
364
+ self.beta2 = peft_config.beta2
365
+ assert self.beta1 > 0 and self.beta1 < 1
366
+ assert self.beta2 > 0 and self.beta2 < 1
367
+
368
+ self.reset_ipt()
369
+ self._set_budget_scheduler(model)
370
+
371
+ def set_total_step(self, total_step):
372
+ self.peft_config.total_step = total_step
373
+
374
+ def reset_ipt(self):
375
+ self.ipt = {}
376
+ self.exp_avg_ipt = {}
377
+ self.exp_avg_unc = {}
378
+
379
+ def _set_budget_scheduler(self, model):
380
+ self.init_bgt = 0
381
+ self.name_set = set()
382
+ for n, p in model.named_parameters():
383
+ if f"lora_A.{self.adapter_name}" in n:
384
+ self.init_bgt += p.size(0)
385
+ self.name_set.add(n.replace("lora_A", "%s"))
386
+ self.name_set = sorted(self.name_set)
387
+ # The total final rank budget
388
+ self.target_bgt = self.peft_config.target_r * len(self.name_set)
389
+
390
+ def budget_schedule(self, step: int):
391
+ tinit = self.peft_config.tinit
392
+ tfinal = self.peft_config.tfinal
393
+ total_step = self.peft_config.total_step
394
+ # Initial warmup
395
+ if step <= tinit:
396
+ budget = self.init_bgt
397
+ mask_ind = False
398
+ # Final fine-tuning
399
+ elif step > total_step - tfinal:
400
+ budget = self.target_bgt
401
+ mask_ind = True
402
+ else:
403
+ # Budget decreasing with a cubic scheduler
404
+ mul_coeff = 1 - (step - tinit) / (total_step - tfinal - tinit)
405
+ budget = int((self.init_bgt - self.target_bgt) * (mul_coeff**3) + self.target_bgt)
406
+ mask_ind = step % self.peft_config.deltaT == 0
407
+ return budget, mask_ind
408
+
409
+ def update_ipt(self, model):
410
+ # Update the sensitivity and uncertainty for every weight
411
+ for n, p in model.named_parameters():
412
+ if "lora_" in n and self.adapter_name in n:
413
+ if n not in self.ipt:
414
+ self.ipt[n] = torch.zeros_like(p)
415
+ self.exp_avg_ipt[n] = torch.zeros_like(p)
416
+ self.exp_avg_unc[n] = torch.zeros_like(p)
417
+ with torch.no_grad():
418
+ if deepspeed_config() is not None:
419
+ import deepspeed
420
+
421
+ grad = deepspeed.utils.safe_get_full_grad(p)
422
+ self.ipt[n] = (p * grad).abs().detach()
423
+ else:
424
+ self.ipt[n] = (p * p.grad).abs().detach()
425
+ # Sensitivity smoothing
426
+ self.exp_avg_ipt[n] = self.beta1 * self.exp_avg_ipt[n] + (1 - self.beta1) * self.ipt[n]
427
+ # Uncertainty quantification
428
+ self.exp_avg_unc[n] = (
429
+ self.beta2 * self.exp_avg_unc[n] + (1 - self.beta2) * (self.ipt[n] - self.exp_avg_ipt[n]).abs()
430
+ )
431
+
432
+ def _element_score(self, n):
433
+ return self.exp_avg_ipt[n] * self.exp_avg_unc[n]
434
+
435
+ def _combine_ipt(self, ipt_E, ipt_AB):
436
+ ipt_AB = ipt_AB.sum(dim=1, keepdim=False)
437
+ sum_ipt = ipt_E.view(-1) + ipt_AB.view(-1)
438
+ return sum_ipt
439
+
440
+ def mask_to_budget(self, model, budget):
441
+ value_ipt = {}
442
+ vector_ipt = {}
443
+ triplet_ipt = {}
444
+ # Get the importance score for A, E, B
445
+ for n, p in model.named_parameters():
446
+ if f"lora_A.{self.adapter_name}" in n:
447
+ entry_ipt = self._element_score(n)
448
+ comb_ipt = torch.mean(entry_ipt, dim=1, keepdim=True)
449
+ name_m = n.replace("lora_A", "%s")
450
+ if name_m not in vector_ipt:
451
+ vector_ipt[name_m] = [comb_ipt]
452
+ else:
453
+ vector_ipt[name_m].append(comb_ipt)
454
+ if f"lora_B.{self.adapter_name}" in n:
455
+ entry_ipt = self._element_score(n)
456
+ comb_ipt = torch.mean(entry_ipt, dim=0, keepdim=False).view(-1, 1)
457
+ name_m = n.replace("lora_B", "%s")
458
+ if name_m not in vector_ipt:
459
+ vector_ipt[name_m] = [comb_ipt]
460
+ else:
461
+ vector_ipt[name_m].append(comb_ipt)
462
+ if f"lora_E.{self.adapter_name}" in n:
463
+ entry_ipt = self._element_score(n)
464
+ name_m = n.replace("lora_E", "%s")
465
+ value_ipt[name_m] = entry_ipt
466
+
467
+ all_score = []
468
+ # Calculate the score for each triplet
469
+ for name_m in vector_ipt:
470
+ ipt_E = value_ipt[name_m]
471
+ ipt_AB = torch.cat(vector_ipt[name_m], dim=1)
472
+ sum_ipt = self._combine_ipt(ipt_E, ipt_AB)
473
+ name_E = name_m % "lora_E"
474
+ triplet_ipt[name_E] = sum_ipt.view(-1, 1)
475
+ all_score.append(sum_ipt.view(-1))
476
+
477
+ # Get the threshold by ranking ipt
478
+ mask_threshold = torch.kthvalue(
479
+ torch.cat(all_score),
480
+ k=self.init_bgt - budget,
481
+ )[0].item()
482
+
483
+ rank_pattern = {}
484
+ # Mask the unimportant triplets
485
+ with torch.no_grad():
486
+ for n, p in model.named_parameters():
487
+ if f"lora_E.{self.adapter_name}" in n:
488
+ p.masked_fill_(triplet_ipt[n] <= mask_threshold, 0.0)
489
+ rank_pattern[n] = (~(triplet_ipt[n] <= mask_threshold)).view(-1).tolist()
490
+ return rank_pattern
491
+
492
+ def update_and_allocate(self, model, global_step, force_mask=False):
493
+ # # Update the importance score and allocate the budget
494
+ if global_step < self.peft_config.total_step - self.peft_config.tfinal:
495
+ self.update_ipt(model)
496
+ budget, mask_ind = self.budget_schedule(global_step)
497
+ # Allocate the budget according to importance scores
498
+ if mask_ind or force_mask:
499
+ rank_pattern = self.mask_to_budget(model, budget)
500
+ else:
501
+ rank_pattern = None
502
+ return budget, rank_pattern
503
+
504
+ def mask_using_rank_pattern(self, model, rank_pattern):
505
+ # Mask the unimportant triplets
506
+ is_adapter_name_truncated = False
507
+ if self.adapter_name not in next(iter(rank_pattern.keys())):
508
+ is_adapter_name_truncated = True
509
+
510
+ with torch.no_grad():
511
+ for n, p in model.named_parameters():
512
+ if f"lora_E.{self.adapter_name}" in n:
513
+ key = n if not is_adapter_name_truncated else n.replace(f".{self.adapter_name}", "")
514
+ mask = torch.Tensor(rank_pattern[key]).unsqueeze(-1).to(p.device)
515
+ p.masked_fill_(~mask.bool(), 0.0)
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adalora/model.py ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import warnings
16
+
17
+ import torch
18
+ from transformers.pytorch_utils import Conv1D
19
+
20
+ from peft.import_utils import is_bnb_4bit_available, is_bnb_available
21
+ from peft.tuners.lora import LoraConfig, LoraModel
22
+ from peft.tuners.tuners_utils import BaseTunerLayer, get_device_map
23
+ from peft.utils import (
24
+ TRANSFORMERS_MODELS_TO_ADALORA_TARGET_MODULES_MAPPING,
25
+ _freeze_adapter,
26
+ _get_submodules,
27
+ get_gptqmodel_quant_linear,
28
+ get_quantization_config,
29
+ )
30
+ from peft.utils.integrations import gather_params_ctx
31
+
32
+ from .gptq import SVDQuantLinear
33
+ from .layer import AdaLoraLayer, RankAllocator, SVDConv2d, SVDLinear
34
+
35
+
36
+ class AdaLoraModel(LoraModel):
37
+ """
38
+ Creates AdaLoRA (Adaptive LoRA) model from a pretrained transformers model. Paper:
39
+ https://openreview.net/forum?id=lq62uWRJjiY
40
+
41
+ Args:
42
+ model ([`transformers.PreTrainedModel`]): The model to be adapted.
43
+ config ([`AdaLoraConfig`]): The configuration of the AdaLora model.
44
+ adapter_name (`str`): The name of the adapter, defaults to `"default"`.
45
+ low_cpu_mem_usage (`bool`, `optional`, defaults to `False`):
46
+ Create empty adapter weights on meta device. Useful to speed up the loading process.
47
+
48
+ Returns:
49
+ `torch.nn.Module`: The AdaLora model.
50
+
51
+ Example:
52
+ ```py
53
+ >>> from transformers import AutoModelForSeq2SeqLM
54
+ >>> from peft import AdaLoraConfig, get_peft_model
55
+
56
+ >>> config = AdaLoraConfig(
57
+ ... peft_type="ADALORA",
58
+ ... task_type="SEQ_2_SEQ_LM",
59
+ ... init_r=12,
60
+ ... lora_alpha=32,
61
+ ... target_modules=["q", "v"],
62
+ ... lora_dropout=0.01,
63
+ ... total_step=1000,
64
+ ... )
65
+ >>> model = AutoModelForSeq2SeqLM.from_pretrained("t5-base")
66
+ >>> adalora_model = get_peft_model(model, config)
67
+ ```
68
+
69
+ **Attributes**:
70
+ - **model** ([`transformers.PreTrainedModel`]) -- The model to be adapted.
71
+ - **peft_config** ([`AdaLoraConfig`]): The configuration of the AdaLora model.
72
+ """
73
+
74
+ # Note: don't redefine prefix or tuner_layer_cls here, it should be inherited from LoraModel
75
+ target_module_mapping = TRANSFORMERS_MODELS_TO_ADALORA_TARGET_MODULES_MAPPING
76
+
77
+ def __init__(self, model, config, adapter_name, **kwargs):
78
+ super().__init__(model, config, adapter_name, **kwargs)
79
+
80
+ traininable_mode_counter = 0
81
+ for peft_config in self.peft_config.values():
82
+ if not peft_config.inference_mode:
83
+ traininable_mode_counter += 1
84
+
85
+ if traininable_mode_counter > 1:
86
+ raise ValueError(
87
+ "AdaLoraModel supports only 1 trainable adapter. "
88
+ "When using multiple adapters, set inference_mode to True for all adapters except the one you want to train."
89
+ )
90
+
91
+ if self.peft_config[adapter_name].inference_mode:
92
+ _freeze_adapter(self.model, adapter_name)
93
+ else:
94
+ self.trainable_adapter_name = adapter_name
95
+ self.rankallocator = RankAllocator(self.model, self.peft_config[adapter_name], self.trainable_adapter_name)
96
+
97
+ def _check_new_adapter_config(self, config: LoraConfig) -> None:
98
+ """
99
+ A helper method to check the config when a new adapter is being added.
100
+
101
+ Raise a ValueError if there is something wrong with the config or if it conflicts with existing adapters.
102
+
103
+ """
104
+ super()._check_new_adapter_config(config)
105
+
106
+ traininable_mode_counter = 0
107
+ for config_ in self.peft_config.values():
108
+ if not config_.inference_mode:
109
+ traininable_mode_counter += 1
110
+
111
+ if traininable_mode_counter > 1:
112
+ raise ValueError(
113
+ f"{self.__class__.__name__} supports only 1 trainable adapter. "
114
+ "When using multiple adapters, set inference_mode to True for all adapters except the one "
115
+ "you want to train."
116
+ )
117
+
118
+ def _create_and_replace(
119
+ self,
120
+ lora_config,
121
+ adapter_name,
122
+ target,
123
+ target_name,
124
+ parent,
125
+ current_key,
126
+ ):
127
+ kwargs = {
128
+ "r": lora_config.init_r,
129
+ "lora_alpha": lora_config.lora_alpha,
130
+ "loaded_in_8bit": getattr(self.model, "is_loaded_in_8bit", False),
131
+ "loaded_in_4bit": getattr(self.model, "is_loaded_in_4bit", False),
132
+ }
133
+ if (kwargs["loaded_in_8bit"] or kwargs["loaded_in_4bit"]) and not is_bnb_available():
134
+ raise ImportError(
135
+ "To use AdaLora with 8-bit quantization, please install the `bitsandbytes` package. "
136
+ "You can install it with `pip install bitsandbytes`."
137
+ )
138
+
139
+ quantization_config = get_quantization_config(self.model, method="gptq")
140
+ if quantization_config is not None:
141
+ kwargs["gptq_quantization_config"] = quantization_config
142
+
143
+ # If it is not an AdaLoraLayer, create a new module, else update it with new adapters
144
+ if not isinstance(target, AdaLoraLayer):
145
+ device_map = get_device_map(self.model)
146
+ new_module = self._create_new_module(lora_config, adapter_name, target, device_map=device_map, **kwargs)
147
+ if adapter_name not in self.active_adapters:
148
+ # adding an additional adapter: it is not automatically trainable
149
+ new_module.requires_grad_(False)
150
+ self._replace_module(parent, target_name, new_module, target)
151
+ else:
152
+ target.update_layer(
153
+ adapter_name,
154
+ lora_config.init_r,
155
+ lora_config.lora_alpha,
156
+ config=lora_config,
157
+ )
158
+
159
+ @staticmethod
160
+ def _create_new_module(lora_config, adapter_name, target, device_map=None, **kwargs):
161
+ # avoid eager bnb import
162
+ if is_bnb_available():
163
+ import bitsandbytes as bnb
164
+
165
+ from .bnb import SVDLinear8bitLt
166
+ if is_bnb_4bit_available():
167
+ from .bnb import SVDLinear4bit
168
+
169
+ gptq_quantization_config = kwargs.get("gptq_quantization_config", None)
170
+
171
+ QuantLinear = get_gptqmodel_quant_linear(gptq_quantization_config, device_map=device_map)
172
+
173
+ loaded_in_8bit = kwargs.pop("loaded_in_8bit", False)
174
+ loaded_in_4bit = kwargs.pop("loaded_in_4bit", False)
175
+
176
+ if isinstance(target, BaseTunerLayer):
177
+ target_base_layer = target.get_base_layer()
178
+ else:
179
+ target_base_layer = target
180
+
181
+ if loaded_in_8bit and isinstance(target_base_layer, bnb.nn.Linear8bitLt):
182
+ kwargs.update(
183
+ {
184
+ "has_fp16_weights": target_base_layer.state.has_fp16_weights,
185
+ "threshold": target_base_layer.state.threshold,
186
+ "index": target_base_layer.index,
187
+ }
188
+ )
189
+ new_module = SVDLinear8bitLt(target, adapter_name, config=lora_config, **kwargs)
190
+ elif loaded_in_4bit and is_bnb_4bit_available() and isinstance(target_base_layer, bnb.nn.Linear4bit):
191
+ fourbit_kwargs = kwargs.copy()
192
+ fourbit_kwargs.update(
193
+ {
194
+ "compute_dtype": target_base_layer.compute_dtype,
195
+ "compress_statistics": target_base_layer.weight.compress_statistics,
196
+ "quant_type": target_base_layer.weight.quant_type,
197
+ }
198
+ )
199
+ new_module = SVDLinear4bit(target, adapter_name, config=lora_config, **fourbit_kwargs)
200
+ elif QuantLinear is not None and isinstance(target, QuantLinear):
201
+ new_module = SVDQuantLinear(target, adapter_name, config=lora_config, **kwargs)
202
+ else:
203
+ if isinstance(target_base_layer, torch.nn.Linear):
204
+ if lora_config.fan_in_fan_out:
205
+ warnings.warn(
206
+ "fan_in_fan_out is set to True but the target module is `torch.nn.Linear`. "
207
+ "Setting fan_in_fan_out to False."
208
+ )
209
+ lora_config.fan_in_fan_out = False
210
+ elif isinstance(target_base_layer, Conv1D):
211
+ if not lora_config.fan_in_fan_out:
212
+ warnings.warn(
213
+ "fan_in_fan_out is set to False but the target module is `Conv1D`. "
214
+ "Setting fan_in_fan_out to True."
215
+ )
216
+ lora_config.fan_in_fan_out = True
217
+ elif not isinstance(target_base_layer, torch.nn.Conv2d):
218
+ raise ValueError(
219
+ f"Target module {target} is not supported. "
220
+ f"Currently, only `torch.nn.Linear`, `Conv1D`, and `torch.nn.Conv2d` are supported."
221
+ )
222
+ if isinstance(target_base_layer, torch.nn.Conv2d):
223
+ new_module = SVDConv2d(target, adapter_name, config=lora_config, **kwargs)
224
+ else:
225
+ new_module = SVDLinear(target, adapter_name, config=lora_config, **kwargs)
226
+
227
+ return new_module
228
+
229
+ def forward(self, *args, **kwargs):
230
+ outputs = self.model.forward(*args, **kwargs)
231
+
232
+ if (getattr(outputs, "loss", None) is not None) and isinstance(outputs.loss, torch.Tensor):
233
+ # Calculate the orthogonal regularization
234
+ orth_reg_weight = self.peft_config[self.trainable_adapter_name].orth_reg_weight
235
+
236
+ if orth_reg_weight <= 0:
237
+ raise ValueError("orth_reg_weight should be greater than 0. ")
238
+
239
+ regu_loss = 0
240
+ num_param = 0
241
+ for n, p in self.model.named_parameters():
242
+ if ("lora_A" in n or "lora_B" in n) and self.trainable_adapter_name in n:
243
+ if p.shape == torch.Size([0]):
244
+ with gather_params_ctx(p, fwd_module=self):
245
+ para_cov = p @ p.T if "lora_A" in n else p.T @ p
246
+ else:
247
+ para_cov = p @ p.T if "lora_A" in n else p.T @ p
248
+ I = torch.eye(*para_cov.size(), out=torch.empty_like(para_cov)) # noqa: E741
249
+ I.requires_grad = False
250
+ num_param += 1
251
+ regu_loss += torch.norm(para_cov - I, p="fro")
252
+ if num_param > 0:
253
+ regu_loss = regu_loss / num_param
254
+ else:
255
+ regu_loss = 0
256
+ outputs.loss += orth_reg_weight * regu_loss
257
+ return outputs
258
+
259
+ def resize_modules_by_rank_pattern(self, rank_pattern, adapter_name):
260
+ lora_config = self.peft_config[adapter_name]
261
+ for name, rank_idx in rank_pattern.items():
262
+ if isinstance(rank_idx, list):
263
+ rank = sum(rank_idx)
264
+ elif isinstance(rank_idx, torch.Tensor):
265
+ rank_idx = rank_idx.view(-1)
266
+ rank = rank_idx.sum().item()
267
+ else:
268
+ raise TypeError("Unexpected type of rank_idx")
269
+ key = ".".join(name.split(".")[0:-2]) if adapter_name in name else ".".join(name.split(".")[0:-1])
270
+ _, target, _ = _get_submodules(self.model, key)
271
+ lora_E_weights = target.lora_E[adapter_name][rank_idx]
272
+ lora_A_weights = target.lora_A[adapter_name][rank_idx]
273
+ lora_B_weights = target.lora_B[adapter_name][:, rank_idx]
274
+ ranknum = target.ranknum[adapter_name]
275
+ target.update_layer(
276
+ adapter_name,
277
+ rank,
278
+ lora_config.lora_alpha,
279
+ config=lora_config,
280
+ )
281
+ with torch.no_grad():
282
+ if rank > 0:
283
+ target.lora_E[adapter_name].copy_(lora_E_weights)
284
+ target.lora_A[adapter_name].copy_(lora_A_weights)
285
+ target.lora_B[adapter_name].copy_(lora_B_weights)
286
+ # The scaling is exactly as the previous
287
+ target.ranknum[adapter_name].copy_(ranknum)
288
+
289
+ def resize_state_dict_by_rank_pattern(self, rank_pattern, state_dict, adapter_name):
290
+ for name, rank_idx in rank_pattern.items():
291
+ rank = sum(rank_idx)
292
+ prefix = ".".join(name.split(".")[0:-2]) if adapter_name in name else ".".join(name.split(".")[0:-1])
293
+ for layer in ["lora_E", "lora_A", "lora_B"]:
294
+ key = f"base_model.model.{prefix}.{layer}.{adapter_name}"
295
+ if layer != "lora_B":
296
+ state_dict[key] = (
297
+ state_dict[key][rank_idx] if rank != state_dict[key].shape[0] else state_dict[key]
298
+ )
299
+ else:
300
+ state_dict[key] = (
301
+ state_dict[key][:, rank_idx] if rank != state_dict[key].shape[1] else state_dict[key]
302
+ )
303
+ return state_dict
304
+
305
+ def update_and_allocate(self, global_step):
306
+ """
307
+ This method updates Adalora budget and mask.
308
+
309
+ This should be called in every training step after `loss.backward()` and before `zero_grad()`.
310
+
311
+ `tinit`, `tfinal` and `deltaT` are handled with in the method.
312
+
313
+ Args:
314
+ global_step (`int`): The current training step, it is used to calculate adalora budget.
315
+
316
+ Example:
317
+
318
+ ```python
319
+ >>> loss = model(**input).loss
320
+ >>> loss.backward()
321
+ >>> optimizer.step()
322
+ >>> model.base_model.update_and_allocate(i_step)
323
+ >>> optimizer.zero_grad()
324
+ ```
325
+ """
326
+ lora_config = self.peft_config[self.trainable_adapter_name]
327
+ # Update the importance score and allocate the budget
328
+ if global_step < lora_config.total_step - lora_config.tfinal:
329
+ _, rank_pattern = self.rankallocator.update_and_allocate(self.model, global_step)
330
+ if rank_pattern:
331
+ lora_config.rank_pattern = rank_pattern
332
+ # Finalize the budget allocation
333
+ elif global_step == lora_config.total_step - lora_config.tfinal:
334
+ _, rank_pattern = self.rankallocator.update_and_allocate(self.model, global_step, force_mask=True)
335
+ # for some reason, this freezes the trainable parameters and nothing gets updates
336
+ # self.resize_modules_by_rank_pattern(rank_pattern, self.trainable_adapter_name)
337
+ lora_config.rank_pattern = rank_pattern
338
+ self.rankallocator.reset_ipt()
339
+ # Currently using inefficient way to mask the unimportant weights using the rank pattern
340
+ # due to problem mentioned above
341
+ elif global_step > lora_config.total_step - lora_config.tfinal:
342
+ self.rankallocator.mask_using_rank_pattern(self.model, lora_config.rank_pattern)
343
+ # Pass the function and do forward propagation
344
+ else:
345
+ return
346
+
347
+ def add_weighted_adapter(self, *args, **kwargs):
348
+ """This method is not supported for AdaLoRA, use LoRA instead."""
349
+ raise TypeError(f"{self.__class__.__name__} does not support add_weighted_adapter method.")
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adamss/__init__.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from peft.utils import register_peft_method
16
+
17
+ from .config import AdamssConfig
18
+ from .layer import AdamssLayer, Linear
19
+ from .model import AdamssModel
20
+
21
+
22
+ __all__ = [
23
+ "AdamssConfig",
24
+ "AdamssLayer",
25
+ "AdamssModel",
26
+ "Linear",
27
+ ]
28
+
29
+ # Register Adamss as a PEFT method
30
+ register_peft_method(
31
+ name="adamss", config_cls=AdamssConfig, model_cls=AdamssModel, prefix="adamss_", is_mixed_compatible=False
32
+ )
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adamss/asa_callback.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """
16
+ ASA (Adaptive Subspace Allocation) Callback for HuggingFace Trainer.
17
+
18
+ This is a thin wrapper around [`AdamssModel.update_and_allocate`]. All ASA logic (importance accumulation, global top-K
19
+ masking, importance reset) lives in [`AdamssModel.update_and_allocate`] so that users with custom training loops can
20
+ call it directly without needing this callback.
21
+
22
+ Important:
23
+ To avoid circular imports between peft and transformers, this callback is NOT exported from the top-level `peft`
24
+ package. Import it directly:
25
+
26
+ ```python
27
+ from peft.tuners.adamss.asa_callback import AdamssAsaCallback
28
+ ```
29
+ """
30
+
31
+ from transformers import TrainerCallback, TrainerControl, TrainerState, TrainingArguments
32
+
33
+
34
+ class AdamssAsaCallback(TrainerCallback):
35
+ """
36
+ Trainer callback for Adaptive Subspace Allocation (ASA).
37
+
38
+ This callback delegates to [`AdamssModel.update_and_allocate`] on every optimizer step so that ASA "just works"
39
+ with HuggingFace `Trainer`.
40
+
41
+ All ASA parameters (`asa_target_subspaces`, `init_warmup`, `final_warmup`, `mask_interval`, etc.) are read from the
42
+ [`AdamssConfig`] that was used to create the model – there is nothing to configure on the callback itself.
43
+
44
+ For custom training loops **without** Trainer, call `model.base_model.update_and_allocate(global_step)` directly
45
+ instead.
46
+
47
+ Example:
48
+
49
+ ```python
50
+ from peft import AdamssConfig, get_peft_model
51
+ from peft.tuners.adamss.asa_callback import AdamssAsaCallback
52
+ from transformers import Trainer
53
+
54
+ config = AdamssConfig(
55
+ r=100,
56
+ num_subspaces=10,
57
+ subspace_rank=3,
58
+ use_asa=True,
59
+ asa_target_subspaces=5,
60
+ init_warmup=50,
61
+ final_warmup=1000,
62
+ mask_interval=100,
63
+ )
64
+ model = get_peft_model(base_model, config)
65
+
66
+ trainer = Trainer(
67
+ model=model,
68
+ callbacks=[AdamssAsaCallback()],
69
+ ...,
70
+ )
71
+ trainer.train()
72
+ ```
73
+ """
74
+
75
+ def on_optimizer_step(
76
+ self,
77
+ args: TrainingArguments,
78
+ state: TrainerState,
79
+ control: TrainerControl,
80
+ **kwargs,
81
+ ):
82
+ """Called after optimizer.step() – delegates to model.update_and_allocate()."""
83
+ model = kwargs.get("model")
84
+ if model is not None:
85
+ # Resolve to the AdamssModel (works for both PeftModel and raw base_model)
86
+ base_model = getattr(model, "base_model", model)
87
+ if hasattr(base_model, "update_and_allocate"):
88
+ base_model.update_and_allocate(state.global_step)
89
+
90
+ return super().on_optimizer_step(args=args, state=state, control=control)
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adamss/config.py ADDED
@@ -0,0 +1,340 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ from dataclasses import dataclass, field
18
+ from typing import Literal, Optional, Union
19
+
20
+ from peft.config import PeftConfig
21
+ from peft.utils import PeftType
22
+
23
+
24
+ @dataclass
25
+ class AdamssConfig(PeftConfig):
26
+ """
27
+ Configuration class for Adamss (Adaptive Multi-Subspaces) method.
28
+
29
+ AdaMSS is a parameter-efficient fine-tuning method that decomposes weight matrices using SVD and clusters the
30
+ decomposed space into multiple trainable subspaces. It learns low-rank updates within these subspaces while keeping
31
+ the original weights frozen.
32
+
33
+ Args:
34
+ r (`int`):
35
+ Total rank for SVD decomposition (denoted as R in the paper). This determines how many singular vectors are
36
+ used to represent the weight matrix before clustering. Higher values capture more information from the
37
+ original weights but require more computation and memory. Lower values provide stronger regularization.
38
+ Typical values range from 50 to 500. Default is 100.
39
+
40
+ num_subspaces (`int`):
41
+ Number of subspaces (K) to cluster the SVD-decomposed space into. Each subspace learns independent low-rank
42
+ updates. Increasing this value allows finer-grained adaptation but increases the number of trainable
43
+ parameters proportionally. When using ASA (Adaptive Subspace Allocation), this determines the initial
44
+ number of subspaces before pruning. Typical values range from 3 to 10. Default is 5.
45
+
46
+ subspace_rank (`int`):
47
+ The rank (r_i) for each trainable subspace. This controls the capacity of each subspace to learn
48
+ adaptations. Higher values increase expressiveness but also increase trainable parameters. Total trainable
49
+ parameters scale as O(num_subspaces * subspace_rank * (in_dim + out_dim) / num_subspaces). For most tasks,
50
+ values of 1-4 work well. Default is 1.
51
+
52
+ target_modules (`Optional[Union[list[str], str]]`):
53
+ The names of the modules to apply AdaMSS to. If specified, only these modules will be adapted. Can be a
54
+ list of exact module names or a regex expression. For example, `['q_proj', 'v_proj']` for attention layers,
55
+ or `'.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'` for regex matching.
56
+
57
+ modules_to_save (`Optional[list[str]]`):
58
+ List of modules apart from AdaMSS layers to be set as trainable and saved in the final checkpoint. These
59
+ modules will be fully fine-tuned (not just low-rank). Required for randomly initialized heads like
60
+ `classifier` or `score` in classification tasks.
61
+
62
+ init_weights (`Literal["orthogonal"]`):
63
+ Initialization method for AdaMSS trainable weights. Currently only "orthogonal" is supported, which uses
64
+ orthogonal initialization for the B matrices (output projection). The A matrices are initialized to zero to
65
+ ensure the model starts from the pretrained weights. Set to None to skip initialization when loading from a
66
+ checkpoint. Default is "orthogonal".
67
+
68
+ layers_to_transform (`Optional[Union[list[int], int]]`):
69
+ Specific layer indices to apply AdaMSS to. If specified, only these layers will be adapted, useful for
70
+ experimenting with which layers benefit most from adaptation. Can be a single integer or a list of
71
+ integers.
72
+
73
+ layers_pattern (`Optional[Union[list[str], str]]`):
74
+ Pattern to match layer names when `layers_to_transform` is specified. Used to extract layer indices from
75
+ module names that don't follow the common pattern.
76
+
77
+ use_asa (`bool`):
78
+ Whether to enable Adaptive Subspace Allocation (ASA). When enabled, ASA dynamically prunes less important
79
+ subspaces during training based on gradient information, reducing the effective number of parameters while
80
+ maintaining performance. Requires integration with a training callback. Default is False.
81
+
82
+ asa_target_subspaces (`int`):
83
+ Target total number of active subspaces across all layers when ASA is enabled. ASA will progressively prune
84
+ subspaces until this target is reached. Lower values result in more aggressive pruning and fewer trainable
85
+ parameters. Should be less than `num_subspaces * num_target_modules`. Typical values range from 20 to 100
86
+ depending on model size. Default is 50.
87
+
88
+ init_warmup (`int`):
89
+ Number of training steps to wait before starting ASA pruning. During warmup, all subspaces remain active to
90
+ allow importance scores to stabilize. Higher values give more time for accurate importance estimation but
91
+ delay pruning. Typical values range from 50 to 200. Default is 50.
92
+
93
+ final_warmup (`int`):
94
+ Training step at which ASA completes pruning and reaches `asa_target_subspaces` active subspaces. The
95
+ pruning is distributed between `init_warmup` and `final_warmup`. Should be set based on total training
96
+ steps; typically 1/3 to 1/2 of total training steps. Default is 1000.
97
+
98
+ mask_interval (`int`):
99
+ Number of training steps between ASA mask updates. Lower values allow more frequent adaptation but increase
100
+ overhead. Higher values provide more stable importance estimates between updates. Typical values range from
101
+ 50 to 200. Default is 100.
102
+
103
+ asa_importance_beta (`float`):
104
+ Exponential moving average (EMA) coefficient for smoothing subspace importance scores. Higher values
105
+ (closer to 1.0) give more weight to historical importance, providing stability. Lower values make
106
+ importance more responsive to recent gradients. Typical values range from 0.8 to 0.95. Default is 0.85.
107
+
108
+ asa_uncertainty_beta (`float`):
109
+ EMA coefficient for smoothing importance uncertainty estimates. Controls how quickly uncertainty adapts to
110
+ gradient variance. Similar to asa_importance_beta, higher values provide more stable estimates. Typical
111
+ values range from 0.8 to 0.95. Default is 0.85.
112
+
113
+ asa_schedule_exponent (`float`):
114
+ Schedule exponent controlling the decay rate from total subspaces to `asa_target_subspaces` during ASA
115
+ warmup. Higher values result in faster initial pruning (more aggressive early reduction), while lower
116
+ values provide a more gradual, linear-like decay. The formula is: current_active_subspaces =
117
+ asa_target_subspaces + (asa_total_subspaces - asa_target_subspaces) * (progress ** exponent). Typical
118
+ values range from 1.0 (linear) to 5.0 (aggressive). Default is 3.0.
119
+
120
+ use_dynamic_rank (`bool`):
121
+ Whether to dynamically determine subspace ranks based on singular value magnitudes. When True, each
122
+ subspace's rank is determined by counting singular values above a threshold, allowing different subspaces
123
+ to have different effective ranks. When False, all subspaces use the fixed `subspace_rank`. Default is
124
+ False.
125
+
126
+ svd_threshold (`float`):
127
+ Threshold ratio for dynamic rank selection, only used when `use_dynamic_rank=True`. A singular value is
128
+ considered significant if it exceeds `threshold * max_singular_value`. Higher values result in lower
129
+ effective ranks (more aggressive truncation). Typical values range from 0.05 to 0.2. Default is 0.1 (10% of
130
+ max).
131
+ """
132
+
133
+ r: int = field(
134
+ default=100,
135
+ metadata={
136
+ "help": (
137
+ "Total rank for SVD decomposition (R in the paper). Higher values capture more "
138
+ "information but require more computation. The actual rank is clamped to "
139
+ "min(r, in_features, out_features). Typical values: 50-500. Default: 100."
140
+ )
141
+ },
142
+ )
143
+ num_subspaces: int = field(
144
+ default=5,
145
+ metadata={
146
+ "help": (
147
+ "Number of subspaces (K) to cluster the SVD space into. Each subspace learns "
148
+ "independent low-rank updates. Increasing this allows finer-grained adaptation "
149
+ "but increases trainable parameters. Typical values: 3-10. Default: 5."
150
+ )
151
+ },
152
+ )
153
+ subspace_rank: int = field(
154
+ default=1,
155
+ metadata={
156
+ "help": (
157
+ "Rank (r_i) for each trainable subspace. Higher values increase expressiveness "
158
+ "but also increase parameters. For most tasks, values of 1-4 work well. Default: 1."
159
+ )
160
+ },
161
+ )
162
+ target_modules: Optional[Union[list[str], str]] = field(
163
+ default=None,
164
+ metadata={
165
+ "help": (
166
+ "List of module names or regex expression of the module names to replace with AdaMSS. "
167
+ "For example, ['q_proj', 'v_proj'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'. "
168
+ "For Vision Transformers, typically ['query', 'value']."
169
+ )
170
+ },
171
+ )
172
+ init_weights: Optional[Literal["orthogonal"]] = field(
173
+ default="orthogonal",
174
+ metadata={
175
+ "help": (
176
+ "Initialization method for AdaMSS trainable weights. Currently only 'orthogonal' "
177
+ "is supported, which uses orthogonal initialization for B matrices. A matrices "
178
+ "are initialized to zero to start from pretrained weights. Set to None to skip "
179
+ "initialization when loading from a checkpoint. Default: 'orthogonal'."
180
+ )
181
+ },
182
+ )
183
+ modules_to_save: Optional[list[str]] = field(
184
+ default=None,
185
+ metadata={
186
+ "help": (
187
+ "List of modules apart from AdaMSS layers to be set as trainable and saved in the final checkpoint. "
188
+ "For example, in Sequence Classification or Token Classification tasks, "
189
+ "the final layer `classifier/score` are randomly initialized and as such need to be trainable and saved."
190
+ )
191
+ },
192
+ )
193
+ layers_to_transform: Optional[Union[list[int], int]] = field(
194
+ default=None,
195
+ metadata={
196
+ "help": (
197
+ "Specific layer indices to apply AdaMSS to. If specified, only these layers will "
198
+ "be adapted, useful for experimenting with which layers benefit most. Can be a "
199
+ "single integer or a list of integers. Default: None (adapt all matching layers)."
200
+ )
201
+ },
202
+ )
203
+ layers_pattern: Optional[Union[list[str], str]] = field(
204
+ default=None,
205
+ metadata={
206
+ "help": (
207
+ "Pattern to match layer names when `layers_to_transform` is specified. Used to "
208
+ "extract layer indices from module names that don't follow common patterns."
209
+ )
210
+ },
211
+ )
212
+ # ASA (Adaptive Subspace Allocation) parameters
213
+ use_asa: bool = field(
214
+ default=False,
215
+ metadata={
216
+ "help": (
217
+ "Whether to enable Adaptive Subspace Allocation (ASA). When enabled, ASA dynamically "
218
+ "prunes less important subspaces during training based on gradient information, "
219
+ "reducing parameters while maintaining performance. Requires a training callback. "
220
+ "Default: False."
221
+ )
222
+ },
223
+ )
224
+ asa_target_subspaces: int = field(
225
+ default=50,
226
+ metadata={
227
+ "help": (
228
+ "Target total number of active subspaces across all layers when ASA is enabled. "
229
+ "ASA progressively prunes subspaces until this target is reached. Lower values "
230
+ "result in more aggressive pruning. Typical values: 20-100. Default: 50."
231
+ )
232
+ },
233
+ )
234
+ init_warmup: int = field(
235
+ default=50,
236
+ metadata={
237
+ "help": (
238
+ "Training steps to wait before starting ASA pruning. During warmup, all subspaces "
239
+ "remain active to allow importance scores to stabilize. Higher values give more "
240
+ "time for accurate estimation. Typical values: 50-200. Default: 50."
241
+ )
242
+ },
243
+ )
244
+ final_warmup: int = field(
245
+ default=1000,
246
+ metadata={
247
+ "help": (
248
+ "Training step at which ASA completes pruning and reaches asa_target_subspaces. "
249
+ "Should be set based on total training steps; typically 1/3 to 1/2 of total steps. "
250
+ "Default: 1000."
251
+ )
252
+ },
253
+ )
254
+ mask_interval: int = field(
255
+ default=100,
256
+ metadata={
257
+ "help": (
258
+ "Training steps between ASA mask updates. Lower values allow more frequent "
259
+ "adaptation but increase overhead. Higher values provide more stable estimates. "
260
+ "Typical values: 50-200. Default: 100."
261
+ )
262
+ },
263
+ )
264
+ asa_importance_beta: float = field(
265
+ default=0.85,
266
+ metadata={
267
+ "help": (
268
+ "EMA coefficient for smoothing subspace importance scores during ASA. Higher "
269
+ "values (closer to 1.0) give more weight to historical importance, providing "
270
+ "stability. Lower values make importance more responsive to recent gradients. "
271
+ "Typical values: 0.8-0.95. Default: 0.85."
272
+ )
273
+ },
274
+ )
275
+ asa_uncertainty_beta: float = field(
276
+ default=0.85,
277
+ metadata={
278
+ "help": (
279
+ "EMA coefficient for smoothing importance uncertainty estimates during ASA. "
280
+ "Controls how quickly uncertainty adapts to gradient variance. Higher values "
281
+ "provide more stable estimates. Typical values: 0.8-0.95. Default: 0.85."
282
+ )
283
+ },
284
+ )
285
+ asa_schedule_exponent: float = field(
286
+ default=3.0,
287
+ metadata={
288
+ "help": (
289
+ "Schedule exponent controlling the decay rate from total subspaces to "
290
+ "asa_target_subspaces. Higher values result in faster initial pruning (aggressive "
291
+ "early reduction), lower values provide gradual linear-like decay. Formula: "
292
+ "current_active_subspaces = asa_target_subspaces + (total - target) * (progress ** exponent). "
293
+ "Typical values: 1.0 (linear) to 5.0 (aggressive). Default: 3.0."
294
+ )
295
+ },
296
+ )
297
+ # Dynamic rank selection parameters
298
+ use_dynamic_rank: bool = field(
299
+ default=False,
300
+ metadata={
301
+ "help": (
302
+ "Whether to dynamically determine subspace ranks based on singular value magnitudes. "
303
+ "When True, each subspace's rank is determined by counting singular values above "
304
+ "a threshold, allowing different subspaces to have different effective ranks. "
305
+ "When False (default), all subspaces use the fixed subspace_rank. Default: False."
306
+ )
307
+ },
308
+ )
309
+ svd_threshold: float = field(
310
+ default=0.1,
311
+ metadata={
312
+ "help": (
313
+ "Threshold ratio for dynamic rank selection (only used when use_dynamic_rank=True). "
314
+ "A singular value is significant if it exceeds threshold * max_singular_value. "
315
+ "Higher values result in lower effective ranks (more aggressive truncation). "
316
+ "Typical values: 0.05-0.2. Default: 0.1 (10% of max)."
317
+ )
318
+ },
319
+ )
320
+
321
+ def __post_init__(self):
322
+ self.peft_type = PeftType.ADAMSS
323
+ self.target_modules = (
324
+ set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules
325
+ )
326
+ super().__post_init__()
327
+
328
+ # Normalize init_weights: convert False to None for backward compatibility
329
+ if self.init_weights is False:
330
+ self.init_weights = None
331
+
332
+ # Validate initialization method
333
+ if self.init_weights not in ["orthogonal", None]:
334
+ raise ValueError(f"init_weights must be 'orthogonal' or None, got {self.init_weights}")
335
+
336
+ # Early check for scikit-learn availability
337
+ try:
338
+ import sklearn # noqa: F401
339
+ except ImportError:
340
+ raise ImportError("scikit-learn is required for AdaMSS. Please install it with: pip install scikit-learn")
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adamss/layer.py ADDED
@@ -0,0 +1,668 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ import warnings
18
+ from typing import Optional
19
+
20
+ import torch
21
+ import torch.nn.functional as F
22
+ from torch import nn
23
+
24
+ from peft.tuners._buffer_dict import BufferDict
25
+ from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge
26
+
27
+ from .config import AdamssConfig
28
+ from .utils import clustering_Z, get_trainable_subspaces, seg_locations, slice_pca
29
+
30
+
31
+ class AdamssLayer(BaseTunerLayer):
32
+ """
33
+ Base Adamss layer that stores adapter-specific information.
34
+ """
35
+
36
+ # All names of layers that may contain adapter weights (trainable or frozen)
37
+ # Use ModuleDict for proper state_dict key format that PEFT's save/load can handle
38
+ # Only include trainable parameter containers here (not buffers)
39
+ # adamss_newB is a buffer (frozen), not a trainable parameter
40
+ adapter_layer_names = ("adamss_A", "adamss_B")
41
+ # other_param_names specifies additional non-tensor metadata
42
+ other_param_names = (
43
+ "num_subspaces",
44
+ "train_subspace_index",
45
+ "seg_result",
46
+ "scatter_index",
47
+ "exp_avg_ipt_A",
48
+ "exp_avg_ipt_B",
49
+ "exp_avg_unc_A",
50
+ "exp_avg_unc_B",
51
+ )
52
+
53
+ def __init__(self, base_layer: nn.Module, **kwargs) -> None:
54
+ self.base_layer = base_layer
55
+ # Adapter-specific attributes
56
+ # Use ModuleDict containing ParameterList for proper state_dict keys (e.g., adamss_A.default.0)
57
+ self.adamss_A = nn.ModuleDict({}) # Will contain ParameterList per adapter
58
+ self.adamss_B = nn.ModuleDict({}) # Will contain ParameterList per adapter
59
+ # Use BufferDict for frozen projection matrix (keys like adamss_newB.default)
60
+ self.adamss_newB = BufferDict(persistent=True)
61
+ self.num_subspaces = {}
62
+ self.train_subspace_index = {}
63
+ self.seg_result = {}
64
+ self.scatter_index = {}
65
+ # ASA importance tracking (per-adapter lists indexed by subspace)
66
+ self.exp_avg_ipt_A = {}
67
+ self.exp_avg_ipt_B = {}
68
+ self.exp_avg_unc_A = {}
69
+ self.exp_avg_unc_B = {}
70
+ self._disable_adapters = False
71
+ self.merged_adapters = []
72
+
73
+ def reset_importance(self, adapter_name: str) -> None:
74
+ """
75
+ Clear stored importance stats for an adapter.
76
+
77
+ Called after each masking interval to restart EMA accumulation for the next importance scoring window. Without
78
+ the reset the scores from early training steps would dominate later masking decisions.
79
+ """
80
+ if adapter_name in self.exp_avg_ipt_A:
81
+ n = len(self.exp_avg_ipt_A[adapter_name])
82
+ self.exp_avg_ipt_A[adapter_name] = [None] * n
83
+ self.exp_avg_ipt_B[adapter_name] = [None] * n
84
+ self.exp_avg_unc_A[adapter_name] = [None] * n
85
+ self.exp_avg_unc_B[adapter_name] = [None] * n
86
+
87
+ def update_importance(
88
+ self, adapter_name: str, importance_beta: float = 0.85, uncertainty_beta: float = 0.85
89
+ ) -> None:
90
+ """
91
+ Update importance scores using current gradients.
92
+
93
+ Called by [`AdamssModel.update_and_allocate`] (which is in turn called by [`AdamssAsaCallback`] when using
94
+ HuggingFace `Trainer`).
95
+
96
+ Args:
97
+ adapter_name: Name of the adapter to update importance for.
98
+ importance_beta: EMA coefficient for importance averaging (0.8-0.95 typical).
99
+ uncertainty_beta: EMA coefficient for uncertainty averaging (0.8-0.95 typical).
100
+ """
101
+ if adapter_name not in self.exp_avg_ipt_A:
102
+ return
103
+ if adapter_name not in self.adamss_A:
104
+ return
105
+
106
+ param_list_A = self.adamss_A[adapter_name]
107
+ param_list_B = self.adamss_B[adapter_name]
108
+
109
+ ipt_A = self.exp_avg_ipt_A[adapter_name]
110
+ ipt_B = self.exp_avg_ipt_B[adapter_name]
111
+ unc_A = self.exp_avg_unc_A[adapter_name]
112
+ unc_B = self.exp_avg_unc_B[adapter_name]
113
+
114
+ for i in range(self.num_subspaces[adapter_name]):
115
+ for param_list, ipt_list, unc_list in [
116
+ (param_list_A, ipt_A, unc_A),
117
+ (param_list_B, ipt_B, unc_B),
118
+ ]:
119
+ param = param_list[i]
120
+ if param.grad is not None:
121
+ if ipt_list[i] is None:
122
+ ipt_list[i] = torch.zeros_like(param, requires_grad=False)
123
+ unc_list[i] = torch.zeros_like(param, requires_grad=False)
124
+
125
+ # Calculate importance: |w * g|
126
+ ipt = (param * param.grad).abs().detach()
127
+
128
+ # Update uncertainty BEFORE updating importance (matches adamss_pkg)
129
+ diff = (ipt - ipt_list[i]).abs()
130
+ unc_list[i].mul_(uncertainty_beta).add_(diff, alpha=1 - uncertainty_beta)
131
+
132
+ # Then update importance
133
+ ipt_list[i].mul_(importance_beta).add_(ipt, alpha=1 - importance_beta)
134
+
135
+ def update_layer(
136
+ self,
137
+ adapter_name: str,
138
+ r: int,
139
+ config: AdamssConfig,
140
+ **kwargs,
141
+ ) -> None:
142
+ """
143
+ Update layer with Adamss adapter.
144
+
145
+ This method initializes the Adamss decomposition for the weight matrix using SVD, clustering, and QR
146
+ initialization.
147
+ """
148
+ num_subspaces = config.num_subspaces
149
+ subspace_rank = config.subspace_rank
150
+ init_weights = config.init_weights
151
+ use_asa = config.use_asa
152
+ inference_mode = config.inference_mode
153
+ use_dynamic_rank = config.use_dynamic_rank
154
+ svd_threshold = config.svd_threshold
155
+
156
+ # Get the base weight info
157
+ weight = self.get_base_layer().weight
158
+ bias = self.get_base_layer().bias
159
+ device = weight.device
160
+ dtype = weight.dtype
161
+ _, in_features = weight.shape
162
+
163
+ # Adjust in_features for bias column
164
+ if bias is not None:
165
+ in_features += 1
166
+
167
+ # Prepare weight tensor (add bias as extra column if present)
168
+ if bias is not None:
169
+ weight_with_bias = torch.cat((weight, bias.unsqueeze(1)), dim=1)
170
+ else:
171
+ weight_with_bias = weight
172
+
173
+ # Reshape to 4D tensor for slice_pca: (1, 1, out_features, in_features)
174
+ weight_tensor = weight_with_bias.unsqueeze(0).unsqueeze(0).to(torch.float32).to(device)
175
+
176
+ # Perform SVD decomposition with diagnostics in case of failure
177
+ try:
178
+ res = slice_pca(weight_tensor, r, device, torch.float32)
179
+ except Exception as e:
180
+ raise RuntimeError(
181
+ f"slice_pca raised an exception for layer {adapter_name} (shape={tuple(weight_tensor.shape)}, dtype={weight_tensor.dtype}, device={device}): {e}"
182
+ ) from e
183
+
184
+ VVT, UU = res
185
+
186
+ # Cluster the column space
187
+ cluster_idx, effective_num_subspaces = clustering_Z(UU[0, 0, :, :], num_subspaces, 10)
188
+
189
+ # Get segment locations
190
+ seg_result = seg_locations(cluster_idx)
191
+
192
+ # Get trainable subspace indices
193
+ train_subspace_index = get_trainable_subspaces(effective_num_subspaces)
194
+
195
+ # Store metadata
196
+ self.num_subspaces[adapter_name] = effective_num_subspaces
197
+ self.train_subspace_index[adapter_name] = train_subspace_index
198
+ self.seg_result[adapter_name] = seg_result
199
+
200
+ # Store projection matrix in BufferDict (frozen, device-aware)
201
+ self.adamss_newB[adapter_name] = VVT[0, 0, :, :].detach().to(dtype)
202
+
203
+ # Use user-specified subspace_rank
204
+ rank_per_subspace = subspace_rank
205
+
206
+ # Initialize trainable subspace parameters
207
+ # Collect parameters in lists, then create ParameterList for proper state_dict keys
208
+ A_params = []
209
+ B_params = []
210
+
211
+ for i in range(self.num_subspaces[adapter_name]):
212
+ subspace_idx = train_subspace_index[i]
213
+ seg_indices = seg_result[subspace_idx]
214
+
215
+ # Extract subspace data: use ALL r columns from SVD (not just r/K)
216
+ # This matches adamss_pkg where A matrices have shape (rank_i, r)
217
+ subspace_data = UU[0, 0, seg_indices, :r]
218
+ # subspace_data shape: (len(seg_indices), r)
219
+
220
+ # Determine actual rank based on configuration
221
+ if use_dynamic_rank:
222
+ # Compute Gram matrix Z = subspace_data @ subspace_data.T
223
+ Z_row = subspace_data @ subspace_data.T # (len(seg_indices), len(seg_indices))
224
+
225
+ # Compute SVD to get row space decomposition
226
+ _U_row, S_row, _V_row = torch.svd_lowrank(Z_row, q=min(Z_row.shape), niter=2)
227
+
228
+ # Dynamic rank selection using SVD threshold
229
+ # Dynamically determine actual rank using configurable threshold
230
+ # Following adamss_pkg: num_ii_jj = min((S > threshold * S[0]).sum().item(), args.adamss_ri)
231
+ threshold_mask = S_row > svd_threshold * S_row[0]
232
+ actual_rank = min(threshold_mask.sum().item(), subspace_rank, len(S_row))
233
+
234
+ # Handle edge case: ensure at least rank 1
235
+ if actual_rank == 0:
236
+ actual_rank = 1
237
+
238
+ else:
239
+ # Fixed rank: match adamss_pkg behavior exactly
240
+ # adamss_pkg uses: num_ii_jj = min(len(seg_result[indx]), args.adamss_ri)
241
+ actual_rank = min(len(seg_indices), subspace_rank)
242
+
243
+ # Ensure at least rank 1
244
+ if actual_rank == 0:
245
+ actual_rank = 1
246
+
247
+ # Initialize A using QR decomposition to match adamss_pkg exactly
248
+ # adamss_pkg: Q, R = torch.linalg.qr((UU[seg_result[indx],:]).T @ A[i], mode='reduced')
249
+ # where A[i] is U from SVD of subspace Gram matrix
250
+
251
+ # First, compute Gram matrix for this subspace
252
+ Z_subspace = subspace_data @ subspace_data.T # (len(seg_indices), len(seg_indices))
253
+
254
+ # SVD of Gram matrix to get A_intermediate
255
+ U_gram, _S_gram, _ = torch.svd_lowrank(Z_subspace, q=min(Z_subspace.shape[0], actual_rank), niter=2)
256
+ A_intermediate = U_gram[:, :actual_rank] # (len(seg_indices), actual_rank)
257
+
258
+ # Now apply QR decomposition: (UU[seg_indices, :r]).T @ A_intermediate
259
+ # UU[0, 0, seg_indices, :r] is subspace_data with shape (len(seg_indices), r)
260
+ matrix_for_qr = subspace_data.T @ A_intermediate # (r, actual_rank)
261
+ Q, _R = torch.linalg.qr(matrix_for_qr, mode="reduced")
262
+
263
+ # A_init is Q.T to match adamss_pkg
264
+ A_init = Q.T.contiguous() # (actual_rank, r)
265
+
266
+ # Initialize B matrix
267
+ # When init_weights='orthogonal', use zeros for identity operation (standard training init)
268
+ # When init_weights=None/False, use random values so adapter produces non-zero effect
269
+ if init_weights == "orthogonal":
270
+ # Zero initialization - adapter produces identity at start
271
+ # Note: A parameters may not update in step 1 since ∂Loss/∂A ∝ B and B=0
272
+ # But after step 1, B becomes non-zero and A will get gradients in step 2+
273
+ B_init = torch.zeros(len(seg_indices), actual_rank, dtype=dtype, device=device)
274
+ else:
275
+ # Random initialization for testing - produces non-zero adapter output
276
+ B_init = torch.randn(len(seg_indices), actual_rank, dtype=dtype, device=device) * 0.01
277
+
278
+ # Collect A and B parameters
279
+ A_params.append(nn.Parameter(A_init.to(dtype)))
280
+ B_params.append(nn.Parameter(B_init.to(dtype)))
281
+
282
+ # Create ParameterLists and store in ModuleDict
283
+ # This creates state_dict keys like 'adamss_A.default.0', 'adamss_A.default.1', etc.
284
+ self.adamss_A[adapter_name] = nn.ParameterList(A_params)
285
+ self.adamss_B[adapter_name] = nn.ParameterList(B_params)
286
+
287
+ # Initialize ASA tracking if enabled
288
+ if use_asa:
289
+ n = effective_num_subspaces
290
+ self.exp_avg_ipt_A[adapter_name] = [None] * n
291
+ self.exp_avg_ipt_B[adapter_name] = [None] * n
292
+ self.exp_avg_unc_A[adapter_name] = [None] * n
293
+ self.exp_avg_unc_B[adapter_name] = [None] * n
294
+
295
+ # Hooks are not used; importance is updated explicitly via update_importance
296
+ # to match adamss_pkg behavior (using accumulated gradients).
297
+
298
+ # Compute scatter_index for forward pass
299
+ self.scatter_index[adapter_name] = torch.cat(
300
+ [
301
+ self.seg_result[adapter_name][self.train_subspace_index[adapter_name][i]]
302
+ for i in range(self.num_subspaces[adapter_name])
303
+ ],
304
+ dim=0,
305
+ ).long()
306
+
307
+ # Move adapter to device of base layer (important for low_cpu_mem_usage support)
308
+ self._move_adapter_to_device_of_base_layer(adapter_name)
309
+
310
+ # Set requires_grad via parent class set_adapter (works with ParameterList)
311
+ self.set_adapter(self.active_adapters, inference_mode=inference_mode)
312
+
313
+
314
+ class Linear(nn.Module, AdamssLayer):
315
+ """
316
+ Adamss-adapted Linear layer.
317
+ """
318
+
319
+ def __init__(
320
+ self,
321
+ base_layer: nn.Module,
322
+ adapter_name: str,
323
+ r: int,
324
+ config: AdamssConfig,
325
+ **kwargs,
326
+ ) -> None:
327
+ super().__init__()
328
+ AdamssLayer.__init__(self, base_layer, **kwargs)
329
+
330
+ # Set in_features and out_features from base layer (required for PEFT compatibility)
331
+ self.in_features = base_layer.in_features
332
+ self.out_features = base_layer.out_features
333
+
334
+ # Initialize the adapter
335
+ self.update_layer(
336
+ adapter_name,
337
+ r,
338
+ config=config,
339
+ **kwargs,
340
+ )
341
+ self._active_adapter = adapter_name
342
+ self.dtype = base_layer.weight.dtype
343
+
344
+ def _load_from_state_dict(
345
+ self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
346
+ ):
347
+ """Handle shape mismatches that arise when loading checkpoints.
348
+
349
+ AdaMSS B parameter shapes depend on KMeans clustering of the weight matrix. KMeans uses a fixed `random_state`
350
+ so results should be deterministic, but this override acts as a safety net in case sklearn changes clustering
351
+ behaviour across versions. It detects shape mismatches and replaces placeholder parameters with
352
+ correctly-shaped tensors before the default `load_state_dict` logic runs.
353
+ """
354
+ for key, value in state_dict.items():
355
+ if not key.startswith(prefix):
356
+ continue
357
+ local_key = key[len(prefix) :]
358
+ parts = local_key.split(".")
359
+ try:
360
+ # Use get_submodule for the parent path
361
+ parent_path = ".".join(parts[:-1])
362
+ target = self.get_submodule(parent_path) if parent_path else self
363
+ last = parts[-1]
364
+ if last.isdigit():
365
+ current = target[int(last)]
366
+ else:
367
+ current = getattr(target, last)
368
+ except (AttributeError, IndexError, KeyError):
369
+ continue
370
+
371
+ if isinstance(current, (torch.Tensor, nn.Parameter)) and current.shape != value.shape:
372
+ new_param = nn.Parameter(torch.empty_like(value), requires_grad=current.requires_grad)
373
+ if last.isdigit():
374
+ target[int(last)] = new_param
375
+ else:
376
+ setattr(target, last, new_param)
377
+
378
+ super()._load_from_state_dict(
379
+ state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
380
+ )
381
+
382
+ def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor:
383
+ """
384
+ Forward pass with Adamss adaptation.
385
+ """
386
+ previous_dtype = x.dtype
387
+
388
+ if self._disable_adapters:
389
+ if self.merged:
390
+ self.unmerge()
391
+ result = self.base_layer(x, *args, **kwargs)
392
+ elif self.merged:
393
+ # Adapter weights are already merged into base_layer.weight,
394
+ # so just call base_layer directly (no adapter delta needed).
395
+ result = self.base_layer(x, *args, **kwargs)
396
+ else:
397
+ # Cast input to layer dtype
398
+ x = x.to(self.dtype)
399
+
400
+ # Add bias column only when the base layer has a bias
401
+ # (update_layer concatenates bias into newB only when bias is not None)
402
+ if self.get_base_layer().bias is not None:
403
+ if x.dim() == 2:
404
+ ones = torch.ones(x.shape[0], 1, device=x.device, dtype=self.dtype)
405
+ else: # x.dim() == 3 or more
406
+ ones = torch.ones(*x.shape[:-1], 1, device=x.device, dtype=self.dtype)
407
+ newx = torch.cat((x, ones), dim=-1)
408
+ else:
409
+ newx = x
410
+
411
+ # Base output from the frozen original weight
412
+ result = self.base_layer(x, *args, **kwargs)
413
+
414
+ # Iterate over all active adapters and add their deltas
415
+ for active_adapter in self.active_adapters:
416
+ if active_adapter not in self.adamss_A:
417
+ continue
418
+
419
+ # Project input into low-rank space
420
+ projected = F.linear(newx, self.adamss_newB[active_adapter].to(self.dtype)) # (..., r)
421
+
422
+ # Apply A and B transformations per subspace
423
+ # TODO: if all subspaces have equal output dimensions, this loop could
424
+ # be replaced with a batched matmul/einsum for better performance.
425
+ # Currently B_i shapes vary per subspace (clustering-dependent), so we loop.
426
+ subspace_chunks = []
427
+ for i in range(self.num_subspaces[active_adapter]):
428
+ A_i = self.adamss_A[active_adapter][i].to(self.dtype) # (ri, r)
429
+ B_i = self.adamss_B[active_adapter][i].to(self.dtype) # (seg_len_i, ri)
430
+ subspace_out = F.linear(projected, A_i) # (..., ri)
431
+ subspace_out = F.linear(subspace_out, B_i) # (..., seg_len_i)
432
+ subspace_chunks.append(subspace_out)
433
+
434
+ # Concatenate subspace results and scatter to output dimension order
435
+ adapter_delta = torch.cat(subspace_chunks, dim=-1)
436
+ scatter_index_tensor = self.scatter_index[active_adapter].to(adapter_delta.device)
437
+
438
+ if adapter_delta.dim() == 2:
439
+ index = scatter_index_tensor.unsqueeze(0).expand(adapter_delta.shape[0], -1)
440
+ adapter_delta = torch.zeros(
441
+ adapter_delta.shape[0],
442
+ result.shape[-1],
443
+ device=adapter_delta.device,
444
+ dtype=adapter_delta.dtype,
445
+ ).scatter(1, index, adapter_delta)
446
+ else:
447
+ index = scatter_index_tensor.unsqueeze(0).unsqueeze(0).expand(*adapter_delta.shape[:-1], -1)
448
+ adapter_delta = torch.zeros(
449
+ *adapter_delta.shape[:-1],
450
+ result.shape[-1],
451
+ device=adapter_delta.device,
452
+ dtype=adapter_delta.dtype,
453
+ ).scatter(-1, index, adapter_delta)
454
+
455
+ result = result + adapter_delta
456
+
457
+ # Cast back to original dtype
458
+ return result.to(previous_dtype)
459
+
460
+ def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None:
461
+ """
462
+ Merge the active adapter weights into the base weights.
463
+
464
+ Args:
465
+ safe_merge (`bool`, *optional*):
466
+ If True, the merge operation will be performed in a copy of the original weights and check for NaNs
467
+ before merging the weights. Defaults to `False`.
468
+ adapter_names (`list[str]`, *optional*):
469
+ The list of adapter names that should be merged. If None, all active adapters will be merged.
470
+ """
471
+ adapter_names = check_adapters_to_merge(self, adapter_names)
472
+ if not adapter_names:
473
+ # no adapter to merge
474
+ return
475
+
476
+ for active_adapter in adapter_names:
477
+ if active_adapter in self.adamss_A:
478
+ base_layer = self.get_base_layer()
479
+ if safe_merge:
480
+ # Note that safe_merge will be slower than the normal merge
481
+ # because of the copy operation.
482
+ orig_weight = base_layer.weight.data.clone()
483
+ orig_dtype = orig_weight.dtype
484
+ delta_weight = self.get_delta_weight(active_adapter)
485
+ orig_weight += delta_weight.to(orig_dtype)
486
+
487
+ if not torch.isfinite(orig_weight).all():
488
+ raise ValueError(
489
+ f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken"
490
+ )
491
+
492
+ base_layer.weight.data = orig_weight
493
+
494
+ # Also update bias if present
495
+ if base_layer.bias is not None:
496
+ orig_bias = base_layer.bias.data.clone()
497
+ delta_bias = self.get_delta_bias(active_adapter)
498
+ orig_bias += delta_bias.to(orig_dtype)
499
+ if not torch.isfinite(orig_bias).all():
500
+ raise ValueError(
501
+ f"NaNs detected in the merged bias. The adapter {active_adapter} seems to be broken"
502
+ )
503
+ base_layer.bias.data = orig_bias
504
+ else:
505
+ delta_weight = self.get_delta_weight(active_adapter)
506
+ base_layer.weight.data += delta_weight
507
+
508
+ # Also update bias if present
509
+ if base_layer.bias is not None:
510
+ delta_bias = self.get_delta_bias(active_adapter)
511
+ base_layer.bias.data += delta_bias
512
+
513
+ self.merged_adapters.append(active_adapter)
514
+
515
+ def unmerge(self) -> None:
516
+ """
517
+ This method unmerges all merged adapter layers from the base weights.
518
+ """
519
+ if not self.merged:
520
+ warnings.warn("Already unmerged. Nothing to do.")
521
+ return
522
+
523
+ while len(self.merged_adapters) > 0:
524
+ active_adapter = self.merged_adapters.pop()
525
+ if active_adapter in self.adamss_A:
526
+ base_layer = self.get_base_layer()
527
+ weight = base_layer.weight
528
+ orig_dtype = weight.dtype
529
+ delta_weight = self.get_delta_weight(active_adapter)
530
+ weight.data -= delta_weight.to(orig_dtype)
531
+
532
+ # Also update bias if present
533
+ if base_layer.bias is not None:
534
+ delta_bias = self.get_delta_bias(active_adapter)
535
+ base_layer.bias.data -= delta_bias.to(orig_dtype)
536
+
537
+ def get_delta_weight(self, adapter_name: str) -> torch.Tensor:
538
+ """
539
+ Compute the delta weight for the given adapter.
540
+
541
+ For AdaMSS, the forward computes:
542
+ result = newx @ resW.T + scatter(newx @ newB.T @ A.T @ B.T)
543
+
544
+ Since resW = original_weight_with_bias, the delta is just the adapter path:
545
+ delta = scatter(B @ A @ newB)
546
+
547
+ We extract the weight portion (excluding bias column) as the delta to add to the base layer's weight.
548
+
549
+ Args:
550
+ adapter_name (str): The name of the adapter for which the delta weight should be computed.
551
+ """
552
+ device = self.get_base_layer().weight.device
553
+ dtype = self.get_base_layer().weight.dtype
554
+ base_weight = self.get_base_layer().weight
555
+
556
+ # Get buffers
557
+ newB = self.adamss_newB[adapter_name] # Shape: (r, in_features + 1)
558
+
559
+ # Get parameter lists
560
+ param_list_A = self.adamss_A[adapter_name]
561
+ param_list_B = self.adamss_B[adapter_name]
562
+
563
+ # In case users wants to merge the adapter weights that are in
564
+ # (b)float16 while being on CPU, we need to cast the weights to float32
565
+ cast_to_fp32 = device.type == "cpu" and dtype in (torch.float16, torch.bfloat16)
566
+ compute_dtype = torch.float32 if cast_to_fp32 else dtype
567
+
568
+ newB = newB.to(device).to(compute_dtype)
569
+
570
+ # Compute the adapter contribution (scattered B @ A @ newB)
571
+ # delta_weight has shape (out_features, in_features + 1)
572
+ out_features = base_weight.shape[0]
573
+ in_features_plus_1 = newB.shape[1]
574
+
575
+ # Initialize delta weight for the adapter path only
576
+ delta_weight = torch.zeros(out_features, in_features_plus_1, device=device, dtype=compute_dtype)
577
+
578
+ # Compute the transformation for each subspace
579
+ # For subspace i: contribution = B_i @ A_i @ newB
580
+ # where A_i has shape (rank_i, r), B_i has shape (seg_len_i, rank_i)
581
+ chunks = []
582
+ for i in range(self.num_subspaces[adapter_name]):
583
+ A_i = param_list_A[i].to(device).to(compute_dtype) # Shape: (rank_i, r)
584
+ B_i = param_list_B[i].to(device).to(compute_dtype) # Shape: (seg_len_i, rank_i)
585
+
586
+ # B_i @ A_i @ newB gives shape (seg_len_i, in_features+1)
587
+ chunk = B_i @ A_i @ newB
588
+ chunks.append(chunk)
589
+
590
+ # Concatenate chunks and scatter to correct positions
591
+ if chunks:
592
+ combined = torch.cat(chunks, dim=0) # Shape: (total_seg_len, in_features+1)
593
+ # Use scatter_index for assignment
594
+ scatter_idx = self.scatter_index[adapter_name].to(delta_weight.device)
595
+ delta_weight[scatter_idx] = combined
596
+
597
+ # Extract just the weight portion
598
+ if self.get_base_layer().bias is not None:
599
+ # delta_weight[:, :-1] is the weight delta (exclude bias column)
600
+ output_tensor = delta_weight[:, :-1] # Shape: (out_features, in_features)
601
+ else:
602
+ # No bias column to strip
603
+ output_tensor = delta_weight # Shape: (out_features, in_features)
604
+
605
+ if cast_to_fp32:
606
+ output_tensor = output_tensor.to(dtype=dtype)
607
+
608
+ return output_tensor
609
+
610
+ def get_delta_bias(self, adapter_name: str) -> torch.Tensor:
611
+ """
612
+ Compute the bias delta for the given adapter.
613
+
614
+ This is the last column of the adapter path contribution (B @ A @ newB).
615
+
616
+ Args:
617
+ adapter_name (str): The name of the adapter for which the bias delta should be computed.
618
+ """
619
+ device = self.get_base_layer().weight.device
620
+ dtype = self.get_base_layer().weight.dtype
621
+ base_weight = self.get_base_layer().weight
622
+
623
+ # Get buffers
624
+ newB = self.adamss_newB[adapter_name] # Shape: (r, in_features + 1)
625
+
626
+ # Get parameter lists
627
+ param_list_A = self.adamss_A[adapter_name]
628
+ param_list_B = self.adamss_B[adapter_name]
629
+
630
+ cast_to_fp32 = device.type == "cpu" and dtype in (torch.float16, torch.bfloat16)
631
+ compute_dtype = torch.float32 if cast_to_fp32 else dtype
632
+
633
+ newB = newB.to(device).to(compute_dtype)
634
+
635
+ out_features = base_weight.shape[0]
636
+ in_features_plus_1 = newB.shape[1]
637
+
638
+ # Initialize delta weight for the adapter path only
639
+ delta_weight = torch.zeros(out_features, in_features_plus_1, device=device, dtype=compute_dtype)
640
+
641
+ # Compute the transformation for each subspace
642
+ chunks = []
643
+ for i in range(self.num_subspaces[adapter_name]):
644
+ A_i = param_list_A[i].to(device).to(compute_dtype)
645
+ B_i = param_list_B[i].to(device).to(compute_dtype)
646
+ chunk = B_i @ A_i @ newB
647
+ chunks.append(chunk)
648
+
649
+ if chunks:
650
+ combined = torch.cat(chunks, dim=0)
651
+ scatter_idx = self.scatter_index[adapter_name].to(delta_weight.device)
652
+ delta_weight[scatter_idx] = combined
653
+
654
+ # Extract the bias portion (last column)
655
+ if self.get_base_layer().bias is None:
656
+ # No bias — return zeros
657
+ output_tensor = torch.zeros(base_weight.shape[0], device=device, dtype=compute_dtype)
658
+ else:
659
+ output_tensor = delta_weight[:, -1] # Shape: (out_features,)
660
+
661
+ if cast_to_fp32:
662
+ output_tensor = output_tensor.to(dtype=dtype)
663
+
664
+ return output_tensor
665
+
666
+ def __repr__(self) -> str:
667
+ rep = super().__repr__()
668
+ return "adamss." + rep
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adamss/model.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ from typing import Optional
18
+
19
+ import torch
20
+ from torch import nn
21
+
22
+ from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer, check_target_module_exists
23
+ from peft.utils import (
24
+ TRANSFORMERS_MODELS_TO_ADAMSS_TARGET_MODULES_MAPPING,
25
+ )
26
+
27
+ from .config import AdamssConfig
28
+ from .layer import AdamssLayer, Linear
29
+
30
+
31
+ class AdamssModel(BaseTuner):
32
+ """
33
+ Creates Adamss (Adaptive Multi-Subspaces) model from a pretrained model.
34
+
35
+ The method decomposes weight matrices using SVD and clusters the decomposed space into multiple trainable subspaces
36
+ for parameter-efficient fine-tuning.
37
+
38
+ Args:
39
+ model (`torch.nn.Module`): The model to be adapted.
40
+ config (`AdamssConfig`): The configuration of the Adamss model.
41
+ adapter_name (`str`): The name of the adapter, defaults to `"default"`.
42
+
43
+ Returns:
44
+ `torch.nn.Module`: The Adamss model.
45
+
46
+ Example:
47
+ ```python
48
+ >>> from transformers import AutoModelForImageClassification
49
+ >>> from peft import AdamssConfig, get_peft_model
50
+
51
+ >>> config = AdamssConfig(
52
+ ... r=500,
53
+ ... num_subspaces=5,
54
+ ... target_modules=["query", "value"],
55
+ ... )
56
+
57
+ >>> model = AutoModelForImageClassification.from_pretrained("google/vit-base-patch16-224")
58
+ >>> adamss_model = get_peft_model(model, config)
59
+ ```
60
+
61
+ **Attributes**:
62
+ - **model** ([`~torch.nn.Module`]) -- The model to be adapted.
63
+ - **peft_config** ([`AdamssConfig`]): The configuration of the Adamss model.
64
+ """
65
+
66
+ prefix: str = "adamss_"
67
+ tuner_layer_cls = (AdamssLayer,)
68
+ target_module_mapping = TRANSFORMERS_MODELS_TO_ADAMSS_TARGET_MODULES_MAPPING
69
+
70
+ def __init__(
71
+ self, model, config, adapter_name, low_cpu_mem_usage: bool = False, state_dict: Optional[dict] = None
72
+ ) -> None:
73
+ # Initialize ASA tracking before BaseTuner injects adapters so attribute exists.
74
+ self._asa_total_subspaces = {}
75
+ super().__init__(model, config, adapter_name, low_cpu_mem_usage=low_cpu_mem_usage, state_dict=state_dict)
76
+
77
+ @staticmethod
78
+ def _check_target_module_exists(adamss_config, key):
79
+ """Helper to check if target module matches the pattern."""
80
+ return check_target_module_exists(adamss_config, key)
81
+
82
+ def _create_and_replace(
83
+ self,
84
+ adamss_config: AdamssConfig,
85
+ adapter_name: str,
86
+ target: nn.Module,
87
+ target_name: str,
88
+ parent: nn.Module,
89
+ current_key: str,
90
+ **optional_kwargs,
91
+ ):
92
+ """
93
+ Create and replace target module with Adamss-adapted module.
94
+ """
95
+ if current_key is None:
96
+ raise ValueError("Current Key shouldn't be `None`")
97
+
98
+ # Check if already an Adamss layer
99
+ if isinstance(target, AdamssLayer):
100
+ target.update_layer(
101
+ adapter_name,
102
+ adamss_config.r,
103
+ config=adamss_config,
104
+ )
105
+ # set_adapter is called inside update_layer, but we need to handle
106
+ # the case where adapter is not in active_adapters
107
+ if adapter_name not in self.active_adapters:
108
+ # Ensure the new adapter is frozen if not active
109
+ target.set_adapter(self.active_adapters, inference_mode=adamss_config.inference_mode)
110
+ else:
111
+ # Create new Adamss layer
112
+ new_module = self._create_new_module(adamss_config, adapter_name, target, **optional_kwargs)
113
+ self._record_asa_total_subspaces(adapter_name, adamss_config, new_module)
114
+ # requires_grad is handled inside _create_new_module via set_adapter
115
+ self._replace_module(parent, target_name, new_module, target)
116
+
117
+ def _record_asa_total_subspaces(self, adapter_name: str, adamss_config: AdamssConfig, module: AdamssLayer) -> None:
118
+ """Track total subspaces per adapter so the ASA schedule matches adamss_pkg."""
119
+ if not hasattr(module, "num_subspaces"):
120
+ return
121
+ layer_num_subspaces = module.num_subspaces.get(adapter_name, 0)
122
+ if layer_num_subspaces is None or layer_num_subspaces <= 0:
123
+ return
124
+ prev_total = self._asa_total_subspaces.get(adapter_name, 0)
125
+ self._asa_total_subspaces[adapter_name] = prev_total + layer_num_subspaces
126
+
127
+ def _create_new_module(
128
+ self,
129
+ adamss_config: AdamssConfig,
130
+ adapter_name: str,
131
+ target: nn.Module,
132
+ **kwargs,
133
+ ) -> nn.Module:
134
+ """
135
+ Create a new Adamss module based on the target module type.
136
+ """
137
+ if isinstance(target, BaseTunerLayer):
138
+ target_base_layer = target.get_base_layer()
139
+ else:
140
+ target_base_layer = target
141
+
142
+ if isinstance(target_base_layer, torch.nn.Linear):
143
+ new_module = Linear(
144
+ target,
145
+ adapter_name,
146
+ r=adamss_config.r,
147
+ config=adamss_config,
148
+ **kwargs,
149
+ )
150
+ else:
151
+ raise TypeError(
152
+ f"Target module {target} is not supported. Currently, only `torch.nn.Linear` is supported."
153
+ )
154
+
155
+ return new_module
156
+
157
+ def update_and_allocate(self, global_step: int) -> None:
158
+ """
159
+ Update importance scores and apply ASA masking (if enabled).
160
+
161
+ This method should be called in **every** training step after ``loss.backward()`` and before
162
+ ``optimizer.zero_grad()`` when ASA is enabled. Internally it:
163
+
164
+ 1. Accumulates importance scores via EMA every step during the warmup period.
165
+ 2. At mask intervals, applies global top-K masking and resets importance.
166
+
167
+ This is the single entry point for ASA – using the :class:`AdamssAsaCallback` with HuggingFace ``Trainer``
168
+ simply delegates to this method. For custom training loops, call this directly instead of the callback.
169
+
170
+ Args:
171
+ global_step (`int`): The current training step.
172
+
173
+ Example::
174
+
175
+ for step, batch in enumerate(dataloader):
176
+ loss = model(**batch).loss loss.backward() optimizer.step() model.base_model.update_and_allocate(step)
177
+ optimizer.zero_grad()
178
+ """
179
+ for adapter_name in self.active_adapters:
180
+ config = self.peft_config[adapter_name]
181
+ if not config.use_asa:
182
+ continue
183
+
184
+ within_warmup = config.init_warmup <= global_step <= config.final_warmup
185
+
186
+ # --- collect ASA layers once ---
187
+ asa_layers = [
188
+ m for m in self.model.modules() if isinstance(m, AdamssLayer) and adapter_name in m.exp_avg_ipt_A
189
+ ]
190
+ if not asa_layers:
191
+ continue
192
+
193
+ # Step 1: accumulate importance EVERY step during warmup
194
+ if within_warmup:
195
+ for module in asa_layers:
196
+ module.update_importance(adapter_name, config.asa_importance_beta, config.asa_uncertainty_beta)
197
+
198
+ # Step 2: at mask intervals → schedule, global mask, then reset
199
+ is_mask_interval = global_step % config.mask_interval == 0
200
+ if within_warmup and is_mask_interval:
201
+ current_target = self._schedule_threshold(global_step, config)
202
+ if current_target is not None:
203
+ self._global_mask_to_target(current_target, adapter_name, asa_layers)
204
+
205
+ # Reset importance AFTER masking for fresh accumulation
206
+ for module in asa_layers:
207
+ module.reset_importance(adapter_name)
208
+
209
+ def _schedule_threshold(self, step: int, config) -> Optional[int]:
210
+ """Calculate current target subspaces based on warmup schedule."""
211
+ total = self._asa_total_subspaces.get(next(iter(self.active_adapters), "default"), 0)
212
+ if total == 0:
213
+ total = self._get_asa_total_subspaces()
214
+ if total == 0:
215
+ return None
216
+
217
+ if step < config.init_warmup:
218
+ return None
219
+ elif step <= config.final_warmup:
220
+ mul_coeff = 1.0 - (step - config.init_warmup) / (config.final_warmup - config.init_warmup)
221
+ mul_coeff = max(0.0, min(1.0, mul_coeff))
222
+ exponent = getattr(config, "asa_schedule_exponent", 3.0)
223
+ return int(config.asa_target_subspaces + (total - config.asa_target_subspaces) * (mul_coeff**exponent))
224
+ else:
225
+ return config.asa_target_subspaces
226
+
227
+ def _get_asa_total_subspaces(self) -> int:
228
+ """Get total number of subspaces from model (sum across all layers)."""
229
+ total = 0
230
+ for module in self.model.modules():
231
+ if isinstance(module, AdamssLayer) and module.num_subspaces:
232
+ total += next(iter(module.num_subspaces.values()))
233
+ return total
234
+
235
+ def _global_mask_to_target(self, target_subspaces: int, adapter_name: str, asa_layers: list) -> None:
236
+ """
237
+ Apply **global** top-K masking across all layers.
238
+
239
+ Collects importance scores from every subspace in every layer, ranks them globally, and keeps only the top
240
+ ``target_subspaces`` active.
241
+ """
242
+ # 1. Collect (module, subspace_idx, score) for every subspace
243
+ subspace_scores: list[tuple] = []
244
+ for module in asa_layers:
245
+ n_subspaces = module.num_subspaces.get(adapter_name, 0)
246
+ ipt_A = module.exp_avg_ipt_A[adapter_name]
247
+ ipt_B = module.exp_avg_ipt_B[adapter_name]
248
+ unc_A = module.exp_avg_unc_A[adapter_name]
249
+ unc_B = module.exp_avg_unc_B[adapter_name]
250
+
251
+ for i in range(n_subspaces):
252
+ if ipt_A[i] is None or ipt_B[i] is None:
253
+ continue
254
+ score = (ipt_A[i] * unc_A[i]).mean() + (ipt_B[i] * unc_B[i]).mean()
255
+ subspace_scores.append((module, i, score))
256
+
257
+ if not subspace_scores:
258
+ return
259
+
260
+ # 2. Compute global threshold via kth-value
261
+ all_scores = torch.stack([s[2] for s in subspace_scores])
262
+ if target_subspaces >= len(subspace_scores):
263
+ threshold = float("-inf")
264
+ else:
265
+ threshold = -torch.kthvalue(-all_scores, target_subspaces)[0].item()
266
+
267
+ # 3. Apply masking
268
+ for module, idx, score in subspace_scores:
269
+ is_active = float(score) > threshold
270
+ param_A = module.adamss_A[adapter_name]
271
+ param_B = module.adamss_B[adapter_name]
272
+ if idx < len(param_A):
273
+ param_A[idx].requires_grad = is_active
274
+ if not is_active:
275
+ param_A[idx].grad = None
276
+ if idx < len(param_B):
277
+ param_B[idx].requires_grad = is_active
278
+ if not is_active:
279
+ param_B[idx].grad = None
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adamss/utils.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import torch
16
+
17
+
18
+ def slice_pca(tensor, r, device, dtype=torch.float32):
19
+ """
20
+ Perform slice-wise PCA (SVD) on 4D tensor.
21
+
22
+ Args:
23
+ tensor: 4D tensor of shape (B, C, H, W)
24
+ r: rank for low-rank approximation
25
+ device: computation device
26
+ dtype: data type
27
+
28
+ Returns:
29
+ VVT: Right singular vectors (B, C, r, W) UU: Left singular vectors (B, C, H, r)
30
+ """
31
+ tensor = tensor.to(device)
32
+ B, C, H, W = tensor.shape
33
+
34
+ # Clamp r to the minimum dimension to avoid SVD errors
35
+ # SVD rank cannot exceed min(H, W)
36
+ effective_r = min(r, H, W)
37
+
38
+ UU = torch.zeros(B, C, H, effective_r, dtype=dtype, device=device)
39
+ VVT = torch.zeros(B, C, effective_r, W, dtype=dtype, device=device)
40
+
41
+ for i in range(B):
42
+ for j in range(C):
43
+ U, _, V = torch.svd_lowrank(tensor[i, j, :, :], q=effective_r, niter=2, M=None)
44
+ UU[i, j, :, :] = U[:, 0:effective_r]
45
+ VVT[i, j, :, :] = V[:, 0:effective_r].T
46
+ # Return computed matrices (important: ensure callers receive VVT and UU)
47
+ return VVT, UU
48
+
49
+
50
+ def clustering_Z(VT, num_subspaces, iternum):
51
+ """
52
+ Cluster the rows of VT into K subspaces using K-Means.
53
+
54
+ Args:
55
+ VT: Matrix to cluster (rows are clustered)
56
+ num_subspaces: Number of clusters (subspaces)
57
+ iternum: Maximum iterations for K-Means
58
+
59
+ Returns:
60
+ cluster_idx: Cluster assignments as a ``torch.LongTensor`` effective_num_subspaces: Actual number of subspaces
61
+ used (``int``)
62
+
63
+ Note:
64
+ This function requires scikit-learn to be installed. Install it with: pip install scikit-learn
65
+ """
66
+ # Local import with helpful error message
67
+ try:
68
+ from sklearn.cluster import KMeans
69
+ except ImportError:
70
+ raise ImportError(
71
+ "scikit-learn is required for AdaMSS initialization. Please install it with: pip install scikit-learn"
72
+ )
73
+
74
+ # Move to numpy for sklearn compatibility
75
+ # Note: We do NOT normalize row vectors here to match the original adamss_pkg behavior.
76
+ # Although normalization is generally recommended for cosine-similarity-like clustering,
77
+ # the reference implementation clusters raw singular vectors.
78
+ vt = VT.detach().cpu().numpy().astype("float32")
79
+
80
+ # Auto-clamp num_subspaces to available samples (output dimensions)
81
+ # Cannot cluster n samples into more than n clusters
82
+ effective_num_subspaces = min(num_subspaces, vt.shape[0])
83
+
84
+ kmeans = KMeans(
85
+ n_clusters=effective_num_subspaces, init="random", n_init=1, max_iter=iternum, random_state=123456789
86
+ )
87
+ idx = kmeans.fit_predict(vt)
88
+
89
+ return torch.from_numpy(idx).long(), effective_num_subspaces
90
+
91
+
92
+ def seg_locations(index):
93
+ """
94
+ Segment indices into locations based on cluster assignments.
95
+
96
+ Args:
97
+ index: Cluster assignments as a ``torch.LongTensor``
98
+
99
+ Returns:
100
+ location: Dict mapping cluster id to ``torch.LongTensor`` of row indices.
101
+ Clusters are ordered by their smallest index so that KMeans label permutations do not affect downstream
102
+ ordering.
103
+ """
104
+ K = int(index.max().item()) + 1
105
+ location = {}
106
+ for i in range(K):
107
+ location[i] = torch.where(index == i)[0]
108
+ return location
109
+
110
+
111
+ def get_trainable_subspaces(num_subspaces):
112
+ """
113
+ Get all trainable subspace indices.
114
+
115
+ Args:
116
+ num_subspaces: Number of subspaces
117
+
118
+ Returns:
119
+ List of trainable subspace indices (``list[int]``)
120
+ """
121
+ return list(range(num_subspaces))
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adaption_prompt/__init__.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from peft.utils import register_peft_method
15
+
16
+ from .config import AdaptionPromptConfig
17
+ from .layer import AdaptedAttention
18
+ from .model import AdaptionPromptModel
19
+
20
+
21
+ __all__ = ["AdaptedAttention", "AdaptionPromptConfig", "AdaptionPromptModel"]
22
+
23
+ register_peft_method(name="adaption_prompt", config_cls=AdaptionPromptConfig, model_cls=AdaptionPromptModel)
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adaption_prompt/config.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from collections import namedtuple
16
+ from dataclasses import dataclass, field
17
+
18
+ from peft.config import PeftConfig
19
+ from peft.utils import PeftType
20
+
21
+ from .utils import gpt2_compute_query_states, llama_compute_query_states
22
+
23
+
24
+ @dataclass
25
+ class AdaptionPromptConfig(PeftConfig):
26
+ """Stores the configuration of an [`AdaptionPromptModel`]."""
27
+
28
+ target_modules: str = field(
29
+ default=None, metadata={"help": "Name of the attention submodules to insert adaption prompts into."}
30
+ )
31
+ adapter_len: int = field(default=None, metadata={"help": "Number of adapter tokens to insert"})
32
+ adapter_layers: int = field(default=None, metadata={"help": "Number of adapter layers (from the top)"})
33
+
34
+ def __post_init__(self):
35
+ super().__post_init__()
36
+ self.peft_type = PeftType.ADAPTION_PROMPT
37
+
38
+ @property
39
+ def is_adaption_prompt(self) -> bool:
40
+ """Return True if this is an adaption prompt config."""
41
+ return True
42
+
43
+
44
+ # Contains the config that is specific to a transformers model type.
45
+ ModelTypeConfig = namedtuple(
46
+ "ModelTypeConfig", ["compute_query_states", "target_modules", "k_proj_layer", "v_proj_layer", "o_proj_layer"]
47
+ )
48
+
49
+ # Mapping of transformers model types to their specific configuration.
50
+ TRANSFORMERS_MODEL_CONFIG = {
51
+ "llama": ModelTypeConfig(
52
+ compute_query_states=llama_compute_query_states,
53
+ target_modules="self_attn",
54
+ k_proj_layer="k_proj",
55
+ v_proj_layer="v_proj",
56
+ o_proj_layer="o_proj",
57
+ ),
58
+ "mistral": ModelTypeConfig( # same as llama,
59
+ compute_query_states=llama_compute_query_states,
60
+ target_modules="self_attn",
61
+ k_proj_layer="k_proj",
62
+ v_proj_layer="v_proj",
63
+ o_proj_layer="o_proj",
64
+ ),
65
+ "gpt2": ModelTypeConfig( # piggybacking of off the prior definitions, GPTs attention calculation is different
66
+ compute_query_states=gpt2_compute_query_states,
67
+ target_modules="attn",
68
+ k_proj_layer="c_attn",
69
+ v_proj_layer=None,
70
+ o_proj_layer=None,
71
+ ),
72
+ }
73
+
74
+
75
+ def prepare_config(
76
+ peft_config: AdaptionPromptConfig,
77
+ model,
78
+ ) -> AdaptionPromptConfig:
79
+ """Prepare the config based on the llama model type."""
80
+ if model.config.model_type not in TRANSFORMERS_MODEL_CONFIG:
81
+ raise ValueError(f"Unsupported model type for adaption prompt: '{model.config.model_type}'.")
82
+
83
+ model_config = TRANSFORMERS_MODEL_CONFIG[model.config.model_type]
84
+
85
+ if peft_config.target_modules is None:
86
+ peft_config.target_modules = model_config.target_modules
87
+
88
+ return peft_config
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adaption_prompt/layer.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import math
16
+ from typing import Optional, Union
17
+
18
+ import torch
19
+ import torch.nn.functional as F
20
+ from torch import nn
21
+
22
+ from .config import TRANSFORMERS_MODEL_CONFIG
23
+
24
+
25
+ class _BaseAdaptedAttention(nn.Module):
26
+ """Base module, which defines adaption prompts for multiple model types."""
27
+
28
+ def __init__(self, model_type: str, adapter_len: int, model, target_dtype=torch.float32):
29
+ """
30
+ Initialize object.
31
+
32
+ Args:
33
+ model_type: The transformer model type. This is used to retrieve the right method to
34
+ compute query states.
35
+ adapter_len: The length of the adaption prompt to insert.
36
+ model: The original transformer attention module that is being wrapped.
37
+ """
38
+ if isinstance(model, _BaseAdaptedAttention):
39
+ raise TypeError("Unable to stack multiple adaption prompts")
40
+ super().__init__()
41
+ self.model_type = model_type
42
+ self.model = model
43
+ self.adapter_len = adapter_len
44
+ # Assume all parameters of the attention model we are wrapping are on the same device.
45
+
46
+ device = next(model.parameters()).device
47
+ # Don't think this was specified in the paper, but we follow the official repo which used an Embedding
48
+ # which initializes the tokens with standard normal values.
49
+ # https://github.com/ZrrSkywalker/LLaMA-Adapter/blob/41c3546fe1997ab8a65809dc8d8f9252b19d9faf/llama/model.py#L234
50
+ # (bsz, adapter_len, hidden_size)
51
+
52
+ hidden_size = self.model.config.hidden_size
53
+ self.num_heads = self.model.config.num_attention_heads
54
+
55
+ self.adaption_prompt = nn.Parameter(
56
+ torch.empty(1, adapter_len, hidden_size, device=device, dtype=target_dtype).normal_()
57
+ )
58
+ # Initialize the gate to 0 as this is "zero-init".
59
+ self.adaption_gate = nn.Parameter(torch.zeros(1, device=device, dtype=target_dtype))
60
+
61
+
62
+ class AdaptedAttentionGPT(_BaseAdaptedAttention):
63
+ """This module wraps a GPT2Attention module and injects adaption prompts"""
64
+
65
+ def __init__(self, model_type, adapter_len, model):
66
+ target_dtype = (
67
+ model.c_proj.weight.dtype if model.c_proj.weight.dtype not in [torch.int8, torch.uint8] else torch.float32
68
+ )
69
+ super().__init__(model_type, adapter_len, model, target_dtype=target_dtype)
70
+
71
+ def forward(
72
+ self,
73
+ hidden_states: Optional[tuple[torch.FloatTensor]],
74
+ layer_past: Optional[tuple[torch.Tensor]] = None,
75
+ attention_mask: Optional[torch.FloatTensor] = None,
76
+ head_mask: Optional[torch.FloatTensor] = None,
77
+ encoder_hidden_states: Optional[torch.Tensor] = None,
78
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
79
+ use_cache: Optional[bool] = False,
80
+ output_attentions: Optional[bool] = False,
81
+ **kwargs,
82
+ ) -> tuple[Union[torch.Tensor, tuple[torch.Tensor]], ...]:
83
+ attn_outputs = self.model(
84
+ hidden_states=hidden_states,
85
+ attention_mask=attention_mask,
86
+ head_mask=head_mask,
87
+ encoder_hidden_states=encoder_hidden_states,
88
+ encoder_attention_mask=encoder_attention_mask,
89
+ use_cache=use_cache,
90
+ output_attentions=output_attentions,
91
+ **kwargs,
92
+ )
93
+ """
94
+ Forward pass for the adapter which wraps the GPT2Attention module
95
+ """
96
+
97
+ attn_output = attn_outputs[0]
98
+ add_outputs = attn_outputs[1:]
99
+
100
+ c_attn_layer = TRANSFORMERS_MODEL_CONFIG[self.model_type].k_proj_layer
101
+
102
+ bsz = attn_output.shape[0]
103
+ q_len = attn_output.shape[1]
104
+ embed_dim = attn_output.shape[2]
105
+
106
+ _, key, value = getattr(self.model, c_attn_layer)(self.adaption_prompt).split(embed_dim, dim=2)
107
+
108
+ adapter_k = (
109
+ key.view(1, self.adapter_len, self.num_heads, self.model.head_dim).repeat(bsz, 1, 1, 1).transpose(1, 2)
110
+ )
111
+ adapter_v = (
112
+ value.view(1, self.adapter_len, self.num_heads, self.model.head_dim).repeat(bsz, 1, 1, 1).transpose(1, 2)
113
+ )
114
+ # recompute query state since it is not returned by GPT2 forward
115
+ compute_query_states = TRANSFORMERS_MODEL_CONFIG[self.model_type].compute_query_states
116
+ query_states = compute_query_states(
117
+ self.model, hidden_states=hidden_states, encoder_hidden_states=encoder_hidden_states
118
+ )
119
+
120
+ previous_dtype = query_states.dtype
121
+
122
+ scores = torch.matmul(query_states, adapter_k.transpose(2, 3).to(previous_dtype)) / math.sqrt(
123
+ self.model.head_dim
124
+ )
125
+ # Upcast attention to fp32
126
+ # (bsz, num_heads, q_len, adapter_len)
127
+ scores = self.adaption_gate * F.softmax(scores, dim=-1, dtype=torch.float32).to(previous_dtype)
128
+ # (bsz, q_len, num_heads * head_dim)
129
+ adapter_output = torch.matmul(scores, adapter_v).transpose(1, 2).reshape(bsz, q_len, -1)
130
+
131
+ # Add adaption prompt output to original output.
132
+ hidden_state = attn_output + adapter_output
133
+
134
+ # Restore original dtype.
135
+ hidden_state = hidden_state.to(previous_dtype)
136
+
137
+ # add additional attention outputs (attention and cross attention)
138
+ output = (hidden_state,) + add_outputs
139
+ return output
140
+
141
+
142
+ class AdaptedAttention(_BaseAdaptedAttention):
143
+ """This module wraps a LLamaAttention module and injects adaption prompts."""
144
+
145
+ def __init__(self, model_type, adapter_len, model):
146
+ target_dtype = (
147
+ model.q_proj.weight.dtype if model.q_proj.weight.dtype not in [torch.int8, torch.uint8] else torch.float32
148
+ )
149
+ super().__init__(model_type, adapter_len, model, target_dtype=target_dtype)
150
+
151
+ def forward(self, **kwargs):
152
+ """
153
+ Forward pass for the adapter which wraps the original LlamaAttention module.
154
+
155
+ "Official" paper implementation:
156
+ https://github.com/ZrrSkywalker/LLaMA-Adapter/blob/41c3546fe1997ab8a65809dc8d8f9252b19d9faf/llama/model.py#L141
157
+
158
+ Args:
159
+ kwargs: See the original LlamaAttention module.
160
+ """
161
+ if kwargs.get("output_attention", False):
162
+ raise NotImplementedError("output_attention is not currently supported.")
163
+
164
+ output, *_ = self.model(**kwargs)
165
+ bsz = output.shape[0]
166
+ q_len = output.shape[1]
167
+ embed_dim = output.shape[2]
168
+ k_proj_layer = TRANSFORMERS_MODEL_CONFIG[self.model_type].k_proj_layer
169
+ v_proj_layer = TRANSFORMERS_MODEL_CONFIG[self.model_type].v_proj_layer
170
+ o_proj_layer = TRANSFORMERS_MODEL_CONFIG[self.model_type].o_proj_layer
171
+ factor = (
172
+ self.model.k_proj.in_features // self.model.k_proj.out_features
173
+ ) # Mistral has different input and output dimension for k_proj and v_proj layers
174
+
175
+ if k_proj_layer == v_proj_layer:
176
+ _, key, value = getattr(self.model, k_proj_layer)(self.adaption_prompt).split(embed_dim, dim=2)
177
+ else:
178
+ key = getattr(self.model, k_proj_layer)(self.adaption_prompt)
179
+ value = getattr(self.model, v_proj_layer)(self.adaption_prompt)
180
+
181
+ num_heads = self.model.config.num_attention_heads
182
+ # (bsz, num_key_value_heads, adapter_len, head_dim)
183
+ adapter_k = (
184
+ key.view(1, self.adapter_len, (num_heads // factor), self.model.head_dim)
185
+ .repeat(bsz, 1, 1, 1)
186
+ .transpose(1, 2)
187
+ )
188
+ adapter_v = (
189
+ value.view(1, self.adapter_len, (num_heads // factor), self.model.head_dim)
190
+ .repeat(bsz, 1, 1, 1)
191
+ .transpose(1, 2)
192
+ )
193
+ # Below is taken from https://github.com/huggingface/transformers/blob/e547458c43dfdbbb8f6a7757237e234c44e20a8f/src/transformers/models/mistral/modeling_mistral.py#L181
194
+ # (bsz, num_heads, adapter_len, head_dim)
195
+ adapter_k = torch.repeat_interleave(adapter_k, repeats=factor, dim=1)
196
+ adapter_v = torch.repeat_interleave(adapter_v, repeats=factor, dim=1)
197
+ # Recompute query states.
198
+ compute_query_states = TRANSFORMERS_MODEL_CONFIG[self.model_type].compute_query_states
199
+ # (bsz, num_heads, q_len, head_dim)
200
+ query_states = compute_query_states(model=self.model, **kwargs)
201
+
202
+ previous_dtype = query_states.dtype
203
+
204
+ # (bsz, num_heads, q_len, adapter_len)
205
+ scores = torch.matmul(query_states, adapter_k.transpose(2, 3).to(previous_dtype)) / math.sqrt(
206
+ self.model.head_dim
207
+ )
208
+ # Upcast attention to fp32
209
+ # (bsz, num_heads, q_len, adapter_len)
210
+ scores = self.adaption_gate * F.softmax(scores, dim=-1, dtype=torch.float32).to(previous_dtype)
211
+ # (bsz, q_len, num_heads * head_dim)
212
+ adapter_output = torch.matmul(scores, adapter_v).transpose(1, 2).reshape(bsz, q_len, -1)
213
+
214
+ # (bsz, q_len, hidden_size)
215
+ if o_proj_layer is not None:
216
+ adapter_output = getattr(self.model, o_proj_layer)(adapter_output)
217
+
218
+ # Add adaption prompt output to original output.
219
+ output = output + adapter_output
220
+
221
+ # Restore original dtype.
222
+ output = output.to(previous_dtype)
223
+ return output, *_
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adaption_prompt/model.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from torch import nn
17
+
18
+ from peft.utils import _freeze_adapter, _get_submodules
19
+
20
+ from .config import AdaptionPromptConfig, prepare_config
21
+ from .layer import AdaptedAttention, AdaptedAttentionGPT
22
+ from .utils import is_adaption_prompt_trainable
23
+
24
+
25
+ class AdaptionPromptModel(nn.Module):
26
+ """
27
+ Implements adaption prompts as described in https://huggingface.co/papers/2303.16199.
28
+
29
+ The top L attention modules are replaced with AdaptedAttention modules that wrap the original ones, but insert
30
+ trainable prompts with gates (for zero init).
31
+
32
+ Notes on the multi-adapter pattern:
33
+ - We store the states of different adapters by keeping a dictionary of AdaptedAttention modules indexed by adapter
34
+ name.
35
+ - Every time we switch adapters, we remove the modules of the currently active adapter from the model, store them
36
+ in the dictionary, and replace them with the modules of the new adapter.
37
+ - To avoid duplicated and potentially inconsistent state, the currently active adapter is always removed from the
38
+ dictionary.
39
+ - Disabling the adapter would also result in the modules being removed from the model.
40
+ """
41
+
42
+ def __init__(self, model, configs: dict, adapter_name: str):
43
+ super().__init__()
44
+ self.model = model
45
+ # Store adapter configs by name.
46
+ self.peft_config: dict[str, AdaptionPromptConfig] = {}
47
+ # Store lists of the parents of the affected attention modules by adapter name.
48
+ # We keep references to the parents so we can swap the adapters in-and-out of the model.
49
+ self._parents: dict[str, list[nn.Module]] = {}
50
+ # Store lists of cached AdaptedAttention modules by name.
51
+ self._cached_adapters: dict[str, list] = {}
52
+ # The name of the currently active adapter.
53
+ self._active_adapter = None
54
+ # Whether the adapter is enabled.
55
+ self._enabled = True
56
+ self.forward = self.model.forward
57
+ self.add_adapter(adapter_name, configs[adapter_name])
58
+ self._mark_only_adaption_prompts_as_trainable(self.model)
59
+
60
+ def add_adapter(self, adapter_name: str, config: AdaptionPromptConfig) -> None:
61
+ """Add an adapter with the given name and config."""
62
+ config = prepare_config(config, self.model)
63
+ if adapter_name in self.peft_config:
64
+ raise ValueError(f"Adapter with name '{adapter_name}' already exists.")
65
+
66
+ parents = []
67
+ for name, _ in self.model.named_modules():
68
+ if name.endswith(f".{config.target_modules}"):
69
+ par, _, _ = _get_submodules(self.model, name)
70
+ parents.append(par)
71
+ if len(parents) < config.adapter_layers:
72
+ raise ValueError(
73
+ f"Config specifies more adapter layers '{config.adapter_layers}' than the model has '{len(parents)}'."
74
+ )
75
+ # Note that if the target modules are not in Sequential, ModuleList, or
76
+ # some other PyTorch ordered container, the behavior is undefined as we
77
+ # assume here that the order of the modules is the same as the order of
78
+ # the transformer decoder layers.
79
+ parents = parents[-config.adapter_layers :]
80
+ self._parents[adapter_name] = parents
81
+
82
+ # It is only None during initialization.
83
+ # If it is disabled, we don't have to remove the modules.
84
+ if self._active_adapter is not None and self._enabled:
85
+ self._remove_adapted_attentions(self._active_adapter)
86
+ self._active_adapter = adapter_name
87
+ self.peft_config[adapter_name] = config
88
+ self._create_adapted_attentions(config, parents)
89
+ if not self._enabled:
90
+ self._remove_adapted_attentions(self._active_adapter)
91
+
92
+ if config.inference_mode:
93
+ _freeze_adapter(self.model, adapter_name)
94
+
95
+ def set_adapter(self, adapter_name: str, inference_mode: bool = False) -> None:
96
+ """Set the model to use the adapter with the given name."""
97
+ if inference_mode:
98
+ raise ValueError("inference_mode is not supported for AdaptionPromptModel.")
99
+ if self._active_adapter == adapter_name:
100
+ return
101
+ if adapter_name not in self.peft_config:
102
+ raise ValueError(f"Adapter with name '{adapter_name}' does not exist.")
103
+
104
+ if self._enabled:
105
+ self._remove_adapted_attentions(self._active_adapter)
106
+ self._set_adapted_attentions(adapter_name)
107
+
108
+ self._active_adapter = adapter_name
109
+
110
+ def enable_adapter_layers(self):
111
+ """Enable adapter layers by swapping in cached AdaptedAttention modules."""
112
+ self._enabled = True
113
+ self._set_adapted_attentions(self._active_adapter)
114
+
115
+ def disable_adapter_layers(self):
116
+ """Disable adapter layers by swapping out AdaptedAttention modules."""
117
+ self._enabled = False
118
+ self._remove_adapted_attentions(self._active_adapter)
119
+
120
+ def _create_adapted_attentions(self, config: AdaptionPromptConfig, parents: list[nn.Module]) -> None:
121
+ """Wrap LlamaAttention modules with newly created AdaptedAttention modules."""
122
+ for par in parents:
123
+ if self.model.config.model_type == "gpt2":
124
+ attn = AdaptedAttentionGPT(
125
+ model_type=self.model.config.model_type,
126
+ adapter_len=config.adapter_len,
127
+ model=getattr(par, config.target_modules),
128
+ )
129
+
130
+ else:
131
+ attn = AdaptedAttention(
132
+ model_type=self.model.config.model_type,
133
+ adapter_len=config.adapter_len,
134
+ model=getattr(par, config.target_modules),
135
+ )
136
+ setattr(par, config.target_modules, attn)
137
+
138
+ def _set_adapted_attentions(self, adapter_name: str) -> None:
139
+ """Replace LlamaAttention modules with cached AdaptedAttention modules."""
140
+ cached = self._cached_adapters[adapter_name]
141
+ del self._cached_adapters[adapter_name]
142
+ config = self.peft_config[adapter_name]
143
+ for i, par in enumerate(self._parents[adapter_name]):
144
+ setattr(par, config.target_modules, cached[i])
145
+
146
+ def _remove_adapted_attentions(self, adapter_name: str) -> None:
147
+ """Remove AdaptedAttention modules from the model and store them in the cache."""
148
+ config = self.peft_config[adapter_name]
149
+ adapted_attentions = []
150
+ for par in self._parents[adapter_name]:
151
+ attn = getattr(par, config.target_modules)
152
+ adapted_attentions.append(attn)
153
+ setattr(par, config.target_modules, attn.model)
154
+ self._cached_adapters[adapter_name] = adapted_attentions
155
+
156
+ def _mark_only_adaption_prompts_as_trainable(self, model: nn.Module) -> None:
157
+ """Freeze all parameters of the model except the adaption prompts."""
158
+ for n, p in model.named_parameters():
159
+ if not is_adaption_prompt_trainable(n):
160
+ p.requires_grad = False
161
+
162
+ def __getattr__(self, name: str):
163
+ """Forward missing attributes to the wrapped module."""
164
+ try:
165
+ return super().__getattr__(name) # defer to nn.Module's logic
166
+ except AttributeError:
167
+ # This is necessary as e.g. causal models have various methods that we
168
+ # don't want to re-implement here.
169
+ if name == "model": # see #1892: prevent infinite recursion if class is not initialized
170
+ raise
171
+ return getattr(self.model, name)
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/adaption_prompt/utils.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import inspect
15
+ from typing import Optional
16
+
17
+ import torch
18
+ from torch import nn
19
+
20
+
21
+ def llama_rotate_half(x: torch.Tensor) -> torch.Tensor:
22
+ """
23
+ Rotate half the hidden dims of the input.
24
+
25
+ This function was duplicated verbatim from:
26
+ https://github.com/huggingface/transformers/blob/1de8ce9ee1191ba761a593ac15d9ccbf5851bfc5/src/transformers/models/llama/modeling_llama.py#L126
27
+
28
+ This was done to eliminate the Llama transformers implementation as a dependency of this file. Note that some other
29
+ functions were also adapted from the transformers implementation but were modified.
30
+ """
31
+ x1 = x[..., : x.shape[-1] // 2]
32
+ x2 = x[..., x.shape[-1] // 2 :]
33
+ return torch.cat((-x2, x1), dim=-1)
34
+
35
+
36
+ def llama_apply_rotary_pos_emb(q, cos, sin, position_ids):
37
+ """
38
+ Apply rotary position embedding to query states in the Llama model.
39
+
40
+ This function was adapted from:
41
+ https://github.com/huggingface/transformers/blob/1de8ce9ee1191ba761a593ac15d9ccbf5851bfc5/src/transformers/models/llama/modeling_llama.py#L133
42
+
43
+ It was modified to remove unnecessary processing of key states. The method is compatible with transformers <=
44
+ 4.34.2 and also with the latest version (>=4.35).
45
+ """
46
+ # In previous transformers version cos/sin cached had a shape of 4D
47
+ if len(cos.shape) == 4:
48
+ gather_indices = position_ids[:, None, :, None] # [bs, 1, seq_len, 1]
49
+ gather_indices = gather_indices.repeat(1, cos.shape[1], 1, cos.shape[3])
50
+ cos = torch.gather(cos.repeat(gather_indices.shape[0], 1, 1, 1), 2, gather_indices)
51
+ sin = torch.gather(sin.repeat(gather_indices.shape[0], 1, 1, 1), 2, gather_indices)
52
+ # In the new version, it is 2D so we fall back to the new implementation
53
+ # https://github.com/huggingface/transformers/blame/eef7ea98c31a333bacdc7ae7a2372bde772be8e4/src/transformers/models/llama/modeling_llama.py#L222-L226
54
+ else:
55
+ cos = cos[position_ids].unsqueeze(1)
56
+ sin = sin[position_ids].unsqueeze(1)
57
+ q_embed = (q * cos) + (llama_rotate_half(q) * sin)
58
+ return q_embed
59
+
60
+
61
+ def llama_compute_query_states(model: nn.Module, **kwargs) -> torch.Tensor:
62
+ """
63
+ Compute query states for Llama models specifically. They need to be recomputed as the forward() method of the
64
+ original LlamaModel in the transformers library does not return them. See the related discussion in the PR:
65
+ https://github.com/huggingface/peft/pull/268
66
+ """
67
+ hidden_states = kwargs.get("hidden_states")
68
+ position_ids = kwargs.get("position_ids")
69
+ past_key_value = kwargs.get("past_key_value")
70
+ bsz, q_len, _ = hidden_states.size()
71
+ num_heads = model.config.num_attention_heads
72
+ query_states = model.q_proj(hidden_states).view(bsz, q_len, num_heads, model.head_dim).transpose(1, 2)
73
+
74
+ factor = model.k_proj.in_features // model.k_proj.out_features
75
+ value_states = model.v_proj(hidden_states).view(bsz, q_len, (num_heads // factor), model.head_dim).transpose(1, 2)
76
+
77
+ seq_len = q_len
78
+
79
+ if past_key_value is not None:
80
+ if isinstance(past_key_value, tuple):
81
+ # for transformers <= 4.35
82
+ seq_len += past_key_value[0].shape[-2]
83
+ else:
84
+ # since transformers 4.36, this is a DynamicCache instance
85
+ seq_len += past_key_value.get_seq_length(model.layer_idx)
86
+
87
+ # model.rotary_emb is deprecated and will be removed in transformers > 4.47.0. Instead, the position embeddings are
88
+ # passed via the kwargs
89
+ if "position_embeddings" in kwargs:
90
+ cos, sin = kwargs["position_embeddings"]
91
+ cos = cos.unsqueeze(1)
92
+ sin = sin.unsqueeze(1)
93
+ return (query_states * cos) + (llama_rotate_half(query_states) * sin)
94
+
95
+ # For transformers > 4.37.2 `position_ids` became a required arguments in the rotary embedding's forward pass.
96
+ if "position_ids" not in inspect.signature(model.rotary_emb.forward).parameters:
97
+ # TODO we assume that position_ids is not None here, not sure if that is safe but the old code also did that
98
+ cos, sin = model.rotary_emb(value_states, seq_len=seq_len)
99
+ return llama_apply_rotary_pos_emb(query_states, cos, sin, position_ids)
100
+
101
+ past_seen_tokens = 0
102
+ if position_ids is None:
103
+ # Compute position_ids, since they are required for transformers > 4.37.2
104
+ if past_key_value is None:
105
+ new_cache_positions = torch.arange(q_len, q_len + q_len, device=value_states.device)
106
+ else:
107
+ past_seen_tokens = past_key_value.get_usable_length(q_len, model.layer_idx)
108
+ new_cache_positions = torch.arange(past_seen_tokens, past_seen_tokens + q_len, device=value_states.device)
109
+ position_ids = new_cache_positions.unsqueeze(0)
110
+
111
+ rotary_emb_kwargs = {"position_ids": position_ids}
112
+ # The `seq_len` argument has been officially removed in transformers >= 4.39.0
113
+ if "seq_len" in inspect.signature(model.rotary_emb.forward).parameters:
114
+ rotary_emb_kwargs["seq_len"] = q_len + past_seen_tokens
115
+
116
+ cos, sin = model.rotary_emb(value_states, **rotary_emb_kwargs)
117
+
118
+ # For batched inference unsqueeze it on the correct dim
119
+ # since: https://github.com/huggingface/transformers/pull/29109
120
+ if len(cos.shape) == 3:
121
+ cos = cos.unsqueeze(1)
122
+ sin = sin.unsqueeze(1)
123
+
124
+ return (query_states * cos) + (llama_rotate_half(query_states) * sin)
125
+
126
+
127
+ def gpt2_compute_query_states(
128
+ model: nn.Module,
129
+ hidden_states: Optional[tuple[torch.FloatTensor]],
130
+ encoder_hidden_states: Optional[torch.Tensor] = None,
131
+ ) -> torch.Tensor:
132
+ """
133
+ Compute query states for GPT2 models. They need to be recomputed as the forward() method of the GPT@ in the
134
+ transformers library does not return them. See the related discussion in the PR:
135
+ """
136
+ if encoder_hidden_states is not None:
137
+ if not hasattr(model, "q_attn"):
138
+ raise ValueError(
139
+ f"If `{model.__class__.__name__}` is used as cross attention, the weights `q_attn` must be defined. "
140
+ f"Please make sure to instantiate it with `GPT2Attention(..., is_cross_attention=True)`."
141
+ )
142
+ query_states = model.q_attn(hidden_states)
143
+ else:
144
+ query_states, _, _ = model.c_attn(hidden_states).split(model.split_size, dim=2)
145
+
146
+ shape_q = (*query_states.shape[:-1], -1, model.head_dim)
147
+ query_states = query_states.view(shape_q).transpose(1, 2)
148
+
149
+ return query_states
150
+
151
+
152
+ def is_adaption_prompt_trainable(params: str) -> bool:
153
+ """Return True if module is trainable under adaption prompt fine-tuning."""
154
+ return params.split(".")[-1].startswith("adaption_")
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/beft/__init__.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from peft.utils import register_peft_method
17
+
18
+ from .config import BeftConfig
19
+ from .layer import BeftLayer, Linear
20
+ from .model import BeftModel
21
+
22
+
23
+ __all__ = ["BeftConfig", "BeftLayer", "BeftModel", "Linear"]
24
+ register_peft_method(name="beft", config_cls=BeftConfig, model_cls=BeftModel, is_mixed_compatible=True)
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/beft/config.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ from dataclasses import dataclass, field
18
+ from typing import Optional, Union
19
+
20
+ from peft.config import PeftConfig
21
+ from peft.utils import PeftType
22
+
23
+
24
+ @dataclass
25
+ class BeftConfig(PeftConfig):
26
+ """
27
+ This is the configuration class to store the configuration of a [`BeftModel`].
28
+
29
+ Args:
30
+ target_modules (`Optional[Union[List[str], str]]`):
31
+ The names of the modules to apply the adapter to. If this is specified, only the modules with the specified
32
+ names will be replaced. When passing a string, a regex match will be performed. When passing a list of
33
+ strings, either an exact match will be performed or it is checked if the name of the module ends with any
34
+ of the passed strings. If this is not specified, modules will be chosen according to the model
35
+ architecture. If the architecture is not known, an error will be raised -- in this case, you should specify
36
+ the target modules manually.
37
+ modules_to_save (`Optional[List[str]]`):
38
+ List of modules apart from BEFT layers to be set as trainable and saved in the final checkpoint.
39
+ init_weights (`bool`):
40
+ Whether to initialize the vectors in the BEFT layers, defaults to `True`. Setting this to `False` is
41
+ discouraged.
42
+ """
43
+
44
+ target_modules: Optional[Union[list[str], str]] = field(
45
+ default=None,
46
+ metadata={
47
+ "help": (
48
+ "List of module names or regex expression of the module names to replace with BEFT."
49
+ "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'."
50
+ "If not specified, modules will be chosen according to the model architecture, If the architecture is "
51
+ "not known, an error will be raised -- in this case, you should specify the target modules manually."
52
+ ),
53
+ },
54
+ )
55
+ modules_to_save: Optional[list[str]] = field(
56
+ default=None,
57
+ metadata={
58
+ "help": "List of modules apart from BEFT layers to be set as trainable and saved in the final checkpoint. "
59
+ "For example, in Sequence Classification or Token Classification tasks, "
60
+ "the final layer `classifier/score` are randomly initialized and as such need to be trainable and saved."
61
+ },
62
+ )
63
+ init_weights: bool = field(
64
+ default=True,
65
+ metadata={"help": "Whether to initialize the vectors in the BEFT layers."},
66
+ )
67
+
68
+ def __post_init__(self):
69
+ super().__post_init__()
70
+ self.peft_type = PeftType.BEFT
71
+ self.target_modules = (
72
+ set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules
73
+ )
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/beft/layer.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import warnings
16
+ from typing import Any, Optional
17
+
18
+ import torch
19
+ from torch import nn
20
+
21
+ from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge
22
+
23
+ from .config import BeftConfig
24
+
25
+
26
+ class BeftLayer(BaseTunerLayer):
27
+ # All names of layers that may contain adapter weights
28
+ adapter_layer_names = ("beft_bias",)
29
+
30
+ def __init__(self, base_layer: nn.Module, **kwargs) -> None:
31
+ self.base_layer = base_layer
32
+ self.beft_bias = nn.ParameterDict({})
33
+ # Mark the weight as unmerged
34
+ self._disable_adapters = False
35
+ self.merged_adapters = []
36
+
37
+ base_layer = self.get_base_layer()
38
+ if isinstance(base_layer, nn.Linear):
39
+ in_features, out_features = base_layer.in_features, base_layer.out_features
40
+ else:
41
+ raise TypeError(f"Unsupported layer type {type(base_layer)}")
42
+ self.in_features = in_features
43
+ self.out_features = out_features
44
+
45
+ def update_layer(self, adapter_name: str, config: BeftConfig, **kwargs):
46
+ base_layer = self.get_base_layer()
47
+ if base_layer.bias is None:
48
+ warnings.warn(
49
+ "Detected that the base layer has no bias term. "
50
+ "Note you cannot merge the BEFT adapter into the base layer."
51
+ )
52
+ init_weights = config.init_weights
53
+ inference_mode = config.inference_mode
54
+ weight = torch.randn((1, self.out_features))
55
+ self.beft_bias[adapter_name] = nn.Parameter(weight)
56
+ if init_weights:
57
+ self.reset_beft_parameters(adapter_name)
58
+ self._move_adapter_to_device_of_base_layer(adapter_name)
59
+ self.set_adapter(self.active_adapters, inference_mode=inference_mode)
60
+
61
+ def reset_beft_parameters(self, adapter_name):
62
+ if adapter_name in self.beft_bias.keys():
63
+ nn.init.constant_(self.beft_bias[adapter_name], 0.0)
64
+
65
+
66
+ class Linear(nn.Module, BeftLayer):
67
+ # BEFT implemented in a dense layer
68
+ def __init__(
69
+ self,
70
+ base_layer: nn.Module,
71
+ adapter_name: str,
72
+ config: BeftConfig,
73
+ **kwargs,
74
+ ) -> None:
75
+ super().__init__()
76
+ BeftLayer.__init__(self, base_layer)
77
+ self._active_adapter = adapter_name
78
+ self.update_layer(adapter_name, config=config)
79
+
80
+ def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None:
81
+ """
82
+ Merge the active adapter bias into the base bias
83
+
84
+ Args:
85
+ safe_merge (`bool`, *optional*):
86
+ If True, the merge operation will be performed in a copy of the original bias and check for NaNs before
87
+ merging the bias. This is useful if you want to check if the merge operation will produce NaNs.
88
+ Defaults to `False`.
89
+ adapter_names (`List[str]`, *optional*):
90
+ The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults
91
+ to `None`.
92
+ """
93
+ adapter_names = check_adapters_to_merge(self, adapter_names)
94
+ if not adapter_names:
95
+ # no adapter to merge
96
+ return
97
+
98
+ for active_adapter in adapter_names:
99
+ if active_adapter in self.beft_bias.keys():
100
+ base_layer = self.get_base_layer()
101
+
102
+ if base_layer.bias is None:
103
+ raise ValueError(f"Base layer has no bias, cannot merge bias adapter {active_adapter}")
104
+
105
+ orig_dtype = base_layer.bias.data.dtype
106
+ beft_bias = self.beft_bias[active_adapter].data
107
+
108
+ if safe_merge:
109
+ output_bias = (base_layer.bias.data + beft_bias.squeeze()).clone()
110
+
111
+ if not torch.isfinite(output_bias).all():
112
+ raise ValueError(
113
+ f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken"
114
+ )
115
+
116
+ base_layer.bias.data = output_bias.to(orig_dtype)
117
+ else:
118
+ base_layer.bias.data.add_(beft_bias.squeeze()).to(orig_dtype)
119
+
120
+ self.merged_adapters.append(active_adapter)
121
+
122
+ def unmerge(self) -> None:
123
+ """
124
+ This method unmerges all merged adapter layers from the base bias.
125
+ """
126
+ if not self.merged:
127
+ warnings.warn("Already unmerged. Nothing to do.")
128
+ return
129
+
130
+ while len(self.merged_adapters) > 0:
131
+ active_adapter = self.merged_adapters.pop()
132
+ if active_adapter in self.beft_bias.keys():
133
+ base_layer = self.get_base_layer()
134
+
135
+ if base_layer.bias is None:
136
+ raise ValueError(f"Base layer has no bias, cannot unmerge bias adapter {active_adapter}")
137
+
138
+ orig_dtype = base_layer.bias.data.dtype
139
+ # minus BEFT bias.
140
+ beft_bias = self.beft_bias[active_adapter].data
141
+ base_layer.bias.data = (base_layer.bias.data - beft_bias.squeeze()).to(orig_dtype)
142
+
143
+ def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor:
144
+ if self.disable_adapters:
145
+ if self.merged:
146
+ self.unmerge()
147
+ result = self.base_layer(x, *args, **kwargs)
148
+ elif self.merged:
149
+ result = self.base_layer(x, *args, **kwargs)
150
+ else:
151
+ beft_bias = None
152
+ for active_adapter in self.active_adapters:
153
+ if active_adapter not in self.beft_bias.keys():
154
+ continue
155
+ current_bias = self.beft_bias[active_adapter].flatten()
156
+ if beft_bias is None:
157
+ beft_bias = current_bias
158
+ else:
159
+ beft_bias = beft_bias + current_bias
160
+
161
+ result = self.base_layer(x, *args, **kwargs)
162
+ if beft_bias is not None:
163
+ orig_dtype = result.dtype
164
+ result = (result + beft_bias).to(orig_dtype)
165
+
166
+ return result
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/beft/model.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from __future__ import annotations
15
+
16
+ import torch
17
+
18
+ from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer
19
+ from peft.utils import (
20
+ TRANSFORMERS_MODELS_TO_BEFT_TARGET_MODULES_MAPPING,
21
+ )
22
+
23
+ from .layer import BeftLayer, Linear
24
+
25
+
26
+ class BeftModel(BaseTuner):
27
+ """
28
+ Creates a Infused Adapter by only fine-tuning the added bias terms of value projections from a pretrained
29
+ transformers model in low-training-data regimes (BEFT). The method is described in detail in
30
+ https://arxiv.org/abs/2509.15974
31
+
32
+ Args:
33
+ model ([`~transformers.PreTrainedModel`]): The model to be adapted.
34
+ config ([`BeftConfig`]): The configuration of the (BEFT) model.
35
+ adapter_name (`str`): The name of the adapter, defaults to `"default"`.
36
+ low_cpu_mem_usage (`bool`, `optional`, defaults to `False`):
37
+ Create empty adapter weights on meta device. Useful to speed up the loading process.
38
+
39
+ Returns:
40
+ `torch.nn.Module`: The (BEFT) model.
41
+
42
+ Example:
43
+
44
+ ```py
45
+ >>> from transformers import AutoModelForSeq2SeqLM
46
+ >>> from peft import BeftModel, BeftConfig
47
+
48
+ >>> config = BeftConfig(
49
+ ... peft_type="Beft",
50
+ ... task_type="SEQ_2_SEQ_LM",
51
+ ... target_modules=["v"],
52
+ ... )
53
+
54
+ >>> model = AutoModelForSeq2SeqLM.from_pretrained("t5-base")
55
+ >>> beft_model = BeftModel(model, config, adapter_name="default")
56
+ ```
57
+
58
+ **Attributes**:
59
+ - **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted.
60
+ - **peft_config** ([`BeftConfig`]): The configuration of the (BEFT) model.
61
+ """
62
+
63
+ prefix: str = "beft_"
64
+ tuner_layer_cls = BeftLayer
65
+ target_module_mapping = TRANSFORMERS_MODELS_TO_BEFT_TARGET_MODULES_MAPPING
66
+
67
+ @staticmethod
68
+ def _create_new_module(beft_config, adapter_name, target, **kwargs):
69
+ if isinstance(target, BaseTunerLayer):
70
+ target_base_layer = target.get_base_layer()
71
+ else:
72
+ target_base_layer = target
73
+
74
+ if isinstance(target_base_layer, torch.nn.Linear):
75
+ new_module = Linear(target, adapter_name, config=beft_config, **kwargs)
76
+ else:
77
+ raise TypeError(
78
+ f"Target module {target} is not supported. Currently, only `torch.nn.Linear` is supported."
79
+ )
80
+ return new_module
81
+
82
+ def _create_and_replace(
83
+ self,
84
+ beft_config,
85
+ adapter_name,
86
+ target,
87
+ target_name,
88
+ parent,
89
+ current_key,
90
+ ):
91
+ kwargs = {}
92
+
93
+ if isinstance(target, BeftLayer):
94
+ target.update_layer(
95
+ adapter_name,
96
+ config=beft_config,
97
+ )
98
+ else:
99
+ new_module = self._create_new_module(beft_config, adapter_name, target, **kwargs)
100
+ if adapter_name not in self.active_adapters:
101
+ # adding an additional adapter: it is not automatically trainable
102
+ new_module.requires_grad_(False)
103
+ self._replace_module(parent, target_name, new_module, target)
tasks/tasksmith-749ff8d440e1/environment/source/src/peft/tuners/boft/__init__.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from peft.utils import register_peft_method
16
+
17
+ from .config import BOFTConfig
18
+ from .layer import BOFTLayer
19
+ from .model import BOFTModel
20
+
21
+
22
+ __all__ = ["BOFTConfig", "BOFTLayer", "BOFTModel"]
23
+
24
+ register_peft_method(name="boft", config_cls=BOFTConfig, model_cls=BOFTModel)