AdithyaSK HF Staff commited on
Commit
4ad161c
·
verified ·
1 Parent(s): b4cc8fe

Stage Harbor release files 72501-73000

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-c488fc138ba1/environment/source/examples/stable_diffusion/train_dreambooth.py +1275 -0
  2. tasks/tasksmith-c488fc138ba1/environment/source/examples/token_classification/peft_lora_ner.ipynb +554 -0
  3. tasks/tasksmith-c488fc138ba1/environment/source/examples/token_classification/peft_lora_token_cls.ipynb +0 -0
  4. tasks/tasksmith-c488fc138ba1/environment/source/examples/token_classification/requirements.txt +7 -0
  5. tasks/tasksmith-c488fc138ba1/environment/source/examples/waveft_finetuning/README.md +64 -0
  6. tasks/tasksmith-c488fc138ba1/environment/source/examples/waveft_finetuning/waveft_finetuning.py +189 -0
  7. tasks/tasksmith-c488fc138ba1/environment/source/examples/xlora/README.md +15 -0
  8. tasks/tasksmith-c488fc138ba1/environment/source/examples/xlora/xlora_inference_mistralrs.py +25 -0
  9. tasks/tasksmith-c488fc138ba1/environment/source/pyproject.toml +67 -0
  10. tasks/tasksmith-c488fc138ba1/environment/source/requirements.txt +15 -0
  11. tasks/tasksmith-c488fc138ba1/environment/source/scripts/ci_clean_cache.py +68 -0
  12. tasks/tasksmith-c488fc138ba1/environment/source/scripts/convert-bone-to-miss.py +69 -0
  13. tasks/tasksmith-c488fc138ba1/environment/source/scripts/evaluate-lora-conversion.py +156 -0
  14. tasks/tasksmith-c488fc138ba1/environment/source/scripts/generate_method_capabilities.py +769 -0
  15. tasks/tasksmith-c488fc138ba1/environment/source/scripts/launch_notebook_mp.py +47 -0
  16. tasks/tasksmith-c488fc138ba1/environment/source/scripts/log_reports.py +144 -0
  17. tasks/tasksmith-c488fc138ba1/environment/source/scripts/stale.py +65 -0
  18. tasks/tasksmith-c488fc138ba1/environment/source/scripts/train_memory.py +276 -0
  19. tasks/tasksmith-c488fc138ba1/environment/source/setup.py +117 -0
  20. tasks/tasksmith-c488fc138ba1/environment/source/src/peft/__init__.py +310 -0
  21. tasks/tasksmith-c488fc138ba1/environment/source/src/peft/auto.py +225 -0
  22. tasks/tasksmith-c488fc138ba1/environment/source/src/peft/config.py +408 -0
  23. tasks/tasksmith-c488fc138ba1/environment/source/src/peft/functional.py +34 -0
  24. tasks/tasksmith-c488fc138ba1/environment/source/src/peft/helpers.py +577 -0
  25. tasks/tasksmith-c488fc138ba1/environment/source/src/peft/import_utils.py +189 -0
  26. tasks/tasksmith-c488fc138ba1/environment/source/src/peft/mapping.py +92 -0
  27. tasks/tasksmith-c488fc138ba1/environment/source/src/peft/mapping_func.py +128 -0
  28. tasks/tasksmith-c488fc138ba1/environment/source/src/peft/mixed_model.py +473 -0
  29. tasks/tasksmith-c488fc138ba1/environment/source/src/peft/optimizers/__init__.py +19 -0
  30. tasks/tasksmith-c488fc138ba1/environment/source/src/peft/optimizers/lorafa.py +255 -0
  31. tasks/tasksmith-c488fc138ba1/environment/source/src/peft/optimizers/loraplus.py +121 -0
  32. tasks/tasksmith-c488fc138ba1/environment/source/src/peft/peft_model.py +0 -0
  33. tasks/tasksmith-c488fc138ba1/environment/source/src/peft/py.typed +0 -0
  34. tasks/tasksmith-c488fc138ba1/environment/source/src/peft/tuners/__init__.py +174 -0
  35. tasks/tasksmith-c488fc138ba1/environment/source/src/peft/tuners/_buffer_dict.py +159 -0
  36. tasks/tasksmith-c488fc138ba1/environment/source/src/peft/tuners/adalora/__init__.py +51 -0
  37. tasks/tasksmith-c488fc138ba1/environment/source/src/peft/tuners/adalora/bnb.py +142 -0
  38. tasks/tasksmith-c488fc138ba1/environment/source/src/peft/tuners/adalora/config.py +108 -0
  39. tasks/tasksmith-c488fc138ba1/environment/source/src/peft/tuners/adalora/gptq.py +71 -0
  40. tasks/tasksmith-c488fc138ba1/environment/source/src/peft/tuners/adalora/layer.py +515 -0
  41. tasks/tasksmith-c488fc138ba1/environment/source/src/peft/tuners/adalora/model.py +349 -0
  42. tasks/tasksmith-c488fc138ba1/environment/source/src/peft/tuners/adamss/__init__.py +32 -0
  43. tasks/tasksmith-c488fc138ba1/environment/source/src/peft/tuners/adamss/asa_callback.py +90 -0
  44. tasks/tasksmith-c488fc138ba1/environment/source/src/peft/tuners/adamss/config.py +349 -0
  45. tasks/tasksmith-c488fc138ba1/environment/source/src/peft/tuners/adamss/layer.py +668 -0
  46. tasks/tasksmith-c488fc138ba1/environment/source/src/peft/tuners/adamss/model.py +279 -0
  47. tasks/tasksmith-c488fc138ba1/environment/source/src/peft/tuners/adamss/utils.py +130 -0
  48. tasks/tasksmith-c488fc138ba1/environment/source/src/peft/tuners/adaption_prompt/__init__.py +23 -0
  49. tasks/tasksmith-c488fc138ba1/environment/source/src/peft/tuners/adaption_prompt/config.py +88 -0
  50. tasks/tasksmith-c488fc138ba1/environment/source/src/peft/tuners/adaption_prompt/layer.py +223 -0
tasks/tasksmith-c488fc138ba1/environment/source/examples/stable_diffusion/train_dreambooth.py ADDED
@@ -0,0 +1,1275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import gc
3
+ import hashlib
4
+ import itertools
5
+ import logging
6
+ import math
7
+ import os
8
+ import threading
9
+ import warnings
10
+ from pathlib import Path
11
+ from typing import Union
12
+
13
+ import datasets
14
+ import diffusers
15
+ import numpy as np
16
+ import psutil
17
+ import torch
18
+ import torch.nn.functional as F
19
+ import torch.utils.checkpoint
20
+ import transformers
21
+ from accelerate import Accelerator
22
+ from accelerate.logging import get_logger
23
+ from accelerate.utils import set_seed
24
+ from diffusers import (
25
+ AutoencoderKL,
26
+ DDPMScheduler,
27
+ DiffusionPipeline,
28
+ DPMSolverMultistepScheduler,
29
+ UNet2DConditionModel,
30
+ )
31
+ from diffusers.optimization import get_scheduler
32
+ from diffusers.utils import check_min_version
33
+ from diffusers.utils.import_utils import is_xformers_available
34
+ from huggingface_hub import HfApi
35
+ from PIL import Image
36
+ from torch.utils.data import Dataset
37
+ from torchvision import transforms
38
+ from tqdm.auto import tqdm
39
+ from transformers import AutoTokenizer, PretrainedConfig
40
+
41
+ from peft import LoHaConfig, LoKrConfig, LoraConfig, get_peft_model
42
+
43
+
44
+ # Will error if the minimal version of diffusers is not installed. Remove at your own risks.
45
+ check_min_version("0.10.0.dev0")
46
+
47
+ logger = get_logger(__name__)
48
+
49
+ UNET_TARGET_MODULES = [
50
+ "to_q",
51
+ "to_k",
52
+ "to_v",
53
+ "proj",
54
+ "proj_in",
55
+ "proj_out",
56
+ "conv",
57
+ "conv1",
58
+ "conv2",
59
+ "conv_shortcut",
60
+ "to_out.0",
61
+ "time_emb_proj",
62
+ "ff.net.2",
63
+ ]
64
+
65
+ TEXT_ENCODER_TARGET_MODULES = ["fc1", "fc2", "q_proj", "k_proj", "v_proj", "out_proj"]
66
+
67
+
68
+ def import_model_class_from_model_name_or_path(pretrained_model_name_or_path: str, revision: str):
69
+ text_encoder_config = PretrainedConfig.from_pretrained(
70
+ pretrained_model_name_or_path,
71
+ subfolder="text_encoder",
72
+ revision=revision,
73
+ )
74
+ model_class = text_encoder_config.architectures[0]
75
+
76
+ if model_class == "CLIPTextModel":
77
+ from transformers import CLIPTextModel
78
+
79
+ return CLIPTextModel
80
+ elif model_class == "RobertaSeriesModelWithTransformation":
81
+ from diffusers.pipelines.alt_diffusion.modeling_roberta_series import RobertaSeriesModelWithTransformation
82
+
83
+ return RobertaSeriesModelWithTransformation
84
+ else:
85
+ raise ValueError(f"{model_class} is not supported.")
86
+
87
+
88
+ def create_unet_adapter_config(args: argparse.Namespace) -> Union[LoraConfig, LoHaConfig, LoKrConfig]:
89
+ if args.adapter == "full":
90
+ raise ValueError("Cannot create unet adapter config for full parameter")
91
+
92
+ if args.adapter == "lora":
93
+ config = LoraConfig(
94
+ r=args.unet_r,
95
+ lora_alpha=args.unet_alpha,
96
+ target_modules=UNET_TARGET_MODULES,
97
+ lora_dropout=args.unet_dropout,
98
+ bias=args.unet_bias,
99
+ init_lora_weights=True,
100
+ )
101
+ elif args.adapter == "loha":
102
+ config = LoHaConfig(
103
+ r=args.unet_r,
104
+ alpha=args.unet_alpha,
105
+ target_modules=UNET_TARGET_MODULES,
106
+ rank_dropout=args.unet_rank_dropout,
107
+ module_dropout=args.unet_module_dropout,
108
+ use_effective_conv2d=args.unet_use_effective_conv2d,
109
+ init_weights=True,
110
+ )
111
+ elif args.adapter == "lokr":
112
+ config = LoKrConfig(
113
+ r=args.unet_r,
114
+ alpha=args.unet_alpha,
115
+ target_modules=UNET_TARGET_MODULES,
116
+ rank_dropout=args.unet_rank_dropout,
117
+ module_dropout=args.unet_module_dropout,
118
+ use_effective_conv2d=args.unet_use_effective_conv2d,
119
+ decompose_both=args.unet_decompose_both,
120
+ decompose_factor=args.unet_decompose_factor,
121
+ init_weights=True,
122
+ )
123
+ else:
124
+ raise ValueError(f"Unknown adapter type {args.adapter}")
125
+
126
+ return config
127
+
128
+
129
+ def create_text_encoder_adapter_config(args: argparse.Namespace) -> Union[LoraConfig, LoHaConfig, LoKrConfig]:
130
+ if args.adapter == "full":
131
+ raise ValueError("Cannot create text_encoder adapter config for full parameter")
132
+
133
+ if args.adapter == "lora":
134
+ config = LoraConfig(
135
+ r=args.te_r,
136
+ lora_alpha=args.te_alpha,
137
+ target_modules=TEXT_ENCODER_TARGET_MODULES,
138
+ lora_dropout=args.te_dropout,
139
+ bias=args.te_bias,
140
+ init_lora_weights=True,
141
+ )
142
+ elif args.adapter == "loha":
143
+ config = LoHaConfig(
144
+ r=args.te_r,
145
+ alpha=args.te_alpha,
146
+ target_modules=TEXT_ENCODER_TARGET_MODULES,
147
+ rank_dropout=args.te_rank_dropout,
148
+ module_dropout=args.te_module_dropout,
149
+ init_weights=True,
150
+ )
151
+ elif args.adapter == "lokr":
152
+ config = LoKrConfig(
153
+ r=args.te_r,
154
+ alpha=args.te_alpha,
155
+ target_modules=TEXT_ENCODER_TARGET_MODULES,
156
+ rank_dropout=args.te_rank_dropout,
157
+ module_dropout=args.te_module_dropout,
158
+ decompose_both=args.te_decompose_both,
159
+ decompose_factor=args.te_decompose_factor,
160
+ init_weights=True,
161
+ )
162
+ else:
163
+ raise ValueError(f"Unknown adapter type {args.adapter}")
164
+
165
+ return config
166
+
167
+
168
+ def parse_args(input_args=None):
169
+ parser = argparse.ArgumentParser(description="Simple example of a training script.")
170
+ parser.add_argument(
171
+ "--pretrained_model_name_or_path",
172
+ type=str,
173
+ default=None,
174
+ required=True,
175
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
176
+ )
177
+ parser.add_argument(
178
+ "--revision",
179
+ type=str,
180
+ default=None,
181
+ required=False,
182
+ help="Revision of pretrained model identifier from huggingface.co/models.",
183
+ )
184
+ parser.add_argument(
185
+ "--tokenizer_name",
186
+ type=str,
187
+ default=None,
188
+ help="Pretrained tokenizer name or path if not the same as model_name",
189
+ )
190
+ parser.add_argument(
191
+ "--instance_data_dir",
192
+ type=str,
193
+ default=None,
194
+ required=True,
195
+ help="A folder containing the training data of instance images.",
196
+ )
197
+ parser.add_argument(
198
+ "--class_data_dir",
199
+ type=str,
200
+ default=None,
201
+ required=False,
202
+ help="A folder containing the training data of class images.",
203
+ )
204
+ parser.add_argument(
205
+ "--instance_prompt",
206
+ type=str,
207
+ default=None,
208
+ required=True,
209
+ help="The prompt with identifier specifying the instance",
210
+ )
211
+ parser.add_argument(
212
+ "--class_prompt",
213
+ type=str,
214
+ default=None,
215
+ help="The prompt to specify images in the same class as provided instance images.",
216
+ )
217
+ parser.add_argument(
218
+ "--with_prior_preservation",
219
+ default=False,
220
+ action="store_true",
221
+ help="Flag to add prior preservation loss.",
222
+ )
223
+ parser.add_argument("--prior_loss_weight", type=float, default=1.0, help="The weight of prior preservation loss.")
224
+ parser.add_argument(
225
+ "--num_class_images",
226
+ type=int,
227
+ default=100,
228
+ help=(
229
+ "Minimal class images for prior preservation loss. If there are not enough images already present in"
230
+ " class_data_dir, additional images will be sampled with class_prompt."
231
+ ),
232
+ )
233
+ parser.add_argument(
234
+ "--validation_prompt",
235
+ type=str,
236
+ default=None,
237
+ help="A prompt that is used during validation to verify that the model is learning.",
238
+ )
239
+ parser.add_argument(
240
+ "--num_validation_images",
241
+ type=int,
242
+ default=4,
243
+ help="Number of images that should be generated during validation with `validation_prompt`.",
244
+ )
245
+ parser.add_argument(
246
+ "--validation_steps",
247
+ type=int,
248
+ default=100,
249
+ help=(
250
+ "Run dreambooth validation every X steps. Dreambooth validation consists of running the prompt"
251
+ " `args.validation_prompt` multiple times: `args.num_validation_images`."
252
+ ),
253
+ )
254
+ parser.add_argument(
255
+ "--output_dir",
256
+ type=str,
257
+ default="text-inversion-model",
258
+ help="The output directory where the model predictions and checkpoints will be written.",
259
+ )
260
+ parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
261
+ parser.add_argument(
262
+ "--resolution",
263
+ type=int,
264
+ default=512,
265
+ help=(
266
+ "The resolution for input images, all the images in the train/validation dataset will be resized to this"
267
+ " resolution"
268
+ ),
269
+ )
270
+ parser.add_argument(
271
+ "--center_crop", action="store_true", help="Whether to center crop images before resizing to resolution"
272
+ )
273
+ parser.add_argument("--train_text_encoder", action="store_true", help="Whether to train the text encoder")
274
+
275
+ parser.add_argument(
276
+ "--train_batch_size", type=int, default=4, help="Batch size (per device) for the training dataloader."
277
+ )
278
+ parser.add_argument(
279
+ "--sample_batch_size", type=int, default=4, help="Batch size (per device) for sampling images."
280
+ )
281
+ parser.add_argument("--num_train_epochs", type=int, default=1)
282
+ parser.add_argument(
283
+ "--max_train_steps",
284
+ type=int,
285
+ default=None,
286
+ help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
287
+ )
288
+ parser.add_argument(
289
+ "--checkpointing_steps",
290
+ type=int,
291
+ default=500,
292
+ help=(
293
+ "Save a checkpoint of the training state every X updates. These checkpoints can be used both as final"
294
+ " checkpoints in case they are better than the last checkpoint, and are also suitable for resuming"
295
+ " training using `--resume_from_checkpoint`."
296
+ ),
297
+ )
298
+ parser.add_argument(
299
+ "--resume_from_checkpoint",
300
+ type=str,
301
+ default=None,
302
+ help=(
303
+ "Whether training should be resumed from a previous checkpoint. Use a path saved by"
304
+ ' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
305
+ ),
306
+ )
307
+ parser.add_argument(
308
+ "--gradient_accumulation_steps",
309
+ type=int,
310
+ default=1,
311
+ help="Number of updates steps to accumulate before performing a backward/update pass.",
312
+ )
313
+ parser.add_argument(
314
+ "--gradient_checkpointing",
315
+ action="store_true",
316
+ help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
317
+ )
318
+ parser.add_argument(
319
+ "--learning_rate",
320
+ type=float,
321
+ default=5e-6,
322
+ help="Initial learning rate (after the potential warmup period) to use.",
323
+ )
324
+ parser.add_argument(
325
+ "--scale_lr",
326
+ action="store_true",
327
+ default=False,
328
+ help="Scale the learning rate by the number of accelerators, gradient accumulation steps, and batch size.",
329
+ )
330
+ parser.add_argument(
331
+ "--lr_scheduler",
332
+ type=str,
333
+ default="constant",
334
+ help=(
335
+ 'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
336
+ ' "constant", "constant_with_warmup"]'
337
+ ),
338
+ )
339
+ parser.add_argument(
340
+ "--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
341
+ )
342
+ parser.add_argument(
343
+ "--lr_num_cycles",
344
+ type=int,
345
+ default=1,
346
+ help="Number of hard resets of the lr in cosine_with_restarts scheduler.",
347
+ )
348
+ parser.add_argument("--lr_power", type=float, default=1.0, help="Power factor of the polynomial scheduler.")
349
+ parser.add_argument(
350
+ "--use_8bit_adam", action="store_true", help="Whether or not to use 8-bit Adam from bitsandbytes."
351
+ )
352
+ parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
353
+ parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
354
+ parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
355
+ parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
356
+ parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
357
+ parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
358
+ parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
359
+ parser.add_argument(
360
+ "--hub_model_id",
361
+ type=str,
362
+ default=None,
363
+ help="The name of the repository to keep in sync with the local `output_dir`.",
364
+ )
365
+ parser.add_argument(
366
+ "--logging_dir",
367
+ type=str,
368
+ default="logs",
369
+ help=(
370
+ "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
371
+ " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
372
+ ),
373
+ )
374
+ parser.add_argument(
375
+ "--allow_tf32",
376
+ action="store_true",
377
+ help=(
378
+ "Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
379
+ " https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
380
+ ),
381
+ )
382
+ parser.add_argument(
383
+ "--report_to",
384
+ type=str,
385
+ default="tensorboard",
386
+ help=(
387
+ 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
388
+ ' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
389
+ ),
390
+ )
391
+ parser.add_argument(
392
+ "--wandb_key",
393
+ type=str,
394
+ default=None,
395
+ help=("If report to option is set to wandb, api-key for wandb used for login to wandb "),
396
+ )
397
+ parser.add_argument(
398
+ "--wandb_project_name",
399
+ type=str,
400
+ default=None,
401
+ help=("If report to option is set to wandb, project name in wandb for log tracking "),
402
+ )
403
+ parser.add_argument(
404
+ "--mixed_precision",
405
+ type=str,
406
+ default=None,
407
+ choices=["no", "fp16", "bf16"],
408
+ help=(
409
+ "Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
410
+ " 1.10. and an Nvidia Ampere GPU or Intel XPU. Default to the value of accelerate config of the current system or the"
411
+ " flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
412
+ ),
413
+ )
414
+ parser.add_argument(
415
+ "--prior_generation_precision",
416
+ type=str,
417
+ default=None,
418
+ choices=["no", "fp32", "fp16", "bf16"],
419
+ help=(
420
+ "Choose prior generation precision between fp32, fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
421
+ " 1.10. and an Nvidia Ampere GPU or Intel XPU. Default to fp16 if an accelerator is available else fp32."
422
+ ),
423
+ )
424
+ parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
425
+ parser.add_argument(
426
+ "--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
427
+ )
428
+
429
+ # Adapter arguments
430
+ subparsers = parser.add_subparsers(dest="adapter")
431
+
432
+ # Dummy subparser to train whole model
433
+ subparsers.add_parser("full", help="Train full model without adapters")
434
+
435
+ # LoRA adapter
436
+ lora = subparsers.add_parser("lora", help="Use LoRA adapter")
437
+ lora.add_argument("--unet_r", type=int, default=8, help="LoRA rank for unet")
438
+ lora.add_argument("--unet_alpha", type=int, default=8, help="LoRA alpha for unet")
439
+ lora.add_argument("--unet_dropout", type=float, default=0.0, help="LoRA dropout probability for unet")
440
+ lora.add_argument(
441
+ "--unet_bias",
442
+ type=str,
443
+ default="none",
444
+ help="Bias type for LoRA. Can be 'none', 'all' or 'lora_only'",
445
+ )
446
+ lora.add_argument(
447
+ "--te_r", type=int, default=8, help="LoRA rank for text_encoder, only used if `train_text_encoder` is True"
448
+ )
449
+ lora.add_argument(
450
+ "--te_alpha",
451
+ type=int,
452
+ default=8,
453
+ help="LoRA alpha for text_encoder, only used if `train_text_encoder` is True",
454
+ )
455
+ lora.add_argument(
456
+ "--te_dropout",
457
+ type=float,
458
+ default=0.0,
459
+ help="LoRA dropout probability for text_encoder, only used if `train_text_encoder` is True",
460
+ )
461
+ lora.add_argument(
462
+ "--te_bias",
463
+ type=str,
464
+ default="none",
465
+ help="Bias type for LoRA. Can be 'none', 'all' or 'lora_only', only used if `train_text_encoder` is True",
466
+ )
467
+
468
+ # LoHa adapter
469
+ loha = subparsers.add_parser("loha", help="Use LoHa adapter")
470
+ loha.add_argument("--unet_r", type=int, default=8, help="LoHa rank for unet")
471
+ loha.add_argument("--unet_alpha", type=int, default=8, help="LoHa alpha for unet")
472
+ loha.add_argument("--unet_rank_dropout", type=float, default=0.0, help="LoHa rank_dropout probability for unet")
473
+ loha.add_argument(
474
+ "--unet_module_dropout", type=float, default=0.0, help="LoHa module_dropout probability for unet"
475
+ )
476
+ loha.add_argument(
477
+ "--unet_use_effective_conv2d",
478
+ action="store_true",
479
+ help="Use parameter effective decomposition in unet for Conv2d 3x3 with ksize > 1",
480
+ )
481
+ loha.add_argument(
482
+ "--te_r", type=int, default=8, help="LoHa rank for text_encoder, only used if `train_text_encoder` is True"
483
+ )
484
+ loha.add_argument(
485
+ "--te_alpha",
486
+ type=int,
487
+ default=8,
488
+ help="LoHa alpha for text_encoder, only used if `train_text_encoder` is True",
489
+ )
490
+ loha.add_argument(
491
+ "--te_rank_dropout",
492
+ type=float,
493
+ default=0.0,
494
+ help="LoHa rank_dropout probability for text_encoder, only used if `train_text_encoder` is True",
495
+ )
496
+ loha.add_argument(
497
+ "--te_module_dropout",
498
+ type=float,
499
+ default=0.0,
500
+ help="LoHa module_dropout probability for text_encoder, only used if `train_text_encoder` is True",
501
+ )
502
+
503
+ # LoKr adapter
504
+ lokr = subparsers.add_parser("lokr", help="Use LoKr adapter")
505
+ lokr.add_argument("--unet_r", type=int, default=8, help="LoKr rank for unet")
506
+ lokr.add_argument("--unet_alpha", type=int, default=8, help="LoKr alpha for unet")
507
+ lokr.add_argument("--unet_rank_dropout", type=float, default=0.0, help="LoKr rank_dropout probability for unet")
508
+ lokr.add_argument(
509
+ "--unet_module_dropout", type=float, default=0.0, help="LoKr module_dropout probability for unet"
510
+ )
511
+ lokr.add_argument(
512
+ "--unet_use_effective_conv2d",
513
+ action="store_true",
514
+ help="Use parameter effective decomposition in unet for Conv2d 3x3 with ksize > 1",
515
+ )
516
+ lokr.add_argument(
517
+ "--unet_decompose_both", action="store_true", help="Decompose left matrix in kronecker product for unet"
518
+ )
519
+ lokr.add_argument(
520
+ "--unet_decompose_factor", type=int, default=-1, help="Decompose factor in kronecker product for unet"
521
+ )
522
+ lokr.add_argument(
523
+ "--te_r", type=int, default=8, help="LoKr rank for text_encoder, only used if `train_text_encoder` is True"
524
+ )
525
+ lokr.add_argument(
526
+ "--te_alpha",
527
+ type=int,
528
+ default=8,
529
+ help="LoKr alpha for text_encoder, only used if `train_text_encoder` is True",
530
+ )
531
+ lokr.add_argument(
532
+ "--te_rank_dropout",
533
+ type=float,
534
+ default=0.0,
535
+ help="LoKr rank_dropout probability for text_encoder, only used if `train_text_encoder` is True",
536
+ )
537
+ lokr.add_argument(
538
+ "--te_module_dropout",
539
+ type=float,
540
+ default=0.0,
541
+ help="LoKr module_dropout probability for text_encoder, only used if `train_text_encoder` is True",
542
+ )
543
+ lokr.add_argument(
544
+ "--te_decompose_both",
545
+ action="store_true",
546
+ help="Decompose left matrix in kronecker product for text_encoder, only used if `train_text_encoder` is True",
547
+ )
548
+ lokr.add_argument(
549
+ "--te_decompose_factor",
550
+ type=int,
551
+ default=-1,
552
+ help="Decompose factor in kronecker product for text_encoder, only used if `train_text_encoder` is True",
553
+ )
554
+
555
+ if input_args is not None:
556
+ args = parser.parse_args(input_args)
557
+ else:
558
+ args = parser.parse_args()
559
+
560
+ env_local_rank = int(os.environ.get("LOCAL_RANK", "-1"))
561
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
562
+ args.local_rank = env_local_rank
563
+
564
+ if args.with_prior_preservation:
565
+ if args.class_data_dir is None:
566
+ raise ValueError("You must specify a data directory for class images.")
567
+ if args.class_prompt is None:
568
+ raise ValueError("You must specify prompt for class images.")
569
+ else:
570
+ # logger is not available yet
571
+ if args.class_data_dir is not None:
572
+ warnings.warn("You need not use --class_data_dir without --with_prior_preservation.")
573
+ if args.class_prompt is not None:
574
+ warnings.warn("You need not use --class_prompt without --with_prior_preservation.")
575
+
576
+ return args
577
+
578
+
579
+ # Converting Bytes to Megabytes
580
+ def b2mb(x):
581
+ return int(x / 2**20)
582
+
583
+
584
+ # This context manager is used to track the peak memory usage of the process
585
+ class TorchTracemalloc:
586
+ def __enter__(self):
587
+ gc.collect()
588
+ self.device_type = torch.accelerator.current_accelerator().type if hasattr(torch, "accelerator") else "cuda"
589
+ self.device_module = getattr(torch, self.device_type, torch.cuda)
590
+ self.device_module.empty_cache()
591
+ self.device_module.reset_peak_memory_stats() # reset the peak gauge to zero
592
+ self.begin = self.device_module.memory_allocated()
593
+ self.process = psutil.Process()
594
+
595
+ self.cpu_begin = self.cpu_mem_used()
596
+ self.peak_monitoring = True
597
+ peak_monitor_thread = threading.Thread(target=self.peak_monitor_func)
598
+ peak_monitor_thread.daemon = True
599
+ peak_monitor_thread.start()
600
+ return self
601
+
602
+ def cpu_mem_used(self):
603
+ """get resident set size memory for the current process"""
604
+ return self.process.memory_info().rss
605
+
606
+ def peak_monitor_func(self):
607
+ self.cpu_peak = -1
608
+
609
+ while True:
610
+ self.cpu_peak = max(self.cpu_mem_used(), self.cpu_peak)
611
+
612
+ # can't sleep or will not catch the peak right (this comment is here on purpose)
613
+ # time.sleep(0.001) # 1msec
614
+
615
+ if not self.peak_monitoring:
616
+ break
617
+
618
+ def __exit__(self, *exc):
619
+ self.peak_monitoring = False
620
+
621
+ gc.collect()
622
+ self.device_module.empty_cache()
623
+ self.end = self.device_module.memory_allocated()
624
+ self.peak = self.device_module.max_memory_allocated()
625
+ self.used = b2mb(self.end - self.begin)
626
+ self.peaked = b2mb(self.peak - self.begin)
627
+
628
+ self.cpu_end = self.cpu_mem_used()
629
+ self.cpu_used = b2mb(self.cpu_end - self.cpu_begin)
630
+ self.cpu_peaked = b2mb(self.cpu_peak - self.cpu_begin)
631
+ # print(f"delta used/peak {self.used:4d}/{self.peaked:4d}")
632
+
633
+
634
+ class DreamBoothDataset(Dataset):
635
+ """
636
+ A dataset to prepare the instance and class images with the prompts for fine-tuning the model.
637
+ It pre-processes the images and the tokenizes prompts.
638
+ """
639
+
640
+ def __init__(
641
+ self,
642
+ instance_data_root,
643
+ instance_prompt,
644
+ tokenizer,
645
+ class_data_root=None,
646
+ class_prompt=None,
647
+ size=512,
648
+ center_crop=False,
649
+ ):
650
+ self.size = size
651
+ self.center_crop = center_crop
652
+ self.tokenizer = tokenizer
653
+
654
+ self.instance_data_root = Path(instance_data_root)
655
+ if not self.instance_data_root.exists():
656
+ raise ValueError("Instance images root doesn't exists.")
657
+
658
+ self.instance_images_path = list(Path(instance_data_root).iterdir())
659
+ self.num_instance_images = len(self.instance_images_path)
660
+ self.instance_prompt = instance_prompt
661
+ self._length = self.num_instance_images
662
+
663
+ if class_data_root is not None:
664
+ self.class_data_root = Path(class_data_root)
665
+ self.class_data_root.mkdir(parents=True, exist_ok=True)
666
+ self.class_images_path = list(self.class_data_root.iterdir())
667
+ self.num_class_images = len(self.class_images_path)
668
+ self._length = max(self.num_class_images, self.num_instance_images)
669
+ self.class_prompt = class_prompt
670
+ else:
671
+ self.class_data_root = None
672
+
673
+ self.image_transforms = transforms.Compose(
674
+ [
675
+ transforms.Resize(size, interpolation=transforms.InterpolationMode.BILINEAR),
676
+ transforms.CenterCrop(size) if center_crop else transforms.RandomCrop(size),
677
+ transforms.ToTensor(),
678
+ transforms.Normalize([0.5], [0.5]),
679
+ ]
680
+ )
681
+
682
+ def __len__(self):
683
+ return self._length
684
+
685
+ def __getitem__(self, index):
686
+ example = {}
687
+ instance_image = Image.open(self.instance_images_path[index % self.num_instance_images])
688
+ if instance_image.mode != "RGB":
689
+ instance_image = instance_image.convert("RGB")
690
+ example["instance_images"] = self.image_transforms(instance_image)
691
+ example["instance_prompt_ids"] = self.tokenizer(
692
+ self.instance_prompt,
693
+ truncation=True,
694
+ padding="max_length",
695
+ max_length=self.tokenizer.model_max_length,
696
+ return_tensors="pt",
697
+ ).input_ids
698
+
699
+ if self.class_data_root:
700
+ class_image = Image.open(self.class_images_path[index % self.num_class_images])
701
+ if class_image.mode != "RGB":
702
+ class_image = class_image.convert("RGB")
703
+ example["class_images"] = self.image_transforms(class_image)
704
+ example["class_prompt_ids"] = self.tokenizer(
705
+ self.class_prompt,
706
+ truncation=True,
707
+ padding="max_length",
708
+ max_length=self.tokenizer.model_max_length,
709
+ return_tensors="pt",
710
+ ).input_ids
711
+
712
+ return example
713
+
714
+
715
+ def collate_fn(examples, with_prior_preservation=False):
716
+ input_ids = [example["instance_prompt_ids"] for example in examples]
717
+ pixel_values = [example["instance_images"] for example in examples]
718
+
719
+ # Concat class and instance examples for prior preservation.
720
+ # We do this to avoid doing two forward passes.
721
+ if with_prior_preservation:
722
+ input_ids += [example["class_prompt_ids"] for example in examples]
723
+ pixel_values += [example["class_images"] for example in examples]
724
+
725
+ pixel_values = torch.stack(pixel_values)
726
+ pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float()
727
+
728
+ input_ids = torch.cat(input_ids, dim=0)
729
+
730
+ batch = {
731
+ "input_ids": input_ids,
732
+ "pixel_values": pixel_values,
733
+ }
734
+ return batch
735
+
736
+
737
+ class PromptDataset(Dataset):
738
+ "A simple dataset to prepare the prompts to generate class images on multiple accelerators."
739
+
740
+ def __init__(self, prompt, num_samples):
741
+ self.prompt = prompt
742
+ self.num_samples = num_samples
743
+
744
+ def __len__(self):
745
+ return self.num_samples
746
+
747
+ def __getitem__(self, index):
748
+ example = {}
749
+ example["prompt"] = self.prompt
750
+ example["index"] = index
751
+ return example
752
+
753
+
754
+ def main(args):
755
+ logging_dir = Path(args.output_dir, args.logging_dir)
756
+
757
+ accelerator = Accelerator(
758
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
759
+ mixed_precision=args.mixed_precision,
760
+ log_with=args.report_to,
761
+ project_dir=logging_dir,
762
+ )
763
+ if args.report_to == "wandb":
764
+ import wandb
765
+
766
+ wandb.login(key=args.wandb_key)
767
+ wandb.init(project=args.wandb_project_name)
768
+ # Currently, it's not possible to do gradient accumulation when training two models with accelerate.accumulate
769
+ # This will be enabled soon in accelerate. For now, we don't allow gradient accumulation when training two models.
770
+ # TODO (patil-suraj): Remove this check when gradient accumulation with two models is enabled in accelerate.
771
+ if args.train_text_encoder and args.gradient_accumulation_steps > 1 and accelerator.num_processes > 1:
772
+ raise ValueError(
773
+ "Gradient accumulation is not supported when training the text encoder in distributed training. "
774
+ "Please set gradient_accumulation_steps to 1. This feature will be supported in the future."
775
+ )
776
+
777
+ # Make one log on every process with the configuration for debugging.
778
+ logging.basicConfig(
779
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
780
+ datefmt="%m/%d/%Y %H:%M:%S",
781
+ level=logging.INFO,
782
+ )
783
+ logger.info(accelerator.state, main_process_only=False)
784
+ if accelerator.is_local_main_process:
785
+ datasets.utils.logging.set_verbosity_warning()
786
+ transformers.utils.logging.set_verbosity_warning()
787
+ diffusers.utils.logging.set_verbosity_info()
788
+ else:
789
+ datasets.utils.logging.set_verbosity_error()
790
+ transformers.utils.logging.set_verbosity_error()
791
+ diffusers.utils.logging.set_verbosity_error()
792
+
793
+ # If passed along, set the training seed now.
794
+ if args.seed is not None:
795
+ set_seed(args.seed)
796
+
797
+ # Generate class images if prior preservation is enabled.
798
+ if args.with_prior_preservation:
799
+ class_images_dir = Path(args.class_data_dir)
800
+ if not class_images_dir.exists():
801
+ class_images_dir.mkdir(parents=True)
802
+ cur_class_images = len(list(class_images_dir.iterdir()))
803
+
804
+ if cur_class_images < args.num_class_images:
805
+ dtype = torch.float16 if accelerator.device.type in ["cuda", "xpu"] else torch.float32
806
+ if args.prior_generation_precision == "fp32":
807
+ dtype = torch.float32
808
+ elif args.prior_generation_precision == "fp16":
809
+ dtype = torch.float16
810
+ elif args.prior_generation_precision == "bf16":
811
+ dtype = torch.bfloat16
812
+ pipeline = DiffusionPipeline.from_pretrained(
813
+ args.pretrained_model_name_or_path,
814
+ dtype=dtype,
815
+ safety_checker=None,
816
+ revision=args.revision,
817
+ )
818
+ pipeline.set_progress_bar_config(disable=True)
819
+
820
+ num_new_images = args.num_class_images - cur_class_images
821
+ logger.info(f"Number of class images to sample: {num_new_images}.")
822
+
823
+ sample_dataset = PromptDataset(args.class_prompt, num_new_images)
824
+ sample_dataloader = torch.utils.data.DataLoader(sample_dataset, batch_size=args.sample_batch_size)
825
+
826
+ sample_dataloader = accelerator.prepare(sample_dataloader)
827
+ pipeline.to(accelerator.device)
828
+
829
+ for example in tqdm(
830
+ sample_dataloader, desc="Generating class images", disable=not accelerator.is_local_main_process
831
+ ):
832
+ images = pipeline(example["prompt"]).images
833
+
834
+ for i, image in enumerate(images):
835
+ hash_image = hashlib.sha1(image.tobytes()).hexdigest()
836
+ image_filename = class_images_dir / f"{example['index'][i] + cur_class_images}-{hash_image}.jpg"
837
+ image.save(image_filename)
838
+
839
+ del pipeline
840
+
841
+ if torch.cuda.is_available():
842
+ torch.cuda.empty_cache()
843
+ elif torch.xpu.is_available():
844
+ torch.xpu.empty_cache()
845
+
846
+ # Handle the repository creation
847
+ if accelerator.is_main_process:
848
+ if args.push_to_hub:
849
+ api = HfApi(token=args.hub_token)
850
+
851
+ # Create repo (repo_name from args or inferred)
852
+ repo_name = args.hub_model_id
853
+ if repo_name is None:
854
+ repo_name = Path(args.output_dir).absolute().name
855
+ repo_id = api.create_repo(repo_name, exist_ok=True).repo_id
856
+
857
+ with open(os.path.join(args.output_dir, ".gitignore"), "w+") as gitignore:
858
+ if "step_*" not in gitignore:
859
+ gitignore.write("step_*\n")
860
+ if "epoch_*" not in gitignore:
861
+ gitignore.write("epoch_*\n")
862
+ elif args.output_dir is not None:
863
+ os.makedirs(args.output_dir, exist_ok=True)
864
+
865
+ # Load the tokenizer
866
+ if args.tokenizer_name:
867
+ tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name, revision=args.revision, use_fast=False)
868
+ elif args.pretrained_model_name_or_path:
869
+ tokenizer = AutoTokenizer.from_pretrained(
870
+ args.pretrained_model_name_or_path,
871
+ subfolder="tokenizer",
872
+ revision=args.revision,
873
+ use_fast=False,
874
+ )
875
+
876
+ # import correct text encoder class
877
+ text_encoder_cls = import_model_class_from_model_name_or_path(args.pretrained_model_name_or_path, args.revision)
878
+
879
+ # Load scheduler and models
880
+ noise_scheduler = DDPMScheduler(
881
+ beta_start=0.00085,
882
+ beta_end=0.012,
883
+ beta_schedule="scaled_linear",
884
+ num_train_timesteps=1000,
885
+ ) # DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
886
+ text_encoder = text_encoder_cls.from_pretrained(
887
+ args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision
888
+ )
889
+ vae = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae", revision=args.revision)
890
+ unet = UNet2DConditionModel.from_pretrained(
891
+ args.pretrained_model_name_or_path, subfolder="unet", revision=args.revision
892
+ )
893
+
894
+ if args.adapter != "full":
895
+ config = create_unet_adapter_config(args)
896
+ unet = get_peft_model(unet, config)
897
+ unet.print_trainable_parameters()
898
+ print(unet)
899
+
900
+ vae.requires_grad_(False)
901
+ if not args.train_text_encoder:
902
+ text_encoder.requires_grad_(False)
903
+ elif args.train_text_encoder and args.adapter != "full":
904
+ config = create_text_encoder_adapter_config(args)
905
+ text_encoder = get_peft_model(text_encoder, config)
906
+ text_encoder.print_trainable_parameters()
907
+ print(text_encoder)
908
+
909
+ if args.enable_xformers_memory_efficient_attention:
910
+ if accelerator.device.type == "xpu":
911
+ logger.warning("XPU hasn't support xformers yet, ignore it.")
912
+ elif is_xformers_available():
913
+ unet.enable_xformers_memory_efficient_attention()
914
+ else:
915
+ raise ValueError("xformers is not available. Make sure it is installed correctly")
916
+
917
+ if args.gradient_checkpointing:
918
+ unet.enable_gradient_checkpointing()
919
+ if args.train_text_encoder and args.adapter == "full":
920
+ text_encoder.gradient_checkpointing_enable()
921
+
922
+ # Enable TF32 for faster training on Ampere GPUs,
923
+ # cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
924
+ if args.allow_tf32 and torch.cuda.is_available():
925
+ torch.backends.cuda.matmul.allow_tf32 = True
926
+
927
+ if args.scale_lr:
928
+ args.learning_rate = (
929
+ args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
930
+ )
931
+
932
+ # Use 8-bit Adam for lower memory usage or to fine-tune the model in 16GB accelerators
933
+ if args.use_8bit_adam:
934
+ try:
935
+ import bitsandbytes as bnb
936
+ except ImportError:
937
+ raise ImportError(
938
+ "To use 8-bit Adam, please install the bitsandbytes library: `pip install bitsandbytes`."
939
+ )
940
+
941
+ optimizer_class = bnb.optim.AdamW8bit
942
+ else:
943
+ optimizer_class = torch.optim.AdamW
944
+
945
+ # Optimizer creation
946
+ params_to_optimize = (
947
+ itertools.chain(unet.parameters(), text_encoder.parameters()) if args.train_text_encoder else unet.parameters()
948
+ )
949
+ optimizer = optimizer_class(
950
+ params_to_optimize,
951
+ lr=args.learning_rate,
952
+ betas=(args.adam_beta1, args.adam_beta2),
953
+ weight_decay=args.adam_weight_decay,
954
+ eps=args.adam_epsilon,
955
+ )
956
+
957
+ # Dataset and DataLoaders creation:
958
+ train_dataset = DreamBoothDataset(
959
+ instance_data_root=args.instance_data_dir,
960
+ instance_prompt=args.instance_prompt,
961
+ class_data_root=args.class_data_dir if args.with_prior_preservation else None,
962
+ class_prompt=args.class_prompt,
963
+ tokenizer=tokenizer,
964
+ size=args.resolution,
965
+ center_crop=args.center_crop,
966
+ )
967
+
968
+ train_dataloader = torch.utils.data.DataLoader(
969
+ train_dataset,
970
+ batch_size=args.train_batch_size,
971
+ shuffle=True,
972
+ collate_fn=lambda examples: collate_fn(examples, args.with_prior_preservation),
973
+ num_workers=1,
974
+ )
975
+
976
+ # Scheduler and math around the number of training steps.
977
+ overrode_max_train_steps = False
978
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
979
+ if args.max_train_steps is None:
980
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
981
+ overrode_max_train_steps = True
982
+
983
+ lr_scheduler = get_scheduler(
984
+ args.lr_scheduler,
985
+ optimizer=optimizer,
986
+ num_warmup_steps=args.lr_warmup_steps * args.gradient_accumulation_steps,
987
+ num_training_steps=args.max_train_steps * args.gradient_accumulation_steps,
988
+ num_cycles=args.lr_num_cycles,
989
+ power=args.lr_power,
990
+ )
991
+
992
+ # Prepare everything with our `accelerator`.
993
+ if args.train_text_encoder:
994
+ unet, text_encoder, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
995
+ unet, text_encoder, optimizer, train_dataloader, lr_scheduler
996
+ )
997
+ else:
998
+ unet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
999
+ unet, optimizer, train_dataloader, lr_scheduler
1000
+ )
1001
+
1002
+ # For mixed precision training we cast the text_encoder and vae weights to half-precision
1003
+ # as these models are only used for inference, keeping weights in full precision is not required.
1004
+ weight_dtype = torch.float32
1005
+ if accelerator.mixed_precision == "fp16":
1006
+ weight_dtype = torch.float16
1007
+ elif accelerator.mixed_precision == "bf16":
1008
+ weight_dtype = torch.bfloat16
1009
+
1010
+ # Move vae and text_encoder to device and cast to weight_dtype
1011
+ vae.to(accelerator.device, dtype=weight_dtype)
1012
+ if not args.train_text_encoder:
1013
+ text_encoder.to(accelerator.device, dtype=weight_dtype)
1014
+
1015
+ # We need to recalculate our total training steps as the size of the training dataloader may have changed.
1016
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
1017
+ if overrode_max_train_steps:
1018
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
1019
+ # Afterwards we recalculate our number of training epochs
1020
+ args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
1021
+
1022
+ # We need to initialize the trackers we use, and also store our configuration.
1023
+ # The trackers initializes automatically on the main process.
1024
+ if accelerator.is_main_process:
1025
+ accelerator.init_trackers("dreambooth", config=vars(args))
1026
+
1027
+ # Train!
1028
+ total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
1029
+
1030
+ logger.info("***** Running training *****")
1031
+ logger.info(f" Num examples = {len(train_dataset)}")
1032
+ logger.info(f" Num batches each epoch = {len(train_dataloader)}")
1033
+ logger.info(f" Num Epochs = {args.num_train_epochs}")
1034
+ logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
1035
+ logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
1036
+ logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
1037
+ logger.info(f" Total optimization steps = {args.max_train_steps}")
1038
+ global_step = 0
1039
+ first_epoch = 0
1040
+
1041
+ # Potentially load in the weights and states from a previous save
1042
+ if args.resume_from_checkpoint:
1043
+ if args.resume_from_checkpoint != "latest":
1044
+ path = os.path.basename(args.resume_from_checkpoint)
1045
+ else:
1046
+ # Get the mos recent checkpoint
1047
+ dirs = os.listdir(args.output_dir)
1048
+ dirs = [d for d in dirs if d.startswith("checkpoint")]
1049
+ dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
1050
+ path = dirs[-1]
1051
+ accelerator.print(f"Resuming from checkpoint {path}")
1052
+ accelerator.load_state(os.path.join(args.output_dir, path))
1053
+ global_step = int(path.split("-")[1])
1054
+
1055
+ resume_global_step = global_step * args.gradient_accumulation_steps
1056
+ first_epoch = resume_global_step // num_update_steps_per_epoch
1057
+ resume_step = resume_global_step % num_update_steps_per_epoch
1058
+
1059
+ # Only show the progress bar once on each machine.
1060
+ progress_bar = tqdm(range(global_step, args.max_train_steps), disable=not accelerator.is_local_main_process)
1061
+ progress_bar.set_description("Steps")
1062
+
1063
+ for epoch in range(first_epoch, args.num_train_epochs):
1064
+ unet.train()
1065
+ if args.train_text_encoder:
1066
+ text_encoder.train()
1067
+ with TorchTracemalloc() as tracemalloc:
1068
+ for step, batch in enumerate(train_dataloader):
1069
+ # Skip steps until we reach the resumed step
1070
+ if args.resume_from_checkpoint and epoch == first_epoch and step < resume_step:
1071
+ if step % args.gradient_accumulation_steps == 0:
1072
+ progress_bar.update(1)
1073
+ if args.report_to == "wandb":
1074
+ accelerator.print(progress_bar)
1075
+ continue
1076
+
1077
+ with accelerator.accumulate(unet):
1078
+ # Convert images to latent space
1079
+ latents = vae.encode(batch["pixel_values"].to(dtype=weight_dtype)).latent_dist.sample()
1080
+ latents = latents * 0.18215
1081
+
1082
+ # Sample noise that we'll add to the latents
1083
+ noise = torch.randn_like(latents)
1084
+ bsz = latents.shape[0]
1085
+ # Sample a random timestep for each image
1086
+ timesteps = torch.randint(
1087
+ 0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device
1088
+ )
1089
+ timesteps = timesteps.long()
1090
+
1091
+ # Add noise to the latents according to the noise magnitude at each timestep
1092
+ # (this is the forward diffusion process)
1093
+ noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
1094
+
1095
+ # Get the text embedding for conditioning
1096
+ encoder_hidden_states = text_encoder(batch["input_ids"])[0]
1097
+
1098
+ # Predict the noise residual
1099
+ model_pred = unet(noisy_latents, timesteps, encoder_hidden_states).sample
1100
+
1101
+ # Get the target for loss depending on the prediction type
1102
+ if noise_scheduler.config.prediction_type == "epsilon":
1103
+ target = noise
1104
+ elif noise_scheduler.config.prediction_type == "v_prediction":
1105
+ target = noise_scheduler.get_velocity(latents, noise, timesteps)
1106
+ else:
1107
+ raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
1108
+
1109
+ if args.with_prior_preservation:
1110
+ # Chunk the noise and model_pred into two parts and compute the loss on each part separately.
1111
+ model_pred, model_pred_prior = torch.chunk(model_pred, 2, dim=0)
1112
+ target, target_prior = torch.chunk(target, 2, dim=0)
1113
+
1114
+ # Compute instance loss
1115
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
1116
+
1117
+ # Compute prior loss
1118
+ prior_loss = F.mse_loss(model_pred_prior.float(), target_prior.float(), reduction="mean")
1119
+
1120
+ # Add the prior loss to the instance loss.
1121
+ loss = loss + args.prior_loss_weight * prior_loss
1122
+ else:
1123
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
1124
+
1125
+ accelerator.backward(loss)
1126
+ if accelerator.sync_gradients:
1127
+ params_to_clip = (
1128
+ itertools.chain(unet.parameters(), text_encoder.parameters())
1129
+ if args.train_text_encoder
1130
+ else unet.parameters()
1131
+ )
1132
+ accelerator.clip_grad_norm_(params_to_clip, args.max_grad_norm)
1133
+ optimizer.step()
1134
+ lr_scheduler.step()
1135
+ optimizer.zero_grad()
1136
+
1137
+ # Checks if the accelerator has performed an optimization step behind the scenes
1138
+ if accelerator.sync_gradients:
1139
+ progress_bar.update(1)
1140
+ if args.report_to == "wandb":
1141
+ accelerator.print(progress_bar)
1142
+ global_step += 1
1143
+
1144
+ # if global_step % args.checkpointing_steps == 0:
1145
+ # if accelerator.is_main_process:
1146
+ # save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
1147
+ # accelerator.save_state(save_path)
1148
+ # logger.info(f"Saved state to {save_path}")
1149
+
1150
+ logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
1151
+ progress_bar.set_postfix(**logs)
1152
+ accelerator.log(logs, step=global_step)
1153
+
1154
+ if (
1155
+ args.validation_prompt is not None
1156
+ and (step + num_update_steps_per_epoch * epoch) % args.validation_steps == 0
1157
+ ):
1158
+ logger.info(
1159
+ f"Running validation... \n Generating {args.num_validation_images} images with prompt:"
1160
+ f" {args.validation_prompt}."
1161
+ )
1162
+ # create pipeline
1163
+ pipeline = DiffusionPipeline.from_pretrained(
1164
+ args.pretrained_model_name_or_path,
1165
+ safety_checker=None,
1166
+ revision=args.revision,
1167
+ )
1168
+ # set `keep_fp32_wrapper` to True because we do not want to remove
1169
+ # mixed precision hooks while we are still training
1170
+ pipeline.unet = accelerator.unwrap_model(unet, keep_fp32_wrapper=True)
1171
+ pipeline.text_encoder = accelerator.unwrap_model(text_encoder, keep_fp32_wrapper=True)
1172
+ pipeline.scheduler = DPMSolverMultistepScheduler.from_config(pipeline.scheduler.config)
1173
+ pipeline = pipeline.to(accelerator.device)
1174
+ pipeline.set_progress_bar_config(disable=True)
1175
+
1176
+ # Set evaliation mode
1177
+ pipeline.unet.eval()
1178
+ pipeline.text_encoder.eval()
1179
+
1180
+ # run inference
1181
+ if args.seed is not None:
1182
+ generator = torch.Generator(device=accelerator.device).manual_seed(args.seed)
1183
+ else:
1184
+ generator = None
1185
+ images = []
1186
+ for _ in range(args.num_validation_images):
1187
+ image = pipeline(args.validation_prompt, num_inference_steps=25, generator=generator).images[0]
1188
+ images.append(image)
1189
+
1190
+ for tracker in accelerator.trackers:
1191
+ if tracker.name == "tensorboard":
1192
+ np_images = np.stack([np.asarray(img) for img in images])
1193
+ tracker.writer.add_images("validation", np_images, epoch, dataformats="NHWC")
1194
+ if tracker.name == "wandb":
1195
+ import wandb
1196
+
1197
+ tracker.log(
1198
+ {
1199
+ "validation": [
1200
+ wandb.Image(image, caption=f"{i}: {args.validation_prompt}")
1201
+ for i, image in enumerate(images)
1202
+ ]
1203
+ }
1204
+ )
1205
+
1206
+ # Set evaliation mode
1207
+ pipeline.unet.train()
1208
+ pipeline.text_encoder.train()
1209
+
1210
+ del pipeline
1211
+ if torch.cuda.is_available():
1212
+ torch.cuda.empty_cache()
1213
+ elif torch.xpu.is_available():
1214
+ torch.xpu.empty_cache()
1215
+
1216
+ if global_step >= args.max_train_steps:
1217
+ break
1218
+ # Printing the accelerator memory usage details such as allocated memory, peak memory, and total memory usage
1219
+ accelerator.print(
1220
+ f"{accelerator.device.type.upper()} Memory before entering the train : {b2mb(tracemalloc.begin)}"
1221
+ )
1222
+ accelerator.print(
1223
+ f"{accelerator.device.type.upper()} Memory consumed at the end of the train (end-begin): {tracemalloc.used}"
1224
+ )
1225
+ accelerator.print(
1226
+ f"{accelerator.device.type.upper()} Peak Memory consumed during the train (max-begin): {tracemalloc.peaked}"
1227
+ )
1228
+ accelerator.print(
1229
+ f"{accelerator.device.type.upper()} Total Peak Memory consumed during the train (max): {tracemalloc.peaked + b2mb(tracemalloc.begin)}"
1230
+ )
1231
+
1232
+ accelerator.print(f"CPU Memory before entering the train : {b2mb(tracemalloc.cpu_begin)}")
1233
+ accelerator.print(f"CPU Memory consumed at the end of the train (end-begin): {tracemalloc.cpu_used}")
1234
+ accelerator.print(f"CPU Peak Memory consumed during the train (max-begin): {tracemalloc.cpu_peaked}")
1235
+ accelerator.print(
1236
+ f"CPU Total Peak Memory consumed during the train (max): {tracemalloc.cpu_peaked + b2mb(tracemalloc.cpu_begin)}"
1237
+ )
1238
+
1239
+ # Create the pipeline using using the trained modules and save it.
1240
+ accelerator.wait_for_everyone()
1241
+ if accelerator.is_main_process:
1242
+ if args.adapter != "full":
1243
+ unwarpped_unet = accelerator.unwrap_model(unet)
1244
+ unwarpped_unet.save_pretrained(
1245
+ os.path.join(args.output_dir, "unet"), state_dict=accelerator.get_state_dict(unet)
1246
+ )
1247
+ if args.train_text_encoder:
1248
+ unwarpped_text_encoder = accelerator.unwrap_model(text_encoder)
1249
+ unwarpped_text_encoder.save_pretrained(
1250
+ os.path.join(args.output_dir, "text_encoder"),
1251
+ state_dict=accelerator.get_state_dict(text_encoder),
1252
+ )
1253
+ else:
1254
+ pipeline = DiffusionPipeline.from_pretrained(
1255
+ args.pretrained_model_name_or_path,
1256
+ unet=accelerator.unwrap_model(unet),
1257
+ text_encoder=accelerator.unwrap_model(text_encoder),
1258
+ revision=args.revision,
1259
+ )
1260
+ pipeline.save_pretrained(args.output_dir)
1261
+
1262
+ if args.push_to_hub:
1263
+ api.upload_folder(
1264
+ repo_id=repo_id,
1265
+ folder_path=args.output_dir,
1266
+ commit_message="End of training",
1267
+ run_as_future=True,
1268
+ )
1269
+
1270
+ accelerator.end_training()
1271
+
1272
+
1273
+ if __name__ == "__main__":
1274
+ args = parse_args()
1275
+ main(args)
tasks/tasksmith-c488fc138ba1/environment/source/examples/token_classification/peft_lora_ner.ipynb ADDED
@@ -0,0 +1,554 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "## Named Entity Recognition with Peft Model 🤗\n",
8
+ "\n",
9
+ "##### In this notebook, we will learn how to perform Named Entity Recognition(NER) on the CoNLL-2003 dataset using the Trainer class\n",
10
+ "\n",
11
+ "##### This notebook has been adapted from the main NLP course here - https://huggingface.co/learn/nlp-course/chapter7/2?fw=pt#fine-tuning-the-model"
12
+ ]
13
+ },
14
+ {
15
+ "cell_type": "code",
16
+ "execution_count": null,
17
+ "metadata": {},
18
+ "outputs": [],
19
+ "source": [
20
+ "#install the required libraries\n",
21
+ "!pip install -q datasets evaluate transformers seqeval"
22
+ ]
23
+ },
24
+ {
25
+ "cell_type": "code",
26
+ "execution_count": null,
27
+ "metadata": {},
28
+ "outputs": [],
29
+ "source": [
30
+ "# Import required libraries\n",
31
+ "from datasets import load_dataset\n",
32
+ "from transformers import AutoTokenizer, AutoModelForTokenClassification, DataCollatorForTokenClassification, TrainingArguments, Trainer, pipeline\n",
33
+ "from peft import get_peft_model, LoraConfig, TaskType\n",
34
+ "import evaluate\n",
35
+ "import numpy as np\n",
36
+ "from huggingface_hub import notebook_login"
37
+ ]
38
+ },
39
+ {
40
+ "cell_type": "code",
41
+ "execution_count": 2,
42
+ "metadata": {},
43
+ "outputs": [
44
+ {
45
+ "name": "stdout",
46
+ "output_type": "stream",
47
+ "text": [
48
+ "DatasetDict({\n",
49
+ " train: Dataset({\n",
50
+ " features: ['id', 'tokens', 'pos_tags', 'chunk_tags', 'ner_tags'],\n",
51
+ " num_rows: 14041\n",
52
+ " })\n",
53
+ " validation: Dataset({\n",
54
+ " features: ['id', 'tokens', 'pos_tags', 'chunk_tags', 'ner_tags'],\n",
55
+ " num_rows: 3250\n",
56
+ " })\n",
57
+ " test: Dataset({\n",
58
+ " features: ['id', 'tokens', 'pos_tags', 'chunk_tags', 'ner_tags'],\n",
59
+ " num_rows: 3453\n",
60
+ " })\n",
61
+ "})\n"
62
+ ]
63
+ }
64
+ ],
65
+ "source": [
66
+ "raw_datasets = load_dataset(\"conll2003\")\n",
67
+ "print(raw_datasets)"
68
+ ]
69
+ },
70
+ {
71
+ "cell_type": "code",
72
+ "execution_count": 3,
73
+ "metadata": {},
74
+ "outputs": [
75
+ {
76
+ "data": {
77
+ "text/plain": [
78
+ "['EU', 'rejects', 'German', 'call', 'to', 'boycott', 'British', 'lamb', '.']"
79
+ ]
80
+ },
81
+ "execution_count": 3,
82
+ "metadata": {},
83
+ "output_type": "execute_result"
84
+ }
85
+ ],
86
+ "source": [
87
+ "# Look at the tokens of the first training example\n",
88
+ "raw_datasets[\"train\"][0][\"tokens\"]"
89
+ ]
90
+ },
91
+ {
92
+ "cell_type": "code",
93
+ "execution_count": 4,
94
+ "metadata": {},
95
+ "outputs": [
96
+ {
97
+ "data": {
98
+ "text/plain": [
99
+ "[3, 0, 7, 0, 0, 0, 7, 0, 0]"
100
+ ]
101
+ },
102
+ "execution_count": 4,
103
+ "metadata": {},
104
+ "output_type": "execute_result"
105
+ }
106
+ ],
107
+ "source": [
108
+ "# Look at the NER tags of the first training example\n",
109
+ "raw_datasets[\"train\"][0][\"ner_tags\"]"
110
+ ]
111
+ },
112
+ {
113
+ "cell_type": "code",
114
+ "execution_count": 5,
115
+ "metadata": {},
116
+ "outputs": [
117
+ {
118
+ "data": {
119
+ "text/plain": [
120
+ "['O', 'B-PER', 'I-PER', 'B-ORG', 'I-ORG', 'B-LOC', 'I-LOC', 'B-MISC', 'I-MISC']"
121
+ ]
122
+ },
123
+ "execution_count": 5,
124
+ "metadata": {},
125
+ "output_type": "execute_result"
126
+ }
127
+ ],
128
+ "source": [
129
+ "# Get the label names for the NER tags\n",
130
+ "ner_feature = raw_datasets[\"train\"].features[\"ner_tags\"]\n",
131
+ "label_names = ner_feature.feature.names\n",
132
+ "label_names"
133
+ ]
134
+ },
135
+ {
136
+ "cell_type": "code",
137
+ "execution_count": 6,
138
+ "metadata": {},
139
+ "outputs": [
140
+ {
141
+ "name": "stdout",
142
+ "output_type": "stream",
143
+ "text": [
144
+ "EU rejects German call to boycott British lamb . \n",
145
+ "B-ORG O B-MISC O O O B-MISC O O \n"
146
+ ]
147
+ }
148
+ ],
149
+ "source": [
150
+ "words = raw_datasets[\"train\"][0][\"tokens\"]\n",
151
+ "labels = raw_datasets[\"train\"][0][\"ner_tags\"]\n",
152
+ "line1 = \"\"\n",
153
+ "line2 = \"\"\n",
154
+ "for word, label in zip(words, labels):\n",
155
+ " full_label = label_names[label]\n",
156
+ " max_length = max(len(word), len(full_label))\n",
157
+ " line1 += word + \" \" * (max_length - len(word) + 1)\n",
158
+ " line2 += full_label + \" \" * (max_length - len(full_label) + 1)\n",
159
+ "\n",
160
+ "print(line1)\n",
161
+ "print(line2)"
162
+ ]
163
+ },
164
+ {
165
+ "cell_type": "code",
166
+ "execution_count": 7,
167
+ "metadata": {},
168
+ "outputs": [],
169
+ "source": [
170
+ "# Load the tokenizer\n",
171
+ "model_checkpoint = \"bert-base-cased\"\n",
172
+ "tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)"
173
+ ]
174
+ },
175
+ {
176
+ "cell_type": "code",
177
+ "execution_count": 8,
178
+ "metadata": {},
179
+ "outputs": [
180
+ {
181
+ "data": {
182
+ "text/plain": [
183
+ "['[CLS]',\n",
184
+ " 'EU',\n",
185
+ " 'rejects',\n",
186
+ " 'German',\n",
187
+ " 'call',\n",
188
+ " 'to',\n",
189
+ " 'boycott',\n",
190
+ " 'British',\n",
191
+ " 'la',\n",
192
+ " '##mb',\n",
193
+ " '.',\n",
194
+ " '[SEP]']"
195
+ ]
196
+ },
197
+ "execution_count": 8,
198
+ "metadata": {},
199
+ "output_type": "execute_result"
200
+ }
201
+ ],
202
+ "source": [
203
+ "# Tokenize the first training example\n",
204
+ "inputs = tokenizer(raw_datasets[\"train\"][0][\"tokens\"], is_split_into_words=True)\n",
205
+ "inputs.tokens()"
206
+ ]
207
+ },
208
+ {
209
+ "cell_type": "code",
210
+ "execution_count": 9,
211
+ "metadata": {},
212
+ "outputs": [],
213
+ "source": [
214
+ "def align_labels_with_tokens(labels, word_ids):\n",
215
+ " new_labels = []\n",
216
+ " current_word = None\n",
217
+ " for word_id in word_ids:\n",
218
+ " if word_id != current_word:\n",
219
+ " # Start of a new word!\n",
220
+ " current_word = word_id\n",
221
+ " label = -100 if word_id is None else labels[word_id]\n",
222
+ " new_labels.append(label)\n",
223
+ " elif word_id is None:\n",
224
+ " # Special token\n",
225
+ " new_labels.append(-100)\n",
226
+ " else:\n",
227
+ " # Same word as previous token\n",
228
+ " label = labels[word_id]\n",
229
+ " # If the label is B-XXX we change it to I-XXX\n",
230
+ " if label % 2 == 1:\n",
231
+ " label += 1\n",
232
+ " new_labels.append(label)\n",
233
+ "\n",
234
+ " return new_labels"
235
+ ]
236
+ },
237
+ {
238
+ "cell_type": "code",
239
+ "execution_count": 10,
240
+ "metadata": {},
241
+ "outputs": [
242
+ {
243
+ "name": "stdout",
244
+ "output_type": "stream",
245
+ "text": [
246
+ "[3, 0, 7, 0, 0, 0, 7, 0, 0]\n",
247
+ "[-100, 3, 0, 7, 0, 0, 0, 7, 0, 0, 0, -100]\n"
248
+ ]
249
+ }
250
+ ],
251
+ "source": [
252
+ "labels = raw_datasets[\"train\"][0][\"ner_tags\"]\n",
253
+ "word_ids = inputs.word_ids()\n",
254
+ "print(labels)\n",
255
+ "print(align_labels_with_tokens(labels, word_ids))"
256
+ ]
257
+ },
258
+ {
259
+ "cell_type": "code",
260
+ "execution_count": 11,
261
+ "metadata": {},
262
+ "outputs": [],
263
+ "source": [
264
+ "def tokenize_and_align_labels(examples):\n",
265
+ " tokenized_inputs = tokenizer(\n",
266
+ " examples[\"tokens\"], truncation=True, is_split_into_words=True\n",
267
+ " )\n",
268
+ " all_labels = examples[\"ner_tags\"]\n",
269
+ " new_labels = []\n",
270
+ " for i, labels in enumerate(all_labels):\n",
271
+ " word_ids = tokenized_inputs.word_ids(i)\n",
272
+ " new_labels.append(align_labels_with_tokens(labels, word_ids))\n",
273
+ "\n",
274
+ " tokenized_inputs[\"labels\"] = new_labels\n",
275
+ " return tokenized_inputs"
276
+ ]
277
+ },
278
+ {
279
+ "cell_type": "code",
280
+ "execution_count": 12,
281
+ "metadata": {},
282
+ "outputs": [],
283
+ "source": [
284
+ "tokenized_datasets = raw_datasets.map(\n",
285
+ " tokenize_and_align_labels,\n",
286
+ " batched=True,\n",
287
+ " remove_columns=raw_datasets[\"train\"].column_names,\n",
288
+ ")"
289
+ ]
290
+ },
291
+ {
292
+ "cell_type": "code",
293
+ "execution_count": 13,
294
+ "metadata": {},
295
+ "outputs": [],
296
+ "source": [
297
+ "data_collator = DataCollatorForTokenClassification(tokenizer=tokenizer)"
298
+ ]
299
+ },
300
+ {
301
+ "cell_type": "code",
302
+ "execution_count": 14,
303
+ "metadata": {},
304
+ "outputs": [
305
+ {
306
+ "name": "stdout",
307
+ "output_type": "stream",
308
+ "text": [
309
+ "[-100, 3, 0, 7, 0, 0, 0, 7, 0, 0, 0, -100]\n",
310
+ "[-100, 1, 2, -100]\n"
311
+ ]
312
+ }
313
+ ],
314
+ "source": [
315
+ "for i in range(2):\n",
316
+ " print(tokenized_datasets[\"train\"][i][\"labels\"])"
317
+ ]
318
+ },
319
+ {
320
+ "cell_type": "code",
321
+ "execution_count": 15,
322
+ "metadata": {},
323
+ "outputs": [],
324
+ "source": [
325
+ "metric = evaluate.load(\"seqeval\")"
326
+ ]
327
+ },
328
+ {
329
+ "cell_type": "code",
330
+ "execution_count": 16,
331
+ "metadata": {},
332
+ "outputs": [],
333
+ "source": [
334
+ "# Create label mappings\n",
335
+ "id2label = {i: label for i, label in enumerate(label_names)}\n",
336
+ "label2id = {v: k for k, v in id2label.items()}"
337
+ ]
338
+ },
339
+ {
340
+ "cell_type": "code",
341
+ "execution_count": null,
342
+ "metadata": {},
343
+ "outputs": [],
344
+ "source": [
345
+ "# Load the pre-trained model\n",
346
+ "model = AutoModelForTokenClassification.from_pretrained(\n",
347
+ " model_checkpoint,\n",
348
+ " id2label=id2label,\n",
349
+ " label2id=label2id,\n",
350
+ ")"
351
+ ]
352
+ },
353
+ {
354
+ "cell_type": "code",
355
+ "execution_count": 18,
356
+ "metadata": {},
357
+ "outputs": [
358
+ {
359
+ "data": {
360
+ "text/plain": [
361
+ "9"
362
+ ]
363
+ },
364
+ "execution_count": 18,
365
+ "metadata": {},
366
+ "output_type": "execute_result"
367
+ }
368
+ ],
369
+ "source": [
370
+ "model.config.num_labels"
371
+ ]
372
+ },
373
+ {
374
+ "cell_type": "code",
375
+ "execution_count": null,
376
+ "metadata": {},
377
+ "outputs": [],
378
+ "source": [
379
+ "model"
380
+ ]
381
+ },
382
+ {
383
+ "cell_type": "code",
384
+ "execution_count": null,
385
+ "metadata": {},
386
+ "outputs": [],
387
+ "source": [
388
+ "# Configure LoRA (Low-Rank Adaptation) for fine-tuning\n",
389
+ "peft_config = LoraConfig(target_modules = [\"query\", \"key\"], task_type = TaskType.TOKEN_CLS)\n",
390
+ "\n",
391
+ "model = get_peft_model(model, peft_config)\n",
392
+ "model.print_trainable_parameters()"
393
+ ]
394
+ },
395
+ {
396
+ "cell_type": "code",
397
+ "execution_count": 21,
398
+ "metadata": {},
399
+ "outputs": [],
400
+ "source": [
401
+ "def compute_metrics(eval_preds):\n",
402
+ " logits, labels = eval_preds\n",
403
+ " predictions = np.argmax(logits, axis=-1)\n",
404
+ "\n",
405
+ " # Remove ignored index (special tokens) and convert to labels\n",
406
+ " true_labels = [[label_names[l] for l in label if l != -100] for label in labels]\n",
407
+ " true_predictions = [\n",
408
+ " [label_names[p] for (p, l) in zip(prediction, label) if l != -100]\n",
409
+ " for prediction, label in zip(predictions, labels)\n",
410
+ " ]\n",
411
+ " all_metrics = metric.compute(predictions=true_predictions, references=true_labels)\n",
412
+ " return {\n",
413
+ " \"precision\": all_metrics[\"overall_precision\"],\n",
414
+ " \"recall\": all_metrics[\"overall_recall\"],\n",
415
+ " \"f1\": all_metrics[\"overall_f1\"],\n",
416
+ " \"accuracy\": all_metrics[\"overall_accuracy\"],\n",
417
+ " }"
418
+ ]
419
+ },
420
+ {
421
+ "cell_type": "code",
422
+ "execution_count": null,
423
+ "metadata": {},
424
+ "outputs": [],
425
+ "source": [
426
+ "notebook_login()"
427
+ ]
428
+ },
429
+ {
430
+ "cell_type": "code",
431
+ "execution_count": null,
432
+ "metadata": {},
433
+ "outputs": [],
434
+ "source": [
435
+ "args = TrainingArguments(\n",
436
+ " \"bert-finetuned-ner-lora\",\n",
437
+ " eval_strategy=\"epoch\",\n",
438
+ " per_device_train_batch_size=32, # decrease this for OOM error\n",
439
+ " per_device_eval_batch_size=64,\n",
440
+ " save_strategy=\"epoch\",\n",
441
+ " learning_rate=2e-3,\n",
442
+ " num_train_epochs=5,\n",
443
+ " weight_decay=0.01,\n",
444
+ " load_best_model_at_end=True,\n",
445
+ " do_eval=True,\n",
446
+ " do_predict=True,\n",
447
+ " metric_for_best_model=\"accuracy\",\n",
448
+ " label_names=[\"labels\"],\n",
449
+ " push_to_hub=True,\n",
450
+ ")"
451
+ ]
452
+ },
453
+ {
454
+ "cell_type": "code",
455
+ "execution_count": null,
456
+ "metadata": {},
457
+ "outputs": [],
458
+ "source": [
459
+ "trainer = Trainer(\n",
460
+ " model=model,\n",
461
+ " args=args,\n",
462
+ " train_dataset=tokenized_datasets[\"train\"],\n",
463
+ " eval_dataset=tokenized_datasets[\"validation\"],\n",
464
+ " data_collator=data_collator,\n",
465
+ " processing_class=tokenizer,\n",
466
+ " compute_metrics=compute_metrics\n",
467
+ ")\n",
468
+ "trainer.train()"
469
+ ]
470
+ },
471
+ {
472
+ "cell_type": "code",
473
+ "execution_count": 31,
474
+ "metadata": {},
475
+ "outputs": [
476
+ {
477
+ "name": "stderr",
478
+ "output_type": "stream",
479
+ "text": [
480
+ "Some weights of BertForTokenClassification were not initialized from the model checkpoint at bert-base-cased and are newly initialized: ['classifier.bias', 'classifier.weight']\n",
481
+ "You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n",
482
+ "Device set to use xpu:0\n"
483
+ ]
484
+ },
485
+ {
486
+ "name": "stdout",
487
+ "output_type": "stream",
488
+ "text": [
489
+ "entity_idx: 0, id2label: {0: 'O', 1: 'B-PER', 2: 'I-PER', 3: 'B-ORG', 4: 'I-ORG', 5: 'B-LOC', 6: 'I-LOC', 7: 'B-MISC', 8: 'I-MISC'}\n",
490
+ "entity_idx: 0, id2label: {0: 'O', 1: 'B-PER', 2: 'I-PER', 3: 'B-ORG', 4: 'I-ORG', 5: 'B-LOC', 6: 'I-LOC', 7: 'B-MISC', 8: 'I-MISC'}\n",
491
+ "entity_idx: 0, id2label: {0: 'O', 1: 'B-PER', 2: 'I-PER', 3: 'B-ORG', 4: 'I-ORG', 5: 'B-LOC', 6: 'I-LOC', 7: 'B-MISC', 8: 'I-MISC'}\n",
492
+ "entity_idx: 1, id2label: {0: 'O', 1: 'B-PER', 2: 'I-PER', 3: 'B-ORG', 4: 'I-ORG', 5: 'B-LOC', 6: 'I-LOC', 7: 'B-MISC', 8: 'I-MISC'}\n",
493
+ "entity_idx: 2, id2label: {0: 'O', 1: 'B-PER', 2: 'I-PER', 3: 'B-ORG', 4: 'I-ORG', 5: 'B-LOC', 6: 'I-LOC', 7: 'B-MISC', 8: 'I-MISC'}\n",
494
+ "entity_idx: 0, id2label: {0: 'O', 1: 'B-PER', 2: 'I-PER', 3: 'B-ORG', 4: 'I-ORG', 5: 'B-LOC', 6: 'I-LOC', 7: 'B-MISC', 8: 'I-MISC'}\n"
495
+ ]
496
+ },
497
+ {
498
+ "data": {
499
+ "text/plain": [
500
+ "[{'entity_group': 'PER',\n",
501
+ " 'score': 0.9702984,\n",
502
+ " 'word': 'Jino',\n",
503
+ " 'start': 11,\n",
504
+ " 'end': 15}]"
505
+ ]
506
+ },
507
+ "execution_count": 31,
508
+ "metadata": {},
509
+ "output_type": "execute_result"
510
+ }
511
+ ],
512
+ "source": [
513
+ "from peft import PeftModel\n",
514
+ "\n",
515
+ "# Replace this with your own checkpoint\n",
516
+ "lora_checkpoint = \"./bert-finetuned-ner-lora\"\n",
517
+ "\n",
518
+ "tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)\n",
519
+ "base_model = AutoModelForTokenClassification.from_pretrained(\n",
520
+ " model_checkpoint,\n",
521
+ " id2label=id2label,\n",
522
+ " label2id=label2id,\n",
523
+ ")\n",
524
+ "lora_model = PeftModel.from_pretrained(base_model, lora_checkpoint)\n",
525
+ "token_classifier = pipeline(\n",
526
+ " \"token-classification\", model=lora_model, tokenizer=tokenizer, aggregation_strategy=\"simple\"\n",
527
+ ")\n",
528
+ "\n",
529
+ "token_classifier(\"My name is Jino.\")"
530
+ ]
531
+ }
532
+ ],
533
+ "metadata": {
534
+ "kernelspec": {
535
+ "display_name": "Python 3",
536
+ "language": "python",
537
+ "name": "python3"
538
+ },
539
+ "language_info": {
540
+ "codemirror_mode": {
541
+ "name": "ipython",
542
+ "version": 3
543
+ },
544
+ "file_extension": ".py",
545
+ "mimetype": "text/x-python",
546
+ "name": "python",
547
+ "nbconvert_exporter": "python",
548
+ "pygments_lexer": "ipython3",
549
+ "version": "3.11.13"
550
+ }
551
+ },
552
+ "nbformat": 4,
553
+ "nbformat_minor": 2
554
+ }
tasks/tasksmith-c488fc138ba1/environment/source/examples/token_classification/peft_lora_token_cls.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
tasks/tasksmith-c488fc138ba1/environment/source/examples/token_classification/requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ transformers
2
+ accelerate
3
+ evaluate
4
+ tqdm
5
+ datasets
6
+ Pillow
7
+ torchvision
tasks/tasksmith-c488fc138ba1/environment/source/examples/waveft_finetuning/README.md ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ # WaveFT: Wavelet Fine-Tuning
4
+
5
+ ## Introduction
6
+ [WaveFT](https://huggingface.co/papers/2505.12532) is a novel parameter-efficient fine-tuning (PEFT) method that introduces sparse updates in the **wavelet domain** of residual matrices. Unlike LoRA, which is constrained by discrete low-rank choices, WaveFT enables fine-grained control over the number of trainable parameters by directly learning a sparse set of coefficients in the transformed space. These coefficients are then mapped back to the weight domain via the Inverse Discrete Wavelet Transform (IDWT), producing high-rank updates without incurring inference overhead.
7
+
8
+ ## Quick start
9
+ ```python
10
+ import torch
11
+ from peft import WaveFTConfig, get_peft_model
12
+ from transformers import AutoTokenizer, AutoModelForCausalLM
13
+ from trl import SFTConfig, SFTTrainer
14
+ from datasets import load_dataset
15
+
16
+ model = AutoModelForCausalLM.from_pretrained("facebook/opt-350m", dtype=torch.bfloat16, device_map="auto")
17
+ tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m")
18
+ dataset = load_dataset("imdb", split="train[:1%]")
19
+ waveft_config = WaveFTConfig(
20
+ n_frequency=2592,
21
+ )
22
+ peft_model = get_peft_model(model, waveft_config)
23
+ training_args = SFTConfig(dataset_text_field="text", max_length=128)
24
+ trainer = SFTTrainer(
25
+ model=peft_model,
26
+ train_dataset=dataset,
27
+ processing_class=tokenizer,
28
+ )
29
+ trainer.train()
30
+ peft_model.save_pretrained("waveft-opt-350m")
31
+ ```
32
+
33
+ For more options and a more detailed example code, you can refer to waveft finetuning script.
34
+ Run the script simply by running:
35
+ ```bash
36
+ python3 examples/waveft_finetuning/waveft_finetuning.py --base_model facebook/opt-350m
37
+ ```
38
+
39
+ If you want to run DDP by [accelerate](https://huggingface.co/docs/accelerate/en/index), please run `accelerate config` to set your ddp config, and run:
40
+ ```bash
41
+ accelerate launch examples/waveft_finetuning/waveft_finetuning.py --base_model facebook/opt-350m
42
+ ```
43
+ please add `--device_map cpu` if you want to run finetune on CPU.
44
+
45
+ ## Use the model
46
+ You can load and use the model as any other 🤗 PEFT model
47
+ ```python
48
+ from peft import PeftModel
49
+ from transformers import AutoTokenizer, AutoModelForCausalLM
50
+ model = AutoModelForCausalLM.from_pretrained("facebook/opt-350m")
51
+ tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m")
52
+ waveft_model = PeftModel.from_pretrained(model, "waveft-opt-350m")
53
+ ```
54
+
55
+ ## Citation
56
+ @misc{bilican2025exploringsparsityparameterefficient,
57
+ title={Exploring Sparsity for Parameter Efficient Fine Tuning Using Wavelets},
58
+ author={Ahmet Bilican and M. Akın Yılmaz and A. Murat Tekalp and R. Gökberk Cinbiş},
59
+ year={2025},
60
+ eprint={2505.12532},
61
+ archivePrefix={arXiv},
62
+ primaryClass={cs.CV},
63
+ url={https://arxiv.org/abs/2505.12532},
64
+ }
tasks/tasksmith-c488fc138ba1/environment/source/examples/waveft_finetuning/waveft_finetuning.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import os
17
+ from typing import Optional
18
+
19
+ import torch
20
+ import transformers
21
+ from datasets import load_dataset
22
+ from transformers import AutoModelForCausalLM, AutoTokenizer, set_seed
23
+
24
+ from peft import (
25
+ WaveFTConfig,
26
+ get_peft_model,
27
+ )
28
+
29
+
30
+ def train(
31
+ base_model: str,
32
+ data_path: str = "yahma/alpaca-cleaned",
33
+ output_dir: str = "waveft",
34
+ batch_size: int = 16,
35
+ num_epochs: int = 1,
36
+ learning_rate: float = 3e-4,
37
+ cutoff_len: int = 256,
38
+ val_set_size: int = 16,
39
+ eval_step: int = 100,
40
+ save_step: int = 100,
41
+ device_map: str = "auto",
42
+ waveft_n_frequency: int = 2592,
43
+ waveft_target_modules: Optional[list[str]] = None,
44
+ waveft_scaling: float = 25.0,
45
+ waveft_wavelet_family: str = "db1",
46
+ waveft_use_idwt: bool = True,
47
+ dtype: str = "float16",
48
+ seed: Optional[int] = None,
49
+ ):
50
+ # Set device_map to the right place when enabling DDP.
51
+ world_size = int(os.environ.get("WORLD_SIZE", "0")) or int(os.environ.get("PMI_SIZE", "0"))
52
+ if world_size > 1 and device_map != "cpu":
53
+ from accelerate import Accelerator
54
+
55
+ device_map = {"": Accelerator().process_index}
56
+ # Set seed
57
+ if seed is not None:
58
+ set_seed(seed)
59
+ model_kwargs = {"dtype": getattr(torch, dtype), "device_map": device_map}
60
+ model = AutoModelForCausalLM.from_pretrained(base_model, **model_kwargs)
61
+
62
+ tokenizer = AutoTokenizer.from_pretrained(base_model, trust_remote_code=True)
63
+ # For some tokenizer with no pad token like llama
64
+ if tokenizer.pad_token is None:
65
+ tokenizer.pad_token = tokenizer.eos_token
66
+
67
+ def tokenize(prompt, add_eos_token=True):
68
+ result = tokenizer(
69
+ prompt,
70
+ truncation=True,
71
+ max_length=cutoff_len,
72
+ padding=False,
73
+ return_tensors=None,
74
+ )
75
+ if (
76
+ result["input_ids"][-1] != tokenizer.eos_token_id
77
+ and len(result["input_ids"]) < cutoff_len
78
+ and add_eos_token
79
+ ):
80
+ result["input_ids"].append(tokenizer.eos_token_id)
81
+ result["attention_mask"].append(1)
82
+
83
+ result["labels"] = result["input_ids"].copy()
84
+
85
+ return result
86
+
87
+ def generate_and_tokenize_prompt(example):
88
+ full_prompt = generate_prompt(example)
89
+ tokenized_full_prompt = tokenize(full_prompt)
90
+ return tokenized_full_prompt
91
+
92
+ config = WaveFTConfig(
93
+ n_frequency=waveft_n_frequency,
94
+ scaling=waveft_scaling,
95
+ wavelet_family=waveft_wavelet_family,
96
+ use_idwt=waveft_use_idwt,
97
+ target_modules=waveft_target_modules,
98
+ task_type="CAUSAL_LM",
99
+ )
100
+
101
+ model = get_peft_model(model, config)
102
+
103
+ data = load_dataset(data_path)
104
+
105
+ train_val = data["train"].train_test_split(test_size=val_set_size, shuffle=True, seed=42)
106
+ train_data = train_val["train"].shuffle().map(generate_and_tokenize_prompt)
107
+ val_data = train_val["test"].shuffle().map(generate_and_tokenize_prompt)
108
+
109
+ trainer = transformers.Trainer(
110
+ model=model,
111
+ train_dataset=train_data,
112
+ eval_dataset=val_data,
113
+ args=transformers.TrainingArguments(
114
+ per_device_train_batch_size=batch_size,
115
+ warmup_steps=100,
116
+ num_train_epochs=num_epochs,
117
+ learning_rate=learning_rate,
118
+ logging_steps=100,
119
+ optim="adamw_torch",
120
+ eval_strategy="steps",
121
+ save_strategy="steps",
122
+ eval_steps=eval_step,
123
+ save_steps=save_step,
124
+ output_dir=output_dir,
125
+ save_total_limit=3,
126
+ load_best_model_at_end=True,
127
+ ddp_find_unused_parameters=False if world_size > 1 else None,
128
+ ),
129
+ data_collator=transformers.DataCollatorForSeq2Seq(
130
+ tokenizer, pad_to_multiple_of=8, return_tensors="pt", padding=True
131
+ ),
132
+ )
133
+ trainer.train()
134
+ model.save_pretrained(output_dir)
135
+
136
+
137
+ def generate_prompt(example):
138
+ return f"""Below is an instruction that describes a task. Write a response that appropriately completes the request.
139
+ ### Instruction:
140
+ {example["instruction"]}
141
+ ### Response:
142
+ {example["output"]}"""
143
+
144
+
145
+ if __name__ == "__main__":
146
+ import argparse
147
+
148
+ parser = argparse.ArgumentParser()
149
+ parser.add_argument("--base_model", type=str)
150
+ parser.add_argument("--data_path", type=str, default="yahma/alpaca-cleaned")
151
+ parser.add_argument("--output_dir", type=str, default="waveft")
152
+ parser.add_argument("--batch_size", type=int, default=16)
153
+ parser.add_argument("--num_epochs", type=int, default=1)
154
+ parser.add_argument("--learning_rate", type=float, default=3e-4)
155
+ parser.add_argument("--cutoff_len", type=int, default=256)
156
+ parser.add_argument("--val_set_size", type=int, default=16)
157
+ parser.add_argument("--eval_step", type=int, default=100)
158
+ parser.add_argument("--save_step", type=int, default=100)
159
+ parser.add_argument("--device_map", type=str, default="auto")
160
+ parser.add_argument("--waveft_n_frequency", type=int, default=2592)
161
+ parser.add_argument("--waveft_target_modules", type=str, default=None)
162
+ parser.add_argument("--waveft_scaling", type=float, default=25.0)
163
+ parser.add_argument("--waveft_wavelet_family", type=str, default="db1")
164
+ parser.add_argument("--waveft_use_idwt", action="store_true", default=True)
165
+ parser.add_argument("--dtype", type=str, default="float16")
166
+ parser.add_argument("--seed", type=int, default=None)
167
+
168
+ args = parser.parse_args()
169
+
170
+ train(
171
+ base_model=args.base_model,
172
+ data_path=args.data_path,
173
+ output_dir=args.output_dir,
174
+ batch_size=args.batch_size,
175
+ num_epochs=args.num_epochs,
176
+ learning_rate=args.learning_rate,
177
+ cutoff_len=args.cutoff_len,
178
+ val_set_size=args.val_set_size,
179
+ eval_step=args.eval_step,
180
+ save_step=args.save_step,
181
+ device_map=args.device_map,
182
+ waveft_n_frequency=args.waveft_n_frequency,
183
+ waveft_target_modules=args.waveft_target_modules,
184
+ waveft_scaling=args.waveft_scaling,
185
+ waveft_wavelet_family=args.waveft_wavelet_family,
186
+ waveft_use_idwt=args.waveft_use_idwt,
187
+ dtype=args.dtype,
188
+ seed=args.seed,
189
+ )
tasks/tasksmith-c488fc138ba1/environment/source/examples/xlora/README.md ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # X-LoRA examples
2
+
3
+ ## `xlora_inference_mistralrs.py`
4
+
5
+ Perform inference of an X-LoRA model using the inference engine mistral.rs.
6
+
7
+ Mistral.rs supports many base models besides Mistral, and can load models directly from saved LoRA checkpoints. Check out [adapter model docs](https://github.com/EricLBuehler/mistral.rs/blob/master/docs/ADAPTER_MODELS.md) and the [models support matrix](https://github.com/EricLBuehler/mistral.rs?tab=readme-ov-file#support-matrix).
8
+
9
+ Mistral.rs features X-LoRA support and incorporates techniques such as a dual-KV cache, continuous batching, Paged Attention, and optional non granular scalings, will allow vastly improved throughput.
10
+
11
+ Links:
12
+
13
+ - Installation: https://github.com/EricLBuehler/mistral.rs/blob/master/mistralrs-pyo3/README.md
14
+ - Runnable example: https://github.com/EricLBuehler/mistral.rs/blob/master/examples/python/xlora_zephyr.py
15
+ - Adapter model docs and making the ordering file: https://github.com/EricLBuehler/mistral.rs/blob/master/docs/ADAPTER_MODELS.md
tasks/tasksmith-c488fc138ba1/environment/source/examples/xlora/xlora_inference_mistralrs.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from mistralrs import ChatCompletionRequest, Runner, Which
2
+
3
+
4
+ runner = Runner(
5
+ which=Which.XLora(
6
+ tok_model_id=None, # Automatically determine from ordering file
7
+ model_id=..., # Model ID of the base model (local path of HF model ID)
8
+ xlora_model_id=..., # X-LoRA Model ID of the base model (local path of HF model ID)
9
+ order=..., # Ordering file to ensure compatability with PEFT
10
+ tgt_non_granular_index=3, # Only generate scalings for the first 3 decoding tokens, and then use the last generated one
11
+ )
12
+ )
13
+
14
+ res = runner.send_chat_completion_request(
15
+ ChatCompletionRequest(
16
+ model="mistral",
17
+ messages=[{"role": "user", "content": "Tell me a story about 2 low rank matrices."}],
18
+ max_tokens=256,
19
+ presence_penalty=1.0,
20
+ top_p=0.1,
21
+ temperature=0.5,
22
+ )
23
+ )
24
+ print(res.choices[0].message.content)
25
+ print(res.usage)
tasks/tasksmith-c488fc138ba1/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-c488fc138ba1/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-c488fc138ba1/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-c488fc138ba1/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-c488fc138ba1/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-c488fc138ba1/environment/source/scripts/generate_method_capabilities.py ADDED
@@ -0,0 +1,769 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Generate a machine-readable capability matrix of all PEFT methods.
15
+
16
+ For each registered PEFT method, a fixed set of checks ("tasks") determines which user-facing features the method
17
+ supports, e.g. which quantization backends it integrates with, which layer types it can target, or whether its adapters
18
+ can be merged into the base weights. The result is written as JSON and is intended as a generic data source, e.g. for
19
+ documentation pages or the PEFT shop app (method_comparison/peft-shop).
20
+
21
+ Each value is annotated with the *source* of the information:
22
+
23
+ - "introspection": determined by statically inspecting the classes of the installed PEFT package
24
+ - "file_check": determined from the presence of integration modules in the PEFT source tree
25
+ - "probe": determined empirically by exercising the feature on a tiny model on CPU
26
+ - "error": the check itself failed; the value is "unknown" and the note contains the reason
27
+
28
+ Values are never guessed: if a check cannot determine a feature, the value is reported as "unknown" together with a
29
+ note. In particular, probing a method requires that its config can be instantiated with default arguments; methods that
30
+ need more than that must have an entry in PROBE_CONFIG_OVERRIDES.
31
+
32
+ The script requires PEFT to be installed (e.g. `pip install -e .`), runs on CPU, downloads nothing, and is idempotent:
33
+ running it twice on the same environment produces identical output.
34
+
35
+ Usage examples:
36
+
37
+ # check all methods, write JSON to method_capabilities.json
38
+ python scripts/generate_method_capabilities.py
39
+
40
+ # check only LoRA and IA3, write to a custom file
41
+ python scripts/generate_method_capabilities.py --methods lora ia3 --output capabilities.json
42
+
43
+ # show which checks would run, without running them
44
+ python scripts/generate_method_capabilities.py --dry-run
45
+
46
+ Tasks are collected up-front before any of them runs (see `collect_tasks`). This makes `--dry-run` trivial and leaves
47
+ the door open to run independent tasks in parallel later, should runtime ever become an issue.
48
+ """
49
+
50
+ import argparse
51
+ import dataclasses
52
+ import enum
53
+ import inspect
54
+ import json
55
+ import logging
56
+ import re
57
+ import sys
58
+ import warnings
59
+ from abc import ABC, abstractmethod
60
+ from collections.abc import Callable
61
+ from copy import deepcopy
62
+ from dataclasses import dataclass
63
+ from pathlib import Path
64
+ from typing import Any, ClassVar
65
+
66
+ import torch
67
+ from torch import nn
68
+ from tqdm import tqdm
69
+ from transformers import LlamaConfig, LlamaForCausalLM
70
+ from transformers.pytorch_utils import Conv1D
71
+
72
+ import peft
73
+ from peft import get_peft_model
74
+ from peft.config import PeftConfig, PromptLearningConfig
75
+ from peft.mapping import PEFT_TYPE_TO_CONFIG_MAPPING, PEFT_TYPE_TO_MIXED_MODEL_MAPPING, PEFT_TYPE_TO_TUNER_MAPPING
76
+ from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer
77
+ from peft.utils.hotswap import CONFIG_KEYS_TO_CHECK
78
+ from peft.utils.peft_types import PeftType
79
+
80
+
81
+ logger = logging.getLogger("generate_method_capabilities")
82
+
83
+ UNKNOWN = "unknown"
84
+ NOT_APPLICABLE = "not_applicable"
85
+
86
+ # Probe models use this hidden dimension throughout. It is chosen to be highly divisible, since several methods have
87
+ # divisibility constraints between their block/rank settings and the layer dimensions (e.g. C3A, VBLoRA, RoAd).
88
+ HIDDEN_DIM = 64
89
+
90
+ # Quantization integration modules inside a tuner package, mapped to the backend names they provide. The bnb module
91
+ # always contains both the 8-bit and the 4-bit integration.
92
+ QUANT_FILE_BACKENDS: dict[str, tuple[str, ...]] = {
93
+ "aqlm": ("aqlm",),
94
+ "awq": ("awq",),
95
+ "bnb": ("bnb_8bit", "bnb_4bit"),
96
+ "eetq": ("eetq",),
97
+ "gptq": ("gptq",),
98
+ "hqq": ("hqq",),
99
+ "inc": ("inc",),
100
+ "torchao": ("torchao",),
101
+ }
102
+
103
+ # Backends covered by the generic quantization integration (peft.utils.quantization_utils). Methods that call
104
+ # resolve_quantization_backend don't need per-backend integration modules; they support everything the resolver
105
+ # handles (merging may still be unavailable for the forward-only backends, which is a property of the backend, not of
106
+ # the PEFT method).
107
+ GENERIC_QUANT_BACKENDS: tuple[str, ...] = (
108
+ "aqlm",
109
+ "awq",
110
+ "bnb_4bit",
111
+ "bnb_8bit",
112
+ "eetq",
113
+ "gptq",
114
+ "hqq",
115
+ "inc",
116
+ "torchao",
117
+ )
118
+
119
+ # Extra config arguments required to instantiate a method's config for probing, on top of the generic arguments
120
+ # (target_modules for adapter methods, task_type/num_virtual_tokens for prompt learning). If probing a method reports
121
+ # "unknown" because its config could not be instantiated, add an entry here.
122
+ PROBE_CONFIG_OVERRIDES: dict[PeftType, dict[str, Any]] = {
123
+ # total_step is a required argument
124
+ PeftType.ADALORA: {"total_step": 10},
125
+ # IA3 needs feedforward_modules
126
+ PeftType.IA3: {"feedforward_modules": []},
127
+ # the default block_size of 256 does not divide HIDDEN_DIM
128
+ PeftType.C3A: {"block_size": 16},
129
+ # token_indices defaults to an empty list, which trains nothing
130
+ PeftType.TRAINABLE_TOKENS: {"token_indices": [0, 1]},
131
+ # the default vector_length of 256 does not divide HIDDEN_DIM
132
+ PeftType.VBLORA: {"num_vectors": 32, "vector_length": 16},
133
+ PeftType.ADAPTION_PROMPT: {"adapter_layers": 1, "adapter_len": 4, "task_type": "CAUSAL_LM"},
134
+ }
135
+
136
+ # Methods that cannot be probed on a self-contained tiny model. Probe-based checks report "unknown" for these.
137
+ PROBE_SKIP: dict[PeftType, str] = {
138
+ PeftType.XLORA: "requires pre-trained LoRA adapter checkpoints to instantiate",
139
+ }
140
+
141
+ # Method-specific config switches that are worth surfacing as "extras". This is a curated list: reporting every config
142
+ # field would drown the relevant information in noise. Note that target_parameters is not listed here, as it is
143
+ # already covered by the target_layer_types check.
144
+ NOTABLE_CONFIG_FIELDS: tuple[str, ...] = (
145
+ "alpha_pattern",
146
+ "layer_replication",
147
+ "rank_pattern",
148
+ "use_dora",
149
+ "use_rslora",
150
+ )
151
+
152
+ # Docs page slugs that differ from the lower-cased PEFT method name.
153
+ DOCS_SLUG_OVERRIDES: dict[str, str] = {
154
+ "ADAPTION_PROMPT": "llama_adapter",
155
+ "CARTRIDGE": "cartridges",
156
+ "LN_TUNING": "layernorm_tuning",
157
+ }
158
+
159
+ # paper links as they appear in the docs intro paragraphs and in the config/model class docstrings
160
+ PAPER_URL_RE = re.compile(
161
+ r"https://(?:huggingface\.co/papers/|arxiv\.org/(?:abs|pdf)/|openreview\.net/forum\?id=)[^\s)\"'>]+"
162
+ )
163
+
164
+
165
+ class Source(enum.StrEnum):
166
+ INTROSPECTION = "introspection"
167
+ FILE_CHECK = "file_check"
168
+ PROBE = "probe"
169
+ ERROR = "error"
170
+
171
+
172
+ @dataclass(frozen=True)
173
+ class Finding:
174
+ value: Any
175
+ source: Source
176
+ note: str | None = None
177
+
178
+ def to_json(self) -> dict[str, Any]:
179
+ result: dict[str, Any] = {"value": self.value, "source": str(self.source)}
180
+ if self.note:
181
+ result["note"] = self.note
182
+ return result
183
+
184
+
185
+ @dataclass(frozen=True)
186
+ class MethodInfo:
187
+ peft_type: PeftType
188
+ config_cls: type[PeftConfig]
189
+ model_cls: type | None
190
+ category: str # "adapter", "prompt_learning", or "other"
191
+
192
+ @property
193
+ def name(self) -> str:
194
+ return self.peft_type.value
195
+
196
+ @classmethod
197
+ def from_peft_type(cls, peft_type: PeftType) -> "MethodInfo":
198
+ config_cls = PEFT_TYPE_TO_CONFIG_MAPPING[peft_type]
199
+ model_cls = PEFT_TYPE_TO_TUNER_MAPPING.get(peft_type)
200
+ if issubclass(config_cls, PromptLearningConfig):
201
+ category = "prompt_learning"
202
+ elif (model_cls is not None) and issubclass(model_cls, BaseTuner):
203
+ category = "adapter"
204
+ else:
205
+ # e.g. adaption prompt, whose model class manages adapters without subclassing BaseTuner
206
+ category = "other"
207
+ return cls(peft_type=peft_type, config_cls=config_cls, model_cls=model_cls, category=category)
208
+
209
+
210
+ def _layer_classes(method: MethodInfo) -> list[type[BaseTunerLayer]]:
211
+ """Return the tuner layer classes defined in the method's main layer module.
212
+
213
+ Quantization-specific layer variants (bnb.py etc.) are deliberately not considered: importing them depends on the
214
+ installed quantization libraries, and the main layer module is what determines baseline support.
215
+ """
216
+ tuner_layer_cls = getattr(method.model_cls, "tuner_layer_cls", None)
217
+ if tuner_layer_cls is None:
218
+ return []
219
+ module = sys.modules[tuner_layer_cls.__module__]
220
+ return [
221
+ obj
222
+ for obj in vars(module).values()
223
+ if isinstance(obj, type) and issubclass(obj, BaseTunerLayer) and obj.__module__ == module.__name__
224
+ ]
225
+
226
+
227
+ def _format_exception(exc: BaseException, limit: int = 250) -> str:
228
+ msg = f"{type(exc).__name__}: {exc}"
229
+ return msg if len(msg) <= limit else msg[: limit - 3] + "..."
230
+
231
+
232
+ class ProbeError(Exception):
233
+ """Raised when a probe cannot be set up; results in an 'unknown' finding, never in a false positive/negative."""
234
+
235
+
236
+ class SingleLayerModel(nn.Module):
237
+ """Minimal host model providing a single named module ("layer") for PEFT to target."""
238
+
239
+ def __init__(self, layer: nn.Module) -> None:
240
+ super().__init__()
241
+ self.layer = layer
242
+
243
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
244
+ return self.layer(x)
245
+
246
+
247
+ @dataclass(frozen=True)
248
+ class LayerSpec:
249
+ label: str
250
+ build: Callable[[], nn.Module]
251
+
252
+
253
+ # The layer types whose support is probed per method. Probing checks injection only (i.e. whether the layer gets
254
+ # wrapped), no forward pass, since a successful wrap is the support signal and a broken forward would be a bug.
255
+ LAYER_SPECS: tuple[LayerSpec, ...] = (
256
+ LayerSpec("Linear", lambda: nn.Linear(HIDDEN_DIM, HIDDEN_DIM)),
257
+ LayerSpec("Embedding", lambda: nn.Embedding(16, HIDDEN_DIM)),
258
+ LayerSpec("Conv1d", lambda: nn.Conv1d(HIDDEN_DIM, HIDDEN_DIM, 3)),
259
+ LayerSpec("Conv2d", lambda: nn.Conv2d(HIDDEN_DIM, HIDDEN_DIM, 3)),
260
+ LayerSpec("Conv3d", lambda: nn.Conv3d(HIDDEN_DIM, HIDDEN_DIM, 3)),
261
+ LayerSpec("LayerNorm", lambda: nn.LayerNorm(HIDDEN_DIM)),
262
+ LayerSpec("MultiheadAttention", lambda: nn.MultiheadAttention(HIDDEN_DIM, num_heads=4)),
263
+ LayerSpec("Conv1D (transformers)", lambda: Conv1D(HIDDEN_DIM, HIDDEN_DIM)),
264
+ )
265
+
266
+
267
+ class ProbeContext:
268
+ """Builds tiny throwaway models to exercise features on CPU.
269
+
270
+ The tiny transformer used for prompt learning methods is constructed from a config (no download) and cached; each
271
+ probe receives a deepcopy so that probes cannot contaminate each other.
272
+ """
273
+
274
+ def __init__(self) -> None:
275
+ self._tiny_lm: nn.Module | None = None
276
+
277
+ def make_config(self, method: MethodInfo, **kwargs: Any) -> PeftConfig:
278
+ if method.peft_type in PROBE_SKIP:
279
+ raise ProbeError(f"not probed: {PROBE_SKIP[method.peft_type]}")
280
+ kwargs = PROBE_CONFIG_OVERRIDES.get(method.peft_type, {}) | kwargs
281
+ try:
282
+ return method.config_cls(**kwargs)
283
+ except Exception as exc:
284
+ raise ProbeError(
285
+ f"could not instantiate {method.config_cls.__name__} for probing "
286
+ f"(consider adding an entry to PROBE_CONFIG_OVERRIDES): {_format_exception(exc)}"
287
+ ) from exc
288
+
289
+ def _probe_layer_and_input(self, method: MethodInfo) -> tuple[nn.Module, torch.Tensor]:
290
+ if method.peft_type == PeftType.TRAINABLE_TOKENS:
291
+ # trainable tokens only target embedding layers
292
+ return nn.Embedding(16, HIDDEN_DIM), torch.randint(0, 16, (2, 5))
293
+ return nn.Linear(HIDDEN_DIM, HIDDEN_DIM), torch.randn(2, HIDDEN_DIM)
294
+
295
+ def adapter_model(self, method: MethodInfo) -> tuple[nn.Module, torch.Tensor]:
296
+ """Return a PEFT model wrapping a single-layer host, plus a suitable example input."""
297
+ torch.manual_seed(0)
298
+ layer, example_input = self._probe_layer_and_input(method)
299
+ host = SingleLayerModel(layer)
300
+ config = self.make_config(method, target_modules=["layer"])
301
+ try:
302
+ return get_peft_model(host, config), example_input
303
+ except Exception as exc:
304
+ raise ProbeError(f"could not build probe model: {_format_exception(exc)}") from exc
305
+
306
+ def transformer_model(self, method: MethodInfo) -> nn.Module:
307
+ """Return a PEFT model on a tiny transformer, for methods that require one (prompt learning etc.)."""
308
+ if self._tiny_lm is None:
309
+ torch.manual_seed(0)
310
+ tiny_config = LlamaConfig(
311
+ vocab_size=64,
312
+ hidden_size=32,
313
+ intermediate_size=64,
314
+ num_hidden_layers=2,
315
+ num_attention_heads=4,
316
+ num_key_value_heads=4,
317
+ max_position_embeddings=64,
318
+ )
319
+ self._tiny_lm = LlamaForCausalLM(tiny_config)
320
+ kwargs: dict[str, Any] = {"task_type": "CAUSAL_LM"}
321
+ if method.category == "prompt_learning":
322
+ kwargs["num_virtual_tokens"] = 4
323
+ config = self.make_config(method, **kwargs)
324
+ try:
325
+ return get_peft_model(deepcopy(self._tiny_lm), config)
326
+ except Exception as exc:
327
+ raise ProbeError(f"could not build probe model: {_format_exception(exc)}") from exc
328
+
329
+ def second_config(self, method: MethodInfo) -> PeftConfig:
330
+ """A config suitable for adding a second adapter to a model built by this context."""
331
+ if method.category == "adapter":
332
+ return self.make_config(method, target_modules=["layer"])
333
+ kwargs: dict[str, Any] = {"task_type": "CAUSAL_LM"}
334
+ if method.category == "prompt_learning":
335
+ kwargs["num_virtual_tokens"] = 4
336
+ return self.make_config(method, **kwargs)
337
+
338
+
339
+ class Task(ABC):
340
+ """A single feature check for a single method. Never raises; failures become 'unknown' findings."""
341
+
342
+ feature: ClassVar[str]
343
+ description: ClassVar[str]
344
+
345
+ def __init__(self, method: MethodInfo, probe: ProbeContext) -> None:
346
+ self.method = method
347
+ self.probe = probe
348
+
349
+ @abstractmethod
350
+ def check(self) -> Finding: ...
351
+
352
+ def run(self) -> Finding:
353
+ try:
354
+ # Probing emits plenty of warnings that are expected and irrelevant here (e.g. about adapter
355
+ # initialization or fan_in_fan_out). Suppression is re-asserted per task instead of once globally, since
356
+ # libraries imported lazily during probing may manipulate the global warning filters.
357
+ with warnings.catch_warnings():
358
+ warnings.simplefilter("ignore")
359
+ return self.check()
360
+ except ProbeError as exc:
361
+ return Finding(value=UNKNOWN, source=Source.PROBE, note=str(exc))
362
+ except Exception as exc:
363
+ return Finding(value=UNKNOWN, source=Source.ERROR, note=_format_exception(exc))
364
+
365
+
366
+ class CategoryTask(Task):
367
+ feature = "category"
368
+ description = "whether the method is a layer-wrapping adapter, a prompt learning method, or something else"
369
+
370
+ def check(self) -> Finding:
371
+ return Finding(value=self.method.category, source=Source.INTROSPECTION)
372
+
373
+
374
+ class TargetLayerTypesTask(Task):
375
+ feature = "target_layer_types"
376
+ description = (
377
+ "which layer types (incl. nn.Parameter) can be targeted, probed by injecting into single-layer models"
378
+ )
379
+
380
+ def check(self) -> Finding:
381
+ if self.method.category != "adapter":
382
+ return Finding(
383
+ value=NOT_APPLICABLE, source=Source.INTROSPECTION, note="method does not wrap target layers"
384
+ )
385
+
386
+ results: dict[str, bool] = {}
387
+ first_error: str | None = None
388
+ for spec in LAYER_SPECS:
389
+ torch.manual_seed(0)
390
+ host = SingleLayerModel(spec.build())
391
+ config = self.probe.make_config(self.method, target_modules=["layer"])
392
+ try:
393
+ model = get_peft_model(host, config)
394
+ except Exception as exc:
395
+ results[spec.label] = False
396
+ if first_error is None:
397
+ first_error = f"{spec.label}: {_format_exception(exc)}"
398
+ else:
399
+ results[spec.label] = any(isinstance(module, BaseTunerLayer) for module in model.modules())
400
+
401
+ if not any(results.values()):
402
+ # if not even one layer type can be wrapped, the probe setup is likely at fault, not the method
403
+ raise ProbeError(f"no layer type could be wrapped, probe presumably mis-configured; {first_error}")
404
+
405
+ # Directly targeting nn.Parameter (crucial e.g. for MoE layers) is governed by the target_parameters config
406
+ # option; its presence is the support signal, no injection probe is needed.
407
+ field_names = {f.name for f in dataclasses.fields(self.method.config_cls)}
408
+ results["nn.Parameter"] = "target_parameters" in field_names
409
+ return Finding(
410
+ value=results,
411
+ source=Source.PROBE,
412
+ note="nn.Parameter support is based on the presence of the target_parameters config option",
413
+ )
414
+
415
+
416
+ class QuantizationTask(Task):
417
+ feature = "quantization_backends"
418
+ description = "supported quantization backends, from integration modules and use of the generic backend resolver"
419
+
420
+ def check(self) -> Finding:
421
+ if self.method.category == "prompt_learning":
422
+ return Finding(
423
+ value=NOT_APPLICABLE,
424
+ source=Source.INTROSPECTION,
425
+ note="prompt learning does not wrap target layers and generally works regardless of quantization",
426
+ )
427
+ if self.method.category != "adapter":
428
+ return Finding(value=UNKNOWN, source=Source.INTROSPECTION, note="no known quantization signal")
429
+
430
+ backends: set[str] = set()
431
+ package_dir = Path(inspect.getfile(self.method.model_cls)).parent
432
+ for stem, names in QUANT_FILE_BACKENDS.items():
433
+ if (package_dir / f"{stem}.py").exists():
434
+ backends.update(names)
435
+
436
+ # methods using the generic quantization integration support all backends the resolver handles
437
+ module_names = {self.method.model_cls.__module__}
438
+ if (tuner_layer_cls := getattr(self.method.model_cls, "tuner_layer_cls", None)) is not None:
439
+ module_names.add(tuner_layer_cls.__module__)
440
+ for module_name in module_names:
441
+ if "resolve_quantization_backend" in inspect.getsource(sys.modules[module_name]):
442
+ backends.update(GENERIC_QUANT_BACKENDS)
443
+ break
444
+
445
+ return Finding(value=sorted(backends), source=Source.FILE_CHECK)
446
+
447
+
448
+ class MultipleAdaptersTask(Task):
449
+ feature = "multiple_adapters"
450
+ description = "whether several adapters can be loaded on the same model, probed via add_adapter"
451
+
452
+ def check(self) -> Finding:
453
+ if self.method.category == "adapter":
454
+ model, _ = self.probe.adapter_model(self.method)
455
+ else:
456
+ model = self.probe.transformer_model(self.method)
457
+ try:
458
+ model.add_adapter("second", self.probe.second_config(self.method))
459
+ model.set_adapter("second")
460
+ except Exception as exc:
461
+ return Finding(value=False, source=Source.PROBE, note=_format_exception(exc))
462
+ return Finding(value=True, source=Source.PROBE)
463
+
464
+
465
+ class MixedAdapterBatchesTask(Task):
466
+ feature = "mixed_adapter_batches"
467
+ description = "whether one batch can mix several adapters via the adapter_names argument"
468
+
469
+ def check(self) -> Finding:
470
+ if self.method.category != "adapter":
471
+ return Finding(
472
+ value=False, source=Source.INTROSPECTION, note="only supported by layer-wrapping adapter methods"
473
+ )
474
+ # Support requires both halves of the mechanism: the model must install the forward hooks that distribute
475
+ # adapter_names, and the tuner layers must implement _mixed_batch_forward (possibly inherited, e.g. from
476
+ # LoRA). Checking only one of them would over-report.
477
+ model_supports_hooks = hasattr(self.method.model_cls, "_enable_peft_forward_hooks")
478
+ layer_classes = _layer_classes(self.method)
479
+ layer_supports = any(hasattr(cls, "_mixed_batch_forward") for cls in layer_classes)
480
+ return Finding(value=model_supports_hooks and layer_supports, source=Source.INTROSPECTION)
481
+
482
+
483
+ class MergeTask(Task):
484
+ feature = "merging"
485
+ description = "whether adapters can be merged into the base weights, verified via merge_and_unload"
486
+
487
+ def check(self) -> Finding:
488
+ if self.method.category == "prompt_learning":
489
+ return Finding(
490
+ value=False, source=Source.INTROSPECTION, note="virtual tokens cannot be merged into base weights"
491
+ )
492
+ if self.method.category != "adapter":
493
+ return Finding(value=False, source=Source.INTROSPECTION, note="method does not implement merging")
494
+
495
+ layer_classes = _layer_classes(self.method)
496
+ # BaseTunerLayer.merge raises NotImplementedError, so an unchanged merge attribute means no support
497
+ implemented = any(cls.merge is not BaseTunerLayer.merge for cls in layer_classes)
498
+ if not implemented:
499
+ return Finding(value=False, source=Source.INTROSPECTION, note="no tuner layer class implements merge()")
500
+
501
+ try:
502
+ model, example_input = self.probe.adapter_model(self.method)
503
+ model.eval()
504
+ with torch.no_grad():
505
+ output_before = model(example_input)
506
+ merged = model.merge_and_unload()
507
+ output_after = merged(example_input)
508
+ except ProbeError as exc:
509
+ return Finding(
510
+ value=True, source=Source.INTROSPECTION, note=f"merge() is implemented, but probing failed: {exc}"
511
+ )
512
+ except NotImplementedError as exc:
513
+ return Finding(value=False, source=Source.PROBE, note=_format_exception(exc))
514
+ except Exception as exc:
515
+ return Finding(
516
+ value=True,
517
+ source=Source.INTROSPECTION,
518
+ note=f"merge() is implemented, but probing failed: {_format_exception(exc)}",
519
+ )
520
+
521
+ note = None
522
+ if not torch.allclose(output_before, output_after, atol=1e-4):
523
+ note = "merged model outputs deviate from unmerged outputs beyond tolerance"
524
+ return Finding(value=True, source=Source.PROBE, note=note)
525
+
526
+
527
+ class MixedMethodModelTask(Task):
528
+ feature = "peft_mixed_model"
529
+ description = "whether the method can be combined with other method types in a PeftMixedModel"
530
+
531
+ def check(self) -> Finding:
532
+ # filled by register_peft_method(..., is_mixed_compatible=True)
533
+ value = self.method.peft_type in PEFT_TYPE_TO_MIXED_MODEL_MAPPING
534
+ return Finding(value=value, source=Source.INTROSPECTION)
535
+
536
+
537
+ class LoraConversionTask(Task):
538
+ feature = "lora_conversion"
539
+ description = "whether adapters of this method can be converted to a LoRA adapter"
540
+
541
+ def check(self) -> Finding:
542
+ if self.method.peft_type == PeftType.LORA:
543
+ return Finding(value=True, source=Source.INTROSPECTION, note="already a LoRA adapter")
544
+ if self.method.category != "adapter":
545
+ return Finding(value=False, source=Source.INTROSPECTION, note="method does not wrap target layers")
546
+
547
+ try:
548
+ model, _ = self.probe.adapter_model(self.method)
549
+ except ProbeError as exc:
550
+ # fall back to a static signal; an override does not guarantee support, hence the note
551
+ layer_classes = _layer_classes(self.method)
552
+ overridden = any(
553
+ cls.supports_lora_conversion is not BaseTunerLayer.supports_lora_conversion for cls in layer_classes
554
+ )
555
+ return Finding(
556
+ value=overridden,
557
+ source=Source.INTROSPECTION,
558
+ note=f"based on presence of a supports_lora_conversion override; probing failed: {exc}",
559
+ )
560
+
561
+ layer = next(module for module in model.modules() if isinstance(module, BaseTunerLayer))
562
+ return Finding(value=bool(layer.supports_lora_conversion("default")), source=Source.PROBE)
563
+
564
+
565
+ class WeightedAdapterTask(Task):
566
+ feature = "add_weighted_adapter"
567
+ description = "whether several adapters can be combined into a new one, probed via add_weighted_adapter"
568
+
569
+ def check(self) -> Finding:
570
+ # Methods without the API don't support the feature; methods that inherit it but override it with a stub
571
+ # that raises (e.g. AdaLoRA) are caught by the probe below.
572
+ if getattr(self.method.model_cls, "add_weighted_adapter", None) is None:
573
+ return Finding(value=False, source=Source.INTROSPECTION)
574
+
575
+ model, _ = self.probe.adapter_model(self.method)
576
+ # combining several adapters requires loading several adapters in the first place; methods that already fail
577
+ # here cannot support add_weighted_adapter either
578
+ try:
579
+ model.add_adapter("second", self.probe.second_config(self.method))
580
+ except Exception as exc:
581
+ return Finding(
582
+ value=False,
583
+ source=Source.PROBE,
584
+ note=f"a second adapter could not be added: {_format_exception(exc)}",
585
+ )
586
+ try:
587
+ model.add_weighted_adapter(adapters=["default", "second"], weights=[0.5, 0.5], adapter_name="combined")
588
+ except Exception as exc:
589
+ return Finding(value=False, source=Source.PROBE, note=_format_exception(exc))
590
+ return Finding(value=True, source=Source.PROBE)
591
+
592
+
593
+ class HotswapTask(Task):
594
+ feature = "hotswapping"
595
+ description = "whether adapters can be hot-swapped in place (peft.utils.hotswap)"
596
+
597
+ def check(self) -> Finding:
598
+ return Finding(value=self.method.peft_type in CONFIG_KEYS_TO_CHECK, source=Source.INTROSPECTION)
599
+
600
+
601
+ class AuxiliaryModulesTask(Task):
602
+ feature = "auxiliary_modules"
603
+ description = "whether the config supports modules_to_save and trainable_token_indices"
604
+
605
+ def check(self) -> Finding:
606
+ field_names = {f.name for f in dataclasses.fields(self.method.config_cls)}
607
+ value = {
608
+ "modules_to_save": "modules_to_save" in field_names,
609
+ "trainable_token_indices": "trainable_token_indices" in field_names,
610
+ }
611
+ return Finding(value=value, source=Source.INTROSPECTION)
612
+
613
+
614
+ class ExtrasTask(Task):
615
+ feature = "extras"
616
+ description = "notable method-specific config options (curated list)"
617
+
618
+ def check(self) -> Finding:
619
+ field_names = {f.name for f in dataclasses.fields(self.method.config_cls)}
620
+ value = sorted(field_names.intersection(NOTABLE_CONFIG_FIELDS))
621
+ return Finding(value=value, source=Source.INTROSPECTION)
622
+
623
+
624
+ class PaperLinkTask(Task):
625
+ feature = "paper_url"
626
+ description = "link to the method's paper, from the docs intro or class docstrings (omitted when ambiguous)"
627
+
628
+ # default assumes the script lives in scripts/ of a repository checkout; can be overridden via --docs-dir
629
+ docs_dir: ClassVar[Path] = Path(__file__).parent.parent / "docs" / "source" / "package_reference"
630
+
631
+ def _docs_intro(self) -> str | None:
632
+ """The first paragraph after the first heading of the method's docs page (the pages start with a license
633
+ comment, a `# Title` heading, and a prose paragraph)."""
634
+ slug = DOCS_SLUG_OVERRIDES.get(self.method.name, self.method.name.lower())
635
+ try:
636
+ text = (self.docs_dir / f"{slug}.md").read_text()
637
+ except OSError:
638
+ return None
639
+ text = re.sub(r"<!--.*?-->", "", text, flags=re.DOTALL)
640
+ match = re.search(r"^# .+?$\s+(.+?)(?:\n\s*\n|$)", text, flags=re.MULTILINE | re.DOTALL)
641
+ return match.group(1) if match else None
642
+
643
+ def check(self) -> Finding:
644
+ # Sources in order of preference; the first one containing exactly one distinct paper URL wins. A source
645
+ # with no link, or with several different ones (e.g. docstrings that also cite related methods), is skipped
646
+ # as ambiguous -- a missing paper link is better than a wrong one.
647
+ sources: list[tuple[str, str | None]] = [
648
+ ("docs intro", self._docs_intro()),
649
+ ("config class docstring", self.method.config_cls.__doc__),
650
+ ("model class docstring", self.method.model_cls.__doc__ if self.method.model_cls is not None else None),
651
+ ]
652
+ for source_name, text in sources:
653
+ if not text:
654
+ continue
655
+ urls = set(PAPER_URL_RE.findall(text))
656
+ if len(urls) == 1:
657
+ return Finding(value=urls.pop(), source=Source.FILE_CHECK, note=f"from the {source_name}")
658
+ return Finding(
659
+ value=None,
660
+ source=Source.FILE_CHECK,
661
+ note="no unambiguous paper link in the docs intro or the config/model class docstrings",
662
+ )
663
+
664
+
665
+ # the order here determines the order of the features in the output
666
+ TASK_CLASSES: tuple[type[Task], ...] = (
667
+ CategoryTask,
668
+ TargetLayerTypesTask,
669
+ QuantizationTask,
670
+ MultipleAdaptersTask,
671
+ MixedAdapterBatchesTask,
672
+ MergeTask,
673
+ MixedMethodModelTask,
674
+ LoraConversionTask,
675
+ WeightedAdapterTask,
676
+ HotswapTask,
677
+ AuxiliaryModulesTask,
678
+ ExtrasTask,
679
+ PaperLinkTask,
680
+ )
681
+
682
+
683
+ def collect_methods(selected: list[str] | None) -> list[MethodInfo]:
684
+ registered = sorted(PEFT_TYPE_TO_CONFIG_MAPPING, key=lambda peft_type: peft_type.value)
685
+ if selected is not None:
686
+ valid = {peft_type.value for peft_type in registered}
687
+ requested = [name.upper() for name in selected]
688
+ if unknown := [name for name in requested if name not in valid]:
689
+ raise SystemExit(
690
+ f"Unknown PEFT method(s): {', '.join(unknown)}. Valid choices: {', '.join(sorted(valid))}"
691
+ )
692
+ registered = [peft_type for peft_type in registered if peft_type.value in requested]
693
+ return [MethodInfo.from_peft_type(peft_type) for peft_type in registered]
694
+
695
+
696
+ def collect_tasks(methods: list[MethodInfo], probe: ProbeContext) -> list[Task]:
697
+ return [task_cls(method, probe) for method in methods for task_cls in TASK_CLASSES]
698
+
699
+
700
+ def run_tasks(tasks: list[Task]) -> dict[str, dict[str, Any]]:
701
+ results: dict[str, dict[str, Any]] = {}
702
+ for task in tqdm(tasks, desc="Checking capabilities", unit="check"):
703
+ method = task.method
704
+ entry = results.setdefault(
705
+ method.name,
706
+ {
707
+ "config_class": method.config_cls.__name__,
708
+ "model_class": method.model_cls.__name__ if method.model_cls is not None else None,
709
+ "features": {},
710
+ },
711
+ )
712
+ entry["features"][task.feature] = task.run().to_json()
713
+ return results
714
+
715
+
716
+ def main(argv: list[str] | None = None) -> None:
717
+ parser = argparse.ArgumentParser(
718
+ description="Generate a JSON capability matrix of all PEFT methods.",
719
+ epilog="Example: python scripts/generate_method_capabilities.py --methods lora ia3 --output capabilities.json",
720
+ )
721
+ parser.add_argument(
722
+ "--methods",
723
+ "-m",
724
+ nargs="+",
725
+ default=None,
726
+ metavar="METHOD",
727
+ help="restrict the analysis to these PEFT methods (case-insensitive, e.g. 'lora ia3'); default: all",
728
+ )
729
+ parser.add_argument(
730
+ "--output",
731
+ "-o",
732
+ type=Path,
733
+ default=Path("method_capabilities.json"),
734
+ help="output JSON file (default: %(default)s)",
735
+ )
736
+ parser.add_argument("--dry-run", action="store_true", help="only list the checks that would run")
737
+ parser.add_argument(
738
+ "--docs-dir",
739
+ type=Path,
740
+ default=PaperLinkTask.docs_dir,
741
+ help="directory containing the package_reference docs pages, used for the paper link check",
742
+ )
743
+ args = parser.parse_args(argv)
744
+ PaperLinkTask.docs_dir = args.docs_dir
745
+ logging.basicConfig(level=logging.INFO, format="%(message)s") # logs to stderr
746
+
747
+ methods = collect_methods(args.methods)
748
+ probe = ProbeContext()
749
+ tasks = collect_tasks(methods, probe)
750
+
751
+ if args.dry_run:
752
+ for method in methods:
753
+ print(f"{method.name}: {', '.join(task_cls.feature for task_cls in TASK_CLASSES)}")
754
+ print(f"\n{len(methods)} methods x {len(TASK_CLASSES)} checks = {len(tasks)} tasks")
755
+ return
756
+
757
+ output = {
758
+ "schema_version": 1,
759
+ "peft_version": peft.__version__,
760
+ "methods": run_tasks(tasks),
761
+ }
762
+ # The results deliberately go to a file, not to stdout: probing can trigger subprocesses whose output is written
763
+ # directly to stdout (e.g. BOFT compiling its CUDA extension via ninja), which would interleave with the JSON.
764
+ args.output.write_text(json.dumps(output, indent=2) + "\n")
765
+ logger.info(f"Wrote capabilities of {len(methods)} methods to {args.output}")
766
+
767
+
768
+ if __name__ == "__main__":
769
+ main()
tasks/tasksmith-c488fc138ba1/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-c488fc138ba1/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-c488fc138ba1/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-c488fc138ba1/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-c488fc138ba1/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-c488fc138ba1/environment/source/src/peft/__init__.py ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ FrodConfig,
74
+ FrodModel,
75
+ GraloraConfig,
76
+ GraloraModel,
77
+ HiraConfig,
78
+ HiraModel,
79
+ HRAConfig,
80
+ HRAModel,
81
+ IA3Config,
82
+ IA3Model,
83
+ LilyConfig,
84
+ LilyModel,
85
+ LNTuningConfig,
86
+ LNTuningModel,
87
+ LoftQConfig,
88
+ LoHaConfig,
89
+ LoHaModel,
90
+ LoKrConfig,
91
+ LoKrModel,
92
+ LoraConfig,
93
+ LoraGAConfig,
94
+ LoraModel,
95
+ LoraRuntimeConfig,
96
+ MissConfig,
97
+ MissModel,
98
+ MontecloraConfig,
99
+ MultitaskPromptTuningConfig,
100
+ MultitaskPromptTuningInit,
101
+ OFTConfig,
102
+ OFTModel,
103
+ OSFConfig,
104
+ OSFModel,
105
+ PeanutConfig,
106
+ PeanutModel,
107
+ PolyConfig,
108
+ PolyModel,
109
+ PrefixEncoder,
110
+ PrefixTuningConfig,
111
+ PromptEmbedding,
112
+ PromptEncoder,
113
+ PromptEncoderConfig,
114
+ PromptEncoderReparameterizationType,
115
+ PromptTuningConfig,
116
+ PromptTuningInit,
117
+ PsoftConfig,
118
+ PsoftModel,
119
+ PveraConfig,
120
+ PveraModel,
121
+ RandLoraConfig,
122
+ RandLoraModel,
123
+ RoadConfig,
124
+ RoadModel,
125
+ ShiraConfig,
126
+ ShiraModel,
127
+ TinyLoraConfig,
128
+ TinyLoraModel,
129
+ TrainableTokensConfig,
130
+ TrainableTokensModel,
131
+ VBLoRAConfig,
132
+ VBLoRAModel,
133
+ VeloraConfig,
134
+ VeraConfig,
135
+ VeraModel,
136
+ WaveFTConfig,
137
+ WaveFTModel,
138
+ XLoraConfig,
139
+ XLoraModel,
140
+ convert_to_lora,
141
+ create_arrow_model,
142
+ get_eva_state_dict,
143
+ initialize_lora_eva_weights,
144
+ preprocess_loraga,
145
+ save_as_lora,
146
+ )
147
+ from .tuners.cartridge.utils import (
148
+ compose_cartridge_adapters,
149
+ initialize_kv_prefix_from_past_key_values,
150
+ initialize_kv_prefix_from_text,
151
+ prompt_embeddings_from_past_key_values,
152
+ )
153
+ from .utils import (
154
+ TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING,
155
+ PeftType,
156
+ PeftWarning,
157
+ TaskType,
158
+ bloom_model_postprocess_past_key_value,
159
+ cast_mixed_precision_params,
160
+ get_peft_model_state_dict,
161
+ load_peft_weights,
162
+ prepare_model_for_kbit_training,
163
+ replace_lora_weights_loftq,
164
+ set_peft_model_state_dict,
165
+ shift_tokens_right,
166
+ )
167
+
168
+
169
+ __all__ = [
170
+ "MODEL_TYPE_TO_PEFT_MODEL_MAPPING",
171
+ "PEFT_TYPE_TO_CONFIG_MAPPING",
172
+ "PEFT_TYPE_TO_MIXED_MODEL_MAPPING",
173
+ "PEFT_TYPE_TO_TUNER_MAPPING",
174
+ "TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING",
175
+ "AdaLoraConfig",
176
+ "AdaLoraModel",
177
+ "AdamssConfig",
178
+ "AdamssModel",
179
+ "AdaptionPromptConfig",
180
+ "AdaptionPromptModel",
181
+ "ArrowConfig",
182
+ "AutoPeftModel",
183
+ "AutoPeftModelForCausalLM",
184
+ "AutoPeftModelForFeatureExtraction",
185
+ "AutoPeftModelForQuestionAnswering",
186
+ "AutoPeftModelForSeq2SeqLM",
187
+ "AutoPeftModelForSequenceClassification",
188
+ "AutoPeftModelForTokenClassification",
189
+ "BOFTConfig",
190
+ "BOFTModel",
191
+ "BdLoraConfig",
192
+ "BeftConfig",
193
+ "BeftModel",
194
+ "C3AConfig",
195
+ "C3AModel",
196
+ "CPTConfig",
197
+ "CPTEmbedding",
198
+ "CartridgeConfig",
199
+ "CartridgeEncoder",
200
+ "DeloraConfig",
201
+ "DeloraModel",
202
+ "EvaConfig",
203
+ "FourierFTConfig",
204
+ "FourierFTModel",
205
+ "FrodConfig",
206
+ "FrodModel",
207
+ "GraloraConfig",
208
+ "GraloraModel",
209
+ "HRAConfig",
210
+ "HRAModel",
211
+ "HiraConfig",
212
+ "HiraModel",
213
+ "IA3Config",
214
+ "IA3Model",
215
+ "LNTuningConfig",
216
+ "LNTuningModel",
217
+ "LilyConfig",
218
+ "LilyModel",
219
+ "LoHaConfig",
220
+ "LoHaModel",
221
+ "LoKrConfig",
222
+ "LoKrModel",
223
+ "LoftQConfig",
224
+ "LoraConfig",
225
+ "LoraGAConfig",
226
+ "LoraModel",
227
+ "LoraRuntimeConfig",
228
+ "MissConfig",
229
+ "MissModel",
230
+ "MontecloraConfig",
231
+ "MultitaskPromptTuningConfig",
232
+ "MultitaskPromptTuningInit",
233
+ "OFTConfig",
234
+ "OFTModel",
235
+ "OSFConfig",
236
+ "OSFModel",
237
+ "PeanutConfig",
238
+ "PeanutModel",
239
+ "PeftConfig",
240
+ "PeftMixedModel",
241
+ "PeftModel",
242
+ "PeftModelForCausalLM",
243
+ "PeftModelForFeatureExtraction",
244
+ "PeftModelForQuestionAnswering",
245
+ "PeftModelForSeq2SeqLM",
246
+ "PeftModelForSequenceClassification",
247
+ "PeftModelForTokenClassification",
248
+ "PeftType",
249
+ "PeftWarning",
250
+ "PolyConfig",
251
+ "PolyModel",
252
+ "PrefixEncoder",
253
+ "PrefixTuningConfig",
254
+ "PromptEmbedding",
255
+ "PromptEncoder",
256
+ "PromptEncoderConfig",
257
+ "PromptEncoderReparameterizationType",
258
+ "PromptLearningConfig",
259
+ "PromptTuningConfig",
260
+ "PromptTuningInit",
261
+ "PsoftConfig",
262
+ "PsoftModel",
263
+ "PveraConfig",
264
+ "PveraModel",
265
+ "RandLoraConfig",
266
+ "RandLoraModel",
267
+ "RoadConfig",
268
+ "RoadModel",
269
+ "ShiraConfig",
270
+ "ShiraModel",
271
+ "TaskType",
272
+ "TinyLoraConfig",
273
+ "TinyLoraModel",
274
+ "TrainableTokensConfig",
275
+ "TrainableTokensModel",
276
+ "VBLoRAConfig",
277
+ "VBLoRAConfig",
278
+ "VBLoRAModel",
279
+ "VeloraConfig",
280
+ "VeraConfig",
281
+ "VeraModel",
282
+ "WaveFTConfig",
283
+ "WaveFTModel",
284
+ "XLoraConfig",
285
+ "XLoraModel",
286
+ "bloom_model_postprocess_past_key_value",
287
+ "cast_mixed_precision_params",
288
+ "compose_cartridge_adapters",
289
+ "convert_to_lora",
290
+ "create_arrow_model",
291
+ "find_kappa_target_modules",
292
+ "get_eva_state_dict",
293
+ "get_layer_status",
294
+ "get_model_status",
295
+ "get_peft_config",
296
+ "get_peft_model",
297
+ "get_peft_model_state_dict",
298
+ "initialize_kv_prefix_from_past_key_values",
299
+ "initialize_kv_prefix_from_text",
300
+ "initialize_lora_eva_weights",
301
+ "inject_adapter_in_model",
302
+ "load_peft_weights",
303
+ "prepare_model_for_kbit_training",
304
+ "preprocess_loraga",
305
+ "prompt_embeddings_from_past_key_values",
306
+ "replace_lora_weights_loftq",
307
+ "save_as_lora",
308
+ "set_peft_model_state_dict",
309
+ "shift_tokens_right",
310
+ ]
tasks/tasksmith-c488fc138ba1/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-c488fc138ba1/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-c488fc138ba1/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-c488fc138ba1/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-c488fc138ba1/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-c488fc138ba1/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-c488fc138ba1/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-c488fc138ba1/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-c488fc138ba1/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-c488fc138ba1/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-c488fc138ba1/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-c488fc138ba1/environment/source/src/peft/peft_model.py ADDED
The diff for this file is too large to render. See raw diff
 
tasks/tasksmith-c488fc138ba1/environment/source/src/peft/py.typed ADDED
File without changes
tasks/tasksmith-c488fc138ba1/environment/source/src/peft/tuners/__init__.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 .frod import FrodConfig, FrodModel
26
+ from .gralora import GraloraConfig, GraloraModel
27
+ from .hira import HiraConfig, HiraModel
28
+ from .hra import HRAConfig, HRAModel
29
+ from .ia3 import IA3Config, IA3Model
30
+ from .lily import LilyConfig, LilyModel
31
+ from .ln_tuning import LNTuningConfig, LNTuningModel
32
+ from .loha import LoHaConfig, LoHaModel
33
+ from .lokr import LoKrConfig, LoKrModel
34
+ from .lora import (
35
+ ArrowConfig,
36
+ BdLoraConfig,
37
+ EvaConfig,
38
+ LoftQConfig,
39
+ LoraConfig,
40
+ LoraGAConfig,
41
+ LoraModel,
42
+ LoraRuntimeConfig,
43
+ MontecloraConfig,
44
+ VeloraConfig,
45
+ convert_to_lora,
46
+ create_arrow_model,
47
+ get_eva_state_dict,
48
+ initialize_lora_eva_weights,
49
+ preprocess_loraga,
50
+ save_as_lora,
51
+ )
52
+ from .miss import MissConfig, MissModel
53
+ from .mixed import MixedModel
54
+ from .multitask_prompt_tuning import MultitaskPromptEmbedding, MultitaskPromptTuningConfig, MultitaskPromptTuningInit
55
+ from .oft import OFTConfig, OFTModel
56
+ from .osf import OSFConfig, OSFModel
57
+ from .p_tuning import PromptEncoder, PromptEncoderConfig, PromptEncoderReparameterizationType
58
+ from .peanut import PeanutConfig, PeanutModel
59
+ from .poly import PolyConfig, PolyModel
60
+ from .prefix_tuning import PrefixEncoder, PrefixTuningConfig
61
+ from .prompt_tuning import PromptEmbedding, PromptTuningConfig, PromptTuningInit
62
+ from .psoft import PsoftConfig, PsoftModel
63
+ from .pvera import PveraConfig, PveraModel
64
+ from .randlora import RandLoraConfig, RandLoraModel
65
+ from .road import RoadConfig, RoadModel
66
+ from .shira import ShiraConfig, ShiraModel
67
+ from .tinylora import TinyLoraConfig, TinyLoraModel
68
+ from .trainable_tokens import TrainableTokensConfig, TrainableTokensModel
69
+ from .vblora import VBLoRAConfig, VBLoRAModel
70
+ from .vera import VeraConfig, VeraModel
71
+ from .waveft import WaveFTConfig, WaveFTModel
72
+ from .xlora import XLoraConfig, XLoraModel
73
+
74
+
75
+ __all__ = [
76
+ "AdaLoraConfig",
77
+ "AdaLoraModel",
78
+ "AdamssConfig",
79
+ "AdamssModel",
80
+ "AdaptionPromptConfig",
81
+ "AdaptionPromptModel",
82
+ "ArrowConfig",
83
+ "BOFTConfig",
84
+ "BOFTModel",
85
+ "BdLoraConfig",
86
+ "BeftConfig",
87
+ "BeftModel",
88
+ "C3AConfig",
89
+ "C3AModel",
90
+ "CPTConfig",
91
+ "CPTEmbedding",
92
+ "CartridgeConfig",
93
+ "CartridgeEncoder",
94
+ "DeloraConfig",
95
+ "DeloraModel",
96
+ "EvaConfig",
97
+ "FourierFTConfig",
98
+ "FourierFTModel",
99
+ "FrodConfig",
100
+ "FrodModel",
101
+ "GraloraConfig",
102
+ "GraloraModel",
103
+ "HRAConfig",
104
+ "HRAModel",
105
+ "HiraConfig",
106
+ "HiraModel",
107
+ "IA3Config",
108
+ "IA3Model",
109
+ "LNTuningConfig",
110
+ "LNTuningModel",
111
+ "LilyConfig",
112
+ "LilyModel",
113
+ "LoHaConfig",
114
+ "LoHaModel",
115
+ "LoKrConfig",
116
+ "LoKrModel",
117
+ "LoftQConfig",
118
+ "LoraConfig",
119
+ "LoraGAConfig",
120
+ "LoraModel",
121
+ "LoraRuntimeConfig",
122
+ "MissConfig",
123
+ "MissModel",
124
+ "MixedModel",
125
+ "MontecloraConfig",
126
+ "MultitaskPromptEmbedding",
127
+ "MultitaskPromptTuningConfig",
128
+ "MultitaskPromptTuningInit",
129
+ "OFTConfig",
130
+ "OFTModel",
131
+ "OSFConfig",
132
+ "OSFModel",
133
+ "PeanutConfig",
134
+ "PeanutModel",
135
+ "PolyConfig",
136
+ "PolyModel",
137
+ "PrefixEncoder",
138
+ "PrefixTuningConfig",
139
+ "PromptEmbedding",
140
+ "PromptEncoder",
141
+ "PromptEncoderConfig",
142
+ "PromptEncoderReparameterizationType",
143
+ "PromptTuningConfig",
144
+ "PromptTuningInit",
145
+ "PsoftConfig",
146
+ "PsoftModel",
147
+ "PveraConfig",
148
+ "PveraModel",
149
+ "RandLoraConfig",
150
+ "RandLoraModel",
151
+ "RoadConfig",
152
+ "RoadModel",
153
+ "ShiraConfig",
154
+ "ShiraModel",
155
+ "TinyLoraConfig",
156
+ "TinyLoraModel",
157
+ "TrainableTokensConfig",
158
+ "TrainableTokensModel",
159
+ "VBLoRAConfig",
160
+ "VBLoRAModel",
161
+ "VeloraConfig",
162
+ "VeraConfig",
163
+ "VeraModel",
164
+ "WaveFTConfig",
165
+ "WaveFTModel",
166
+ "XLoraConfig",
167
+ "XLoraModel",
168
+ "convert_to_lora",
169
+ "create_arrow_model",
170
+ "get_eva_state_dict",
171
+ "initialize_lora_eva_weights",
172
+ "preprocess_loraga",
173
+ "save_as_lora",
174
+ ]
tasks/tasksmith-c488fc138ba1/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-c488fc138ba1/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-c488fc138ba1/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-c488fc138ba1/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-c488fc138ba1/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-c488fc138ba1/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-c488fc138ba1/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-c488fc138ba1/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-c488fc138ba1/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-c488fc138ba1/environment/source/src/peft/tuners/adamss/config.py ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ random_seed: int = field(
321
+ default=0,
322
+ metadata={
323
+ "help": (
324
+ "Seed used to deterministically create and rebuild the adapter weights, so that a saved adapter "
325
+ "reproduces its outputs after loading. Default: 0."
326
+ )
327
+ },
328
+ )
329
+
330
+ def __post_init__(self):
331
+ self.peft_type = PeftType.ADAMSS
332
+ self.target_modules = (
333
+ set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules
334
+ )
335
+ super().__post_init__()
336
+
337
+ # Normalize init_weights: convert False to None for backward compatibility
338
+ if self.init_weights is False:
339
+ self.init_weights = None
340
+
341
+ # Validate initialization method
342
+ if self.init_weights not in ["orthogonal", None]:
343
+ raise ValueError(f"init_weights must be 'orthogonal' or None, got {self.init_weights}")
344
+
345
+ # Early check for scikit-learn availability
346
+ try:
347
+ import sklearn # noqa: F401
348
+ except ImportError:
349
+ raise ImportError("scikit-learn is required for AdaMSS. Please install it with: pip install scikit-learn")
tasks/tasksmith-c488fc138ba1/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, random_seed=config.random_seed)
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-c488fc138ba1/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-c488fc138ba1/environment/source/src/peft/tuners/adamss/utils.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, random_seed=0):
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
+ random_seed: seed for the random projection used by `torch.svd_lowrank`, so the decomposition is
28
+ deterministic and reproducible across save/load
29
+
30
+ Returns:
31
+ VVT: Right singular vectors (B, C, r, W) UU: Left singular vectors (B, C, H, r)
32
+ """
33
+ tensor = tensor.to(device)
34
+ B, C, H, W = tensor.shape
35
+
36
+ # Clamp r to the minimum dimension to avoid SVD errors
37
+ # SVD rank cannot exceed min(H, W)
38
+ effective_r = min(r, H, W)
39
+
40
+ UU = torch.zeros(B, C, H, effective_r, dtype=dtype, device=device)
41
+ VVT = torch.zeros(B, C, effective_r, W, dtype=dtype, device=device)
42
+
43
+ # torch.svd_lowrank draws a random projection internally, so its result (and hence the downstream
44
+ # clustering and scatter_index) depends on the RNG state. Seed a forked RNG with the configurable
45
+ # random_seed so the result is deterministic (torch.svd_lowrank does not accept a generator argument);
46
+ # fork_rng leaves the global RNG stream untouched.
47
+ fork_devices = [device] if torch.device(device).type == "cuda" else []
48
+ with torch.random.fork_rng(devices=fork_devices):
49
+ torch.manual_seed(random_seed)
50
+ for i in range(B):
51
+ for j in range(C):
52
+ U, _, V = torch.svd_lowrank(tensor[i, j, :, :], q=effective_r, niter=2, M=None)
53
+ UU[i, j, :, :] = U[:, 0:effective_r]
54
+ VVT[i, j, :, :] = V[:, 0:effective_r].T
55
+ # Return computed matrices (important: ensure callers receive VVT and UU)
56
+ return VVT, UU
57
+
58
+
59
+ def clustering_Z(VT, num_subspaces, iternum):
60
+ """
61
+ Cluster the rows of VT into K subspaces using K-Means.
62
+
63
+ Args:
64
+ VT: Matrix to cluster (rows are clustered)
65
+ num_subspaces: Number of clusters (subspaces)
66
+ iternum: Maximum iterations for K-Means
67
+
68
+ Returns:
69
+ cluster_idx: Cluster assignments as a ``torch.LongTensor`` effective_num_subspaces: Actual number of subspaces
70
+ used (``int``)
71
+
72
+ Note:
73
+ This function requires scikit-learn to be installed. Install it with: pip install scikit-learn
74
+ """
75
+ # Local import with helpful error message
76
+ try:
77
+ from sklearn.cluster import KMeans
78
+ except ImportError:
79
+ raise ImportError(
80
+ "scikit-learn is required for AdaMSS initialization. Please install it with: pip install scikit-learn"
81
+ )
82
+
83
+ # Move to numpy for sklearn compatibility
84
+ # Note: We do NOT normalize row vectors here to match the original adamss_pkg behavior.
85
+ # Although normalization is generally recommended for cosine-similarity-like clustering,
86
+ # the reference implementation clusters raw singular vectors.
87
+ vt = VT.detach().cpu().numpy().astype("float32")
88
+
89
+ # Auto-clamp num_subspaces to available samples (output dimensions)
90
+ # Cannot cluster n samples into more than n clusters
91
+ effective_num_subspaces = min(num_subspaces, vt.shape[0])
92
+
93
+ kmeans = KMeans(
94
+ n_clusters=effective_num_subspaces, init="random", n_init=1, max_iter=iternum, random_state=123456789
95
+ )
96
+ idx = kmeans.fit_predict(vt)
97
+
98
+ return torch.from_numpy(idx).long(), effective_num_subspaces
99
+
100
+
101
+ def seg_locations(index):
102
+ """
103
+ Segment indices into locations based on cluster assignments.
104
+
105
+ Args:
106
+ index: Cluster assignments as a ``torch.LongTensor``
107
+
108
+ Returns:
109
+ location: Dict mapping cluster id to ``torch.LongTensor`` of row indices.
110
+ Clusters are ordered by their smallest index so that KMeans label permutations do not affect downstream
111
+ ordering.
112
+ """
113
+ K = int(index.max().item()) + 1
114
+ location = {}
115
+ for i in range(K):
116
+ location[i] = torch.where(index == i)[0]
117
+ return location
118
+
119
+
120
+ def get_trainable_subspaces(num_subspaces):
121
+ """
122
+ Get all trainable subspace indices.
123
+
124
+ Args:
125
+ num_subspaces: Number of subspaces
126
+
127
+ Returns:
128
+ List of trainable subspace indices (``list[int]``)
129
+ """
130
+ return list(range(num_subspaces))
tasks/tasksmith-c488fc138ba1/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-c488fc138ba1/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-c488fc138ba1/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, *_