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

Stage Harbor release files 73001-73500

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/tests/source/examples/int8_training/config.yaml +19 -0
  2. tasks/tasksmith-c488fc138ba1/tests/source/examples/int8_training/fine_tune_blip2_int8.py +104 -0
  3. tasks/tasksmith-c488fc138ba1/tests/source/examples/int8_training/peft_adalora_whisper_large_training.py +817 -0
  4. tasks/tasksmith-c488fc138ba1/tests/source/examples/int8_training/peft_bnb_whisper_large_v2_training.ipynb +0 -0
  5. tasks/tasksmith-c488fc138ba1/tests/source/examples/int8_training/requirements.txt +9 -0
  6. tasks/tasksmith-c488fc138ba1/tests/source/examples/int8_training/run_adalora_whisper_int8.sh +37 -0
  7. tasks/tasksmith-c488fc138ba1/tests/source/examples/lily_finetuning/README.md +90 -0
  8. tasks/tasksmith-c488fc138ba1/tests/source/examples/lily_finetuning/lily_finetuning.py +190 -0
  9. tasks/tasksmith-c488fc138ba1/tests/source/examples/loftq_finetuning/LoftQ_weight_replacement.ipynb +801 -0
  10. tasks/tasksmith-c488fc138ba1/tests/source/examples/loftq_finetuning/README.md +144 -0
  11. tasks/tasksmith-c488fc138ba1/tests/source/examples/loftq_finetuning/int8_correction.py +279 -0
  12. tasks/tasksmith-c488fc138ba1/tests/source/examples/loftq_finetuning/quantize_save_load.py +193 -0
  13. tasks/tasksmith-c488fc138ba1/tests/source/examples/loftq_finetuning/train_gsm8k_llama.py +851 -0
  14. tasks/tasksmith-c488fc138ba1/tests/source/examples/lora_dreambooth/colab_notebook.ipynb +54 -0
  15. tasks/tasksmith-c488fc138ba1/tests/source/examples/lora_dreambooth/convert_kohya_ss_sd_lora_to_peft.py +175 -0
  16. tasks/tasksmith-c488fc138ba1/tests/source/examples/lora_dreambooth/convert_peft_sd_lora_to_kohya_ss.py +100 -0
  17. tasks/tasksmith-c488fc138ba1/tests/source/examples/lora_dreambooth/lora_dreambooth_inference.ipynb +0 -0
  18. tasks/tasksmith-c488fc138ba1/tests/source/examples/lora_dreambooth/requirements.txt +11 -0
  19. tasks/tasksmith-c488fc138ba1/tests/source/examples/lora_dreambooth/train_dreambooth.py +1107 -0
  20. tasks/tasksmith-c488fc138ba1/tests/source/examples/lora_finetuning_transformer_engine/Dockerfile +8 -0
  21. tasks/tasksmith-c488fc138ba1/tests/source/examples/lora_finetuning_transformer_engine/README.md +119 -0
  22. tasks/tasksmith-c488fc138ba1/tests/source/examples/lora_finetuning_transformer_engine/lora_finetuning_te.py +329 -0
  23. tasks/tasksmith-c488fc138ba1/tests/source/examples/lora_finetuning_transformer_engine/requirements.txt +12 -0
  24. tasks/tasksmith-c488fc138ba1/tests/source/examples/lora_ga_finetuning/README.md +295 -0
  25. tasks/tasksmith-c488fc138ba1/tests/source/examples/lora_ga_finetuning/lora_ga_finetuning.py +279 -0
  26. tasks/tasksmith-c488fc138ba1/tests/source/examples/lorafa_finetune/README.md +121 -0
  27. tasks/tasksmith-c488fc138ba1/tests/source/examples/lorafa_finetune/lorafa_finetuning.py +221 -0
  28. tasks/tasksmith-c488fc138ba1/tests/source/examples/miss_finetuning/README.md +106 -0
  29. tasks/tasksmith-c488fc138ba1/tests/source/examples/miss_finetuning/miss_finetuning.py +109 -0
  30. tasks/tasksmith-c488fc138ba1/tests/source/examples/monteclora_finetuning/sequence_classification_finetune_monteclora.py +203 -0
  31. tasks/tasksmith-c488fc138ba1/tests/source/examples/multi_adapter_examples/Lora_Merging.ipynb +194 -0
  32. tasks/tasksmith-c488fc138ba1/tests/source/examples/multi_adapter_examples/PEFT_Multi_LoRA_Inference.ipynb +367 -0
  33. tasks/tasksmith-c488fc138ba1/tests/source/examples/multi_adapter_examples/multi_adapter_weighted_inference_diffusers.ipynb +0 -0
  34. tasks/tasksmith-c488fc138ba1/tests/source/examples/multilayer_perceptron/README.md +5 -0
  35. tasks/tasksmith-c488fc138ba1/tests/source/examples/multilayer_perceptron/multilayer_perceptron_lora.ipynb +752 -0
  36. tasks/tasksmith-c488fc138ba1/tests/source/examples/oft_dreambooth/oft_dreambooth_inference.ipynb +0 -0
  37. tasks/tasksmith-c488fc138ba1/tests/source/examples/oft_dreambooth/train_dreambooth.py +1115 -0
  38. tasks/tasksmith-c488fc138ba1/tests/source/examples/olora_finetuning/README.md +96 -0
  39. tasks/tasksmith-c488fc138ba1/tests/source/examples/olora_finetuning/olora_finetuning.py +199 -0
  40. tasks/tasksmith-c488fc138ba1/tests/source/examples/orthogonal_subspace_learning/README.md +299 -0
  41. tasks/tasksmith-c488fc138ba1/tests/source/examples/orthogonal_subspace_learning/osf_continual_learning.py +693 -0
  42. tasks/tasksmith-c488fc138ba1/tests/source/examples/orthogonal_subspace_learning/utils.py +304 -0
  43. tasks/tasksmith-c488fc138ba1/tests/source/examples/peanut_finetuning/README.md +86 -0
  44. tasks/tasksmith-c488fc138ba1/tests/source/examples/peanut_finetuning/peanut_finetuning.py +207 -0
  45. tasks/tasksmith-c488fc138ba1/tests/source/examples/pissa_finetuning/README.md +131 -0
  46. tasks/tasksmith-c488fc138ba1/tests/source/examples/pissa_finetuning/pissa_finetuning.py +150 -0
  47. tasks/tasksmith-c488fc138ba1/tests/source/examples/pissa_finetuning/preprocess.py +69 -0
  48. tasks/tasksmith-c488fc138ba1/tests/source/examples/poly/peft_poly_seq2seq_with_generate.ipynb +0 -0
  49. tasks/tasksmith-c488fc138ba1/tests/source/examples/psoft_finetuning/README.md +77 -0
  50. tasks/tasksmith-c488fc138ba1/tests/source/examples/psoft_finetuning/psoft_finetuning.py +182 -0
tasks/tasksmith-c488fc138ba1/tests/source/examples/int8_training/config.yaml ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ compute_environment: LOCAL_MACHINE
2
+ debug: false
3
+ distributed_type: MULTI_XPU
4
+ downcast_bf16: 'no'
5
+ enable_cpu_affinity: false
6
+ gpu_ids: all
7
+ ipex_config:
8
+ ipex: false
9
+ machine_rank: 0
10
+ main_training_function: main
11
+ mixed_precision: 'no'
12
+ num_machines: 1
13
+ num_processes: 4
14
+ rdzv_backend: static
15
+ same_network: true
16
+ tpu_env: []
17
+ tpu_use_cluster: false
18
+ tpu_use_sudo: false
19
+ use_cpu: false
tasks/tasksmith-c488fc138ba1/tests/source/examples/int8_training/fine_tune_blip2_int8.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import torch
15
+ from datasets import load_dataset
16
+ from torch.utils.data import DataLoader, Dataset
17
+ from transformers import AutoModelForVision2Seq, AutoProcessor, BitsAndBytesConfig
18
+
19
+ from peft import LoraConfig, get_peft_model
20
+
21
+
22
+ # Let's define the LoraConfig
23
+ config = LoraConfig(
24
+ r=16,
25
+ lora_alpha=32,
26
+ lora_dropout=0.05,
27
+ bias="none",
28
+ )
29
+
30
+ # We load our model and processor using `transformers`
31
+ model = AutoModelForVision2Seq.from_pretrained(
32
+ "Salesforce/blip2-opt-2.7b", quantization_config=BitsAndBytesConfig(load_in_8bit=True)
33
+ )
34
+ processor = AutoProcessor.from_pretrained("Salesforce/blip2-opt-2.7b")
35
+
36
+ # Get our peft model and print the number of trainable parameters
37
+ model = get_peft_model(model, config)
38
+ model.print_trainable_parameters()
39
+
40
+ # Let's load the dataset here!
41
+ dataset = load_dataset("ybelkada/football-dataset", split="train")
42
+
43
+
44
+ class ImageCaptioningDataset(Dataset):
45
+ def __init__(self, dataset, processor):
46
+ self.dataset = dataset
47
+ self.processor = processor
48
+
49
+ def __len__(self):
50
+ return len(self.dataset)
51
+
52
+ def __getitem__(self, idx):
53
+ item = self.dataset[idx]
54
+ encoding = self.processor(images=item["image"], padding="max_length", return_tensors="pt")
55
+ # remove batch dimension
56
+ encoding = {k: v.squeeze() for k, v in encoding.items()}
57
+ encoding["text"] = item["text"]
58
+ return encoding
59
+
60
+
61
+ def collator(batch):
62
+ # pad the input_ids and attention_mask
63
+ processed_batch = {}
64
+ for key in batch[0].keys():
65
+ if key != "text":
66
+ processed_batch[key] = torch.stack([example[key] for example in batch])
67
+ else:
68
+ text_inputs = processor.tokenizer(
69
+ [example["text"] for example in batch], padding=True, return_tensors="pt"
70
+ )
71
+ processed_batch["input_ids"] = text_inputs["input_ids"]
72
+ processed_batch["attention_mask"] = text_inputs["attention_mask"]
73
+ return processed_batch
74
+
75
+
76
+ train_dataset = ImageCaptioningDataset(dataset, processor)
77
+ train_dataloader = DataLoader(train_dataset, shuffle=True, batch_size=2, collate_fn=collator)
78
+
79
+ optimizer = torch.optim.AdamW(model.parameters(), lr=5e-5)
80
+
81
+ device = torch.accelerator.current_accelerator().type if hasattr(torch, "accelerator") else "cuda"
82
+
83
+ model.train()
84
+
85
+ for epoch in range(50):
86
+ print("Epoch:", epoch)
87
+ for idx, batch in enumerate(train_dataloader):
88
+ input_ids = batch.pop("input_ids").to(device)
89
+ pixel_values = batch.pop("pixel_values").to(device, torch.float16)
90
+
91
+ outputs = model(input_ids=input_ids, pixel_values=pixel_values, labels=input_ids)
92
+
93
+ loss = outputs.loss
94
+
95
+ print("Loss:", loss.item())
96
+
97
+ loss.backward()
98
+
99
+ optimizer.step()
100
+ optimizer.zero_grad()
101
+
102
+ if idx % 10 == 0:
103
+ generated_output = model.generate(pixel_values=pixel_values)
104
+ print(processor.batch_decode(generated_output, skip_special_tokens=True))
tasks/tasksmith-c488fc138ba1/tests/source/examples/int8_training/peft_adalora_whisper_large_training.py ADDED
@@ -0,0 +1,817 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import gc
3
+ import json
4
+ import logging
5
+ import math
6
+ import os
7
+ from dataclasses import dataclass
8
+ from datetime import datetime, timezone
9
+ from pathlib import Path
10
+ from random import randint
11
+ from typing import Any, Union
12
+
13
+ # datasets imports
14
+ import datasets
15
+
16
+ # metric imports
17
+ import evaluate
18
+ import numpy as np
19
+ import torch
20
+ import transformers
21
+ import wandb
22
+
23
+ # accelerate imports
24
+ from accelerate import Accelerator, dispatch_model
25
+ from accelerate.logging import get_logger
26
+ from datasets import Audio, DatasetDict, IterableDatasetDict, interleave_datasets, load_dataset
27
+
28
+ # hf imports
29
+ from huggingface_hub import HfApi
30
+ from torch.utils.data import DataLoader
31
+ from tqdm import tqdm
32
+ from transformers import (
33
+ BitsAndBytesConfig,
34
+ SchedulerType,
35
+ WhisperForConditionalGeneration,
36
+ WhisperProcessor,
37
+ get_scheduler,
38
+ set_seed,
39
+ )
40
+ from transformers.models.whisper.english_normalizer import BasicTextNormalizer
41
+
42
+ # peft imports
43
+ from peft import AdaLoraConfig, LoraConfig, PeftModel, get_peft_model
44
+
45
+
46
+ logger = get_logger(__name__, log_level="INFO")
47
+
48
+
49
+ def parse_args():
50
+ parser = argparse.ArgumentParser(description="Whisper Fine-Tuning with AdaLora")
51
+ parser.add_argument(
52
+ "--model_name_or_path",
53
+ type=str,
54
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
55
+ required=True,
56
+ )
57
+ parser.add_argument("--language", type=str, help="Language to use for training; e.g., 'Hindi' ", required=True)
58
+ parser.add_argument("--language_abbr", type=str, help="Language to use for training; e.g., 'hi' ", required=True)
59
+ parser.add_argument(
60
+ "--task", type=str, default="transcribe", help="Task to use for training; e.g., 'transcribe' ", required=False
61
+ )
62
+ parser.add_argument(
63
+ "--dataset_name",
64
+ type=str,
65
+ default="mozilla-foundation/common_voice_11_0",
66
+ help="Dataset to use for training; e.g., 'whisper' ",
67
+ required=False,
68
+ )
69
+ parser.add_argument(
70
+ "--dataset_in_streaming_mode",
71
+ action="store_true",
72
+ help="Whether to use streaming mode for the dataset.",
73
+ )
74
+ parser.add_argument(
75
+ "--do_lower_case", action="store_true", help="lowercase the transcribed text before tokenizing"
76
+ )
77
+ parser.add_argument(
78
+ "--do_remove_punctuation", action="store_true", help="remove punctuation from the transcribed text"
79
+ )
80
+ parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
81
+ parser.add_argument(
82
+ "--overwrite_cache", type=bool, default=False, help="Overwrite the cached training and evaluation sets"
83
+ )
84
+ parser.add_argument("--max_audio_input_length", type=float, default=30.0, help="Maximum audio length in seconds.")
85
+ parser.add_argument(
86
+ "--preprocessing_num_workers",
87
+ type=int,
88
+ default=None,
89
+ help="The number of processes to use for the preprocessing.",
90
+ )
91
+ parser.add_argument(
92
+ "--per_device_train_batch_size",
93
+ type=int,
94
+ default=8,
95
+ help="Batch size (per device) for the training dataloader.",
96
+ )
97
+ parser.add_argument(
98
+ "--per_device_eval_batch_size",
99
+ type=int,
100
+ default=8,
101
+ help="Batch size (per device) for the evaluation dataloader.",
102
+ )
103
+ parser.add_argument(
104
+ "--buffer_size",
105
+ type=int,
106
+ default=5000,
107
+ help="Number of samples to prefetch in the streaming mode.",
108
+ )
109
+ parser.add_argument(
110
+ "--dataloader_pin_memory",
111
+ action="store_true",
112
+ help="Whether or not to pin memory for the DataLoader.",
113
+ )
114
+ parser.add_argument(
115
+ "--dataloader_num_workers",
116
+ type=int,
117
+ default=0,
118
+ help="Number of subprocesses to use for data loading.",
119
+ )
120
+ parser.add_argument(
121
+ "--learning_rate",
122
+ type=float,
123
+ default=5e-5,
124
+ help="Initial learning rate (after the potential warmup period) to use.",
125
+ )
126
+ parser.add_argument("--weight_decay", type=float, default=0.0, help="Weight decay to use.")
127
+ parser.add_argument("--num_train_epochs", type=int, default=3, help="Total number of training epochs to perform.")
128
+ parser.add_argument(
129
+ "--max_train_steps",
130
+ type=int,
131
+ default=None,
132
+ help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
133
+ )
134
+ parser.add_argument(
135
+ "--gradient_accumulation_steps",
136
+ type=int,
137
+ default=1,
138
+ help="Number of updates steps to accumulate before performing a backward/update pass.",
139
+ )
140
+ parser.add_argument(
141
+ "--lr_scheduler_type",
142
+ type=SchedulerType,
143
+ default="linear",
144
+ help="The scheduler type to use.",
145
+ choices=["linear", "cosine", "cosine_with_restarts", "polynomial", "constant", "constant_with_warmup"],
146
+ )
147
+ parser.add_argument(
148
+ "--num_warmup_steps", type=int, default=0, help="Number of steps for the warmup in the lr scheduler."
149
+ )
150
+ parser.add_argument("--output_dir", type=str, default=None, help="Where to store the final model.")
151
+ parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
152
+ parser.add_argument(
153
+ "--load_best_model",
154
+ action="store_true",
155
+ help="Whether to load the best model at the end of training",
156
+ )
157
+ parser.add_argument(
158
+ "--with_tracking",
159
+ action="store_true",
160
+ help="Whether to enable experiment trackers for logging.",
161
+ )
162
+ parser.add_argument(
163
+ "--report_to",
164
+ type=str,
165
+ default="all",
166
+ help=(
167
+ 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`,'
168
+ ' `"wandb"` and `"comet_ml"`. Use `"all"` (default) to report to all integrations.'
169
+ "Only applicable when `--with_tracking` is passed."
170
+ ),
171
+ )
172
+ parser.add_argument("--hub_token", type=str, help="The token to use to push to the Model Hub.")
173
+ parser.add_argument(
174
+ "--hub_model_id", type=str, help="The name of the repository to keep in sync with the local `output_dir`."
175
+ )
176
+ parser.add_argument(
177
+ "--checkpointing_steps",
178
+ type=int,
179
+ default=500,
180
+ help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.",
181
+ )
182
+ parser.add_argument(
183
+ "--logging_steps",
184
+ type=int,
185
+ default=100,
186
+ help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.",
187
+ )
188
+ parser.add_argument(
189
+ "--evaluation_steps",
190
+ type=int,
191
+ default=500,
192
+ help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.",
193
+ )
194
+ parser.add_argument(
195
+ "--resume_from_checkpoint",
196
+ type=str,
197
+ default=None,
198
+ help="If the training should continue from a checkpoint folder.",
199
+ )
200
+
201
+ # lora/adalora specific args
202
+ parser.add_argument(
203
+ "--use_peft",
204
+ action="store_true",
205
+ help="Whether to use PEFT",
206
+ )
207
+ parser.add_argument(
208
+ "--use_adalora",
209
+ action="store_true",
210
+ help="Whether to use AdaLoRA or LoRA. If set, uses AdaLoRA instead of the default LoRA.",
211
+ )
212
+ parser.add_argument(
213
+ "--init_r",
214
+ type=int,
215
+ default=12,
216
+ help="Initial AdaLoRA rank",
217
+ )
218
+ parser.add_argument(
219
+ "--target_r",
220
+ type=int,
221
+ default=4,
222
+ help="Target AdaLoRA rank",
223
+ )
224
+ parser.add_argument(
225
+ "--tinit",
226
+ type=int,
227
+ default=200,
228
+ help="number of warmup steps for AdaLoRA wherein no pruning is performed",
229
+ )
230
+ parser.add_argument(
231
+ "--tfinal",
232
+ type=int,
233
+ default=1000,
234
+ help=" fix the resulting budget distribution and fine-tune the model for tfinal steps when using AdaLoRA ",
235
+ )
236
+ parser.add_argument(
237
+ "--delta_t",
238
+ type=int,
239
+ default=10,
240
+ help="interval of steps for AdaLoRA to update rank",
241
+ )
242
+ parser.add_argument(
243
+ "--lora_alpha",
244
+ type=int,
245
+ default=32,
246
+ help="LORA alpha",
247
+ )
248
+ parser.add_argument(
249
+ "--r",
250
+ type=int,
251
+ default=8,
252
+ help="LORA rank",
253
+ )
254
+ parser.add_argument(
255
+ "--lora_dropout",
256
+ type=float,
257
+ default=0.1,
258
+ help="LORA dropout",
259
+ )
260
+ parser.add_argument(
261
+ "--orth_reg_weight",
262
+ type=float,
263
+ default=0.5,
264
+ help="Orthogonal regularization weight",
265
+ )
266
+ parser.add_argument(
267
+ "--debug_mode",
268
+ action="store_true",
269
+ help="Whether to use debug mode",
270
+ )
271
+
272
+ args = parser.parse_args()
273
+
274
+ if args.push_to_hub:
275
+ assert args.output_dir is not None, "Need an `output_dir` to create a repo when `--push_to_hub` is passed."
276
+
277
+ return args
278
+
279
+
280
+ def load_streaming_dataset(dataset_name, dataset_config_name, split, **kwargs):
281
+ if "+" in split:
282
+ # load multiple splits separated by the `+` symbol *with* streaming mode
283
+ dataset_splits = [
284
+ load_dataset(dataset_name, dataset_config_name, split=split_name, streaming=True, **kwargs)
285
+ for split_name in split.split("+")
286
+ ]
287
+ # interleave multiple splits to form one dataset
288
+ interleaved_dataset = interleave_datasets(dataset_splits)
289
+ return interleaved_dataset
290
+ else:
291
+ # load a single split *with* streaming mode
292
+ dataset = load_dataset(dataset_name, dataset_config_name, split=split, streaming=True, **kwargs)
293
+ return dataset
294
+
295
+
296
+ def prepare_dataset_wrapper(do_lower_case, do_remove_punctuation, processor, normalizer):
297
+ def prepare_dataset(batch):
298
+ # load and (possibly) resample audio data to 16kHz
299
+ audio = batch["audio"]
300
+
301
+ # compute log-Mel input features from input audio array
302
+ batch["input_features"] = processor.feature_extractor(
303
+ audio["array"], sampling_rate=audio["sampling_rate"]
304
+ ).input_features[0]
305
+ # compute input length of audio sample in seconds
306
+ batch["input_length"] = len(audio["array"]) / audio["sampling_rate"]
307
+
308
+ # optional pre-processing steps
309
+ transcription = batch["sentence"]
310
+ if do_lower_case:
311
+ transcription = transcription.lower()
312
+ if do_remove_punctuation:
313
+ transcription = normalizer(transcription).strip()
314
+
315
+ # encode target text to label ids
316
+ batch["labels"] = processor.tokenizer(transcription).input_ids
317
+ return batch
318
+
319
+ return prepare_dataset
320
+
321
+
322
+ def save_model_hook(models, weights, output_dir):
323
+ for model in models:
324
+ model.save_pretrained(output_dir)
325
+ # make sure to pop weight so that corresponding model is not saved again
326
+ weights.pop()
327
+
328
+
329
+ def load_model_hook(models, input_dir):
330
+ while len(models) > 0:
331
+ model = models.pop()
332
+ # pop models so that they are not loaded again
333
+ PeftModel.from_pretrained(model.base_model.model, input_dir)
334
+
335
+
336
+ @dataclass
337
+ class DataCollatorSpeechSeq2SeqWithPadding:
338
+ processor: Any
339
+
340
+ def __call__(self, features: list[dict[str, Union[list[int], torch.Tensor]]]) -> dict[str, torch.Tensor]:
341
+ # split inputs and labels since they have to be of different lengths and need different padding methods
342
+ # first treat the audio inputs by simply returning torch tensors
343
+ input_features = [{"input_features": feature["input_features"]} for feature in features]
344
+ batch = self.processor.feature_extractor.pad(input_features, return_tensors="pt")
345
+
346
+ # get the tokenized label sequences
347
+ label_features = [{"input_ids": feature["labels"]} for feature in features]
348
+ # pad the labels to max length
349
+ labels_batch = self.processor.tokenizer.pad(label_features, return_tensors="pt")
350
+
351
+ # replace padding with -100 to ignore loss correctly
352
+ labels = labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1), -100)
353
+
354
+ # if bos token is appended in previous tokenization step,
355
+ # cut bos token here as it's append later anyways
356
+ if (labels[:, 0] == self.processor.tokenizer.bos_token_id).all().cpu().item():
357
+ labels = labels[:, 1:]
358
+
359
+ batch["labels"] = labels
360
+
361
+ return batch
362
+
363
+
364
+ def get_audio_length_processor(max_input_length):
365
+ def is_audio_in_length_range(length):
366
+ return length < max_input_length
367
+
368
+ return is_audio_in_length_range
369
+
370
+
371
+ def evaluation_loop(model, eval_dataloader, processor, normalizer, metric, forced_decoder_ids, accelerator):
372
+ model.eval()
373
+ predictions = []
374
+ references = []
375
+ normalized_predictions = []
376
+ normalized_references = []
377
+ device_type = torch.accelerator.current_accelerator().type if hasattr(torch, "accelerator") else "cuda"
378
+ for _, batch in enumerate(tqdm(eval_dataloader)):
379
+ with torch.amp.autocast(device_type=device_type):
380
+ with torch.no_grad():
381
+ generated_tokens = (
382
+ model.generate(
383
+ input_features=batch["input_features"],
384
+ forced_decoder_ids=forced_decoder_ids,
385
+ max_new_tokens=255,
386
+ )
387
+ .cpu()
388
+ .numpy()
389
+ )
390
+ labels = batch["labels"].cpu().numpy()
391
+ labels = np.where(labels != -100, labels, processor.tokenizer.pad_token_id)
392
+ decoded_preds = processor.tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)
393
+ decoded_labels = processor.tokenizer.batch_decode(labels, skip_special_tokens=True)
394
+ predictions.extend(decoded_preds)
395
+ references.extend(decoded_labels)
396
+ normalized_predictions.extend([normalizer(pred).strip() for pred in decoded_preds])
397
+ normalized_references.extend([normalizer(label).strip() for label in decoded_labels])
398
+ del generated_tokens, labels, batch
399
+ gc.collect()
400
+ wer = 100 * metric.compute(predictions=predictions, references=references)
401
+ normalized_wer = 100 * metric.compute(predictions=normalized_predictions, references=normalized_references)
402
+ eval_metrics = {"eval/wer": wer, "eval/normalized_wer": normalized_wer}
403
+ if accelerator.get_tracker("wandb"):
404
+ sample_size = min(len(predictions), 256)
405
+ ids = [randint(0, len(predictions) - 1) for p in range(sample_size)]
406
+ sample_predictions = [predictions[i] for i in ids]
407
+ sample_references = [references[i] for i in ids]
408
+ sample_normalized_predictions = [normalized_predictions[i] for i in ids]
409
+ sample_normalized_references = [normalized_references[i] for i in ids]
410
+ table_rows = [
411
+ list(r)
412
+ for r in zip(
413
+ sample_predictions, sample_references, sample_normalized_predictions, sample_normalized_references
414
+ )
415
+ ]
416
+ eval_metrics["eval_samples"] = wandb.Table(
417
+ columns=["predictions", "references", "normalized_predictions", "normalized_references"],
418
+ rows=table_rows,
419
+ )
420
+ return eval_metrics
421
+
422
+
423
+ def main():
424
+ args = parse_args()
425
+
426
+ accelerator_kwargs = {"gradient_accumulation_steps": args.gradient_accumulation_steps}
427
+ if args.with_tracking:
428
+ accelerator_kwargs["log_with"] = args.report_to
429
+ accelerator_kwargs["project_dir"] = args.output_dir
430
+ accelerator = Accelerator(**accelerator_kwargs)
431
+
432
+ # Make one log on every process with the configuration for debugging.
433
+ logging.basicConfig(
434
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
435
+ datefmt="%m/%d/%Y %H:%M:%S",
436
+ level=logging.INFO,
437
+ )
438
+ logger.info(accelerator.state, main_process_only=False)
439
+ if accelerator.is_local_main_process:
440
+ datasets.utils.logging.set_verbosity_warning()
441
+ transformers.utils.logging.set_verbosity_info()
442
+ else:
443
+ datasets.utils.logging.set_verbosity_error()
444
+ transformers.utils.logging.set_verbosity_error()
445
+
446
+ # If passed along, set the training seed now.
447
+ if args.seed is not None:
448
+ set_seed(args.seed)
449
+
450
+ # Handle the repository creation
451
+ if accelerator.is_main_process:
452
+ if args.push_to_hub:
453
+ api = HfApi(token=args.hub_token)
454
+
455
+ # Create repo (repo_name from args or inferred)
456
+ repo_name = args.hub_model_id
457
+ if repo_name is None:
458
+ repo_name = Path(args.output_dir).absolute().name
459
+ repo_id = api.create_repo(repo_name, exist_ok=True).repo_id
460
+
461
+ with open(os.path.join(args.output_dir, ".gitignore"), "w+") as gitignore:
462
+ if "step_*" not in gitignore:
463
+ gitignore.write("step_*\n")
464
+ if "epoch_*" not in gitignore:
465
+ gitignore.write("epoch_*\n")
466
+ elif args.output_dir is not None:
467
+ os.makedirs(args.output_dir, exist_ok=True)
468
+ accelerator.wait_for_everyone()
469
+
470
+ # load dataset either in streaming mode or not
471
+ processor = WhisperProcessor.from_pretrained(args.model_name_or_path, language=args.language, task=args.task)
472
+ normalizer = BasicTextNormalizer()
473
+ prepare_dataset = prepare_dataset_wrapper(args.do_lower_case, args.do_remove_punctuation, processor, normalizer)
474
+ is_audio_in_length_range = get_audio_length_processor(args.max_audio_input_length)
475
+ data_collator = DataCollatorSpeechSeq2SeqWithPadding(processor=processor)
476
+
477
+ if args.dataset_in_streaming_mode:
478
+ raw_datasets = IterableDatasetDict()
479
+ loading_method = load_streaming_dataset
480
+ else:
481
+ raw_datasets = DatasetDict()
482
+ loading_method = load_dataset
483
+
484
+ if args.debug_mode:
485
+ train_split = "train[:100]"
486
+ test_split = "test[:10]"
487
+ else:
488
+ train_split = "train+validation"
489
+ test_split = "test"
490
+
491
+ raw_datasets["train"] = loading_method(args.dataset_name, args.language_abbr, split=train_split)
492
+ raw_datasets["test"] = loading_method(args.dataset_name, args.language_abbr, split=test_split)
493
+ raw_datasets = raw_datasets.cast_column("audio", Audio(sampling_rate=16000))
494
+
495
+ logger.info("Dataset loaded: %s", raw_datasets)
496
+ logger.info(f"{raw_datasets['train'][0]}")
497
+
498
+ vectorized_datasets = raw_datasets.map(
499
+ prepare_dataset,
500
+ remove_columns=list(next(iter(raw_datasets.values())).features),
501
+ num_proc=args.preprocessing_num_workers,
502
+ ).with_format("torch")
503
+
504
+ if args.dataset_in_streaming_mode:
505
+ vectorized_datasets["train"] = vectorized_datasets["train"].shuffle(
506
+ buffer_size=args.buffer_size,
507
+ seed=args.seed,
508
+ )
509
+
510
+ # filter out audio files that are too long from the training set
511
+ is_audio_in_length_range = get_audio_length_processor(args.max_audio_input_length)
512
+ vectorized_datasets["train"] = vectorized_datasets["train"].filter(
513
+ is_audio_in_length_range, input_columns=["input_length"]
514
+ )
515
+
516
+ # get dataloaders
517
+ train_dataloader = DataLoader(
518
+ vectorized_datasets["train"],
519
+ batch_size=args.per_device_train_batch_size,
520
+ shuffle=True,
521
+ collate_fn=data_collator,
522
+ num_workers=args.dataloader_num_workers,
523
+ pin_memory=args.dataloader_pin_memory,
524
+ )
525
+ eval_dataloader = DataLoader(
526
+ vectorized_datasets["test"],
527
+ batch_size=args.per_device_eval_batch_size,
528
+ collate_fn=data_collator,
529
+ num_workers=args.dataloader_num_workers,
530
+ pin_memory=args.dataloader_pin_memory,
531
+ )
532
+
533
+ # metric
534
+ metric = evaluate.load("wer")
535
+
536
+ # model
537
+ model = WhisperForConditionalGeneration.from_pretrained(
538
+ args.model_name_or_path, quantization_config=BitsAndBytesConfig(load_in_8bit=True)
539
+ )
540
+ model.config.forced_decoder_ids = None
541
+ model.config.suppress_tokens = []
542
+ if hasattr(model, "hf_device_map") and len(set(model.hf_device_map.values()).intersection({"cpu", "disk"})) > 0:
543
+ raise ValueError("Training on CPU or disk is not supported.")
544
+ if hasattr(model, "hf_device_map") and len(set(model.hf_device_map.values())) > 1:
545
+ device_map = model.hf_device_map.copy()
546
+ # required because `labels` are on main execution device (0) while the output of `proj_out` is on other device.
547
+ # So, this leads to device mismatch error when calculation cross-entropy between logits and labels.
548
+ # Won't arise during inference as `labels` aren't supplied during that time
549
+ # instead of changing device of one of the tied modules, I have to do this for all tied modules
550
+ # else the execution device of remaining tied modules isn't changed
551
+ device_map["model.decoder.embed_tokens"] = model._hf_hook.execution_device
552
+ device_map["model.decoder.embed_positions"] = model._hf_hook.execution_device
553
+ device_map["proj_out"] = model._hf_hook.execution_device
554
+ dispatch_model(model, device_map=device_map)
555
+
556
+ # preparing peft model
557
+ if args.use_peft:
558
+ from peft import prepare_model_for_kbit_training
559
+
560
+ model = prepare_model_for_kbit_training(model)
561
+
562
+ # as Whisper model uses Conv layer in encoder, checkpointing disables grad computation
563
+ # to avoid this, make the inputs trainable
564
+ def make_inputs_require_grad(module, input, output):
565
+ output.requires_grad_(True)
566
+
567
+ model.model.encoder.conv1.register_forward_hook(make_inputs_require_grad)
568
+
569
+ # Calculate total steps first for AdaLoRA
570
+ if args.max_train_steps is None:
571
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
572
+ total_steps = args.num_train_epochs * num_update_steps_per_epoch
573
+ else:
574
+ total_steps = args.max_train_steps
575
+
576
+ # wrapping model with adalora tuner
577
+ if args.use_adalora:
578
+ config = AdaLoraConfig(
579
+ init_r=args.init_r,
580
+ target_r=args.target_r,
581
+ beta1=0.85,
582
+ beta2=0.85,
583
+ tinit=args.tinit,
584
+ tfinal=args.tfinal,
585
+ deltaT=args.delta_t,
586
+ lora_alpha=args.lora_alpha,
587
+ lora_dropout=args.lora_dropout,
588
+ target_modules=["k_proj", "q_proj", "v_proj", "out_proj", "fc1", "fc2"],
589
+ orth_reg_weight=args.orth_reg_weight,
590
+ total_step=total_steps,
591
+ )
592
+ else:
593
+ config = LoraConfig(
594
+ r=args.r,
595
+ lora_alpha=args.lora_alpha,
596
+ target_modules=["q_proj", "v_proj"],
597
+ lora_dropout=args.lora_dropout,
598
+ )
599
+
600
+ model = get_peft_model(model, config)
601
+ model.print_trainable_parameters()
602
+
603
+ # optimizer
604
+ optimizer = torch.optim.AdamW(model.parameters(), lr=args.learning_rate, weight_decay=args.weight_decay)
605
+
606
+ if args.max_train_steps is None:
607
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
608
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
609
+ else:
610
+ args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
611
+
612
+ # scheduler
613
+ lr_scheduler = get_scheduler(
614
+ name=args.lr_scheduler_type,
615
+ optimizer=optimizer,
616
+ num_warmup_steps=args.num_warmup_steps,
617
+ num_training_steps=args.max_train_steps,
618
+ )
619
+
620
+ # Prepare everything with our `accelerator`.
621
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
622
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
623
+ )
624
+
625
+ accelerator.print(model)
626
+
627
+ # Note here that the max steps is adjusted by the accelerator's num_processes
628
+ args.max_train_steps = math.ceil(args.max_train_steps / accelerator.num_processes)
629
+ if args.use_peft and args.use_adalora:
630
+ # Update the total_step in the config to reflect the adjusted max_train_steps
631
+ # Handle DDP case where model is wrapped
632
+ if hasattr(model, "module"):
633
+ # DDP case
634
+ model.module.base_model.peft_config["default"].total_step = args.max_train_steps
635
+ else:
636
+ # Non-DDP case
637
+ model.base_model.peft_config["default"].total_step = args.max_train_steps
638
+
639
+ # We need to initialize the trackers we use, and also store our configuration.
640
+ # The trackers initializes automatically on the main process.
641
+ if args.with_tracking:
642
+ run_name = f"run-{datetime.now(timezone.utc).strftime('%Y-%m-%d_%H-%M-%S')}"
643
+ experiment_config = vars(args)
644
+ # TensorBoard cannot log Enums, need the raw value
645
+ experiment_config["lr_scheduler_type"] = experiment_config["lr_scheduler_type"].value
646
+ accelerator.init_trackers(
647
+ "Whisper PEFT Fine-Tuning", config=experiment_config, init_kwargs={"wandb": {"name": run_name}}
648
+ )
649
+
650
+ # saving and loading checkpoints for resuming training
651
+ accelerator.register_save_state_pre_hook(save_model_hook)
652
+ accelerator.register_load_state_pre_hook(load_model_hook)
653
+
654
+ total_batch_size = args.per_device_train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
655
+ logger.info("***** Running training *****")
656
+ logger.info(f" Num Epochs = {args.num_train_epochs}")
657
+ logger.info(f" Instantaneous batch size per device = {args.per_device_train_batch_size}")
658
+ logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
659
+ logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
660
+ logger.info(f" Total optimization steps = {args.max_train_steps}")
661
+ # Only show the progress bar once on each machine.
662
+ progress_bar = tqdm(range(args.max_train_steps), disable=not accelerator.is_local_main_process)
663
+ global_step = 0
664
+ starting_epoch = 0
665
+ best_metric = None
666
+ resume_step = 0
667
+ forced_decoder_ids = processor.get_decoder_prompt_ids(language=args.language, task=args.task)
668
+
669
+ # Potentially load in the weights and states from a previous save
670
+ if args.resume_from_checkpoint:
671
+ accelerator.load_state(args.resume_from_checkpoint)
672
+ path = os.path.basename(args.resume_from_checkpoint)
673
+ training_difference = os.path.splitext(path)[0]
674
+ global_step = resume_step = int(training_difference.replace("step_", ""))
675
+ starting_epoch = resume_step // len(train_dataloader)
676
+ resume_step -= starting_epoch * len(train_dataloader)
677
+
678
+ # We need to adjust the progress bar to the current step
679
+ progress_bar.update(resume_step)
680
+ for epoch in range(starting_epoch, args.num_train_epochs):
681
+ model.train()
682
+ if args.with_tracking:
683
+ total_loss = 0
684
+ running_loss = 0
685
+ for step, batch in enumerate(accelerator.skip_first_batches(train_dataloader, num_batches=resume_step)):
686
+ with accelerator.accumulate(model):
687
+ outputs = model(**batch)
688
+ loss = outputs.loss
689
+ accelerator.backward(loss)
690
+ optimizer.step()
691
+ lr_scheduler.step()
692
+
693
+ # Update the importance of low-rank matrices
694
+ # and allocate the budget accordingly.
695
+ # This is only needed for AdaLora.
696
+ # Note that this requires parameter gradients.
697
+ # Hence being called before optimizer.zero_grad().
698
+ if args.use_peft and args.use_adalora:
699
+ # Handle DDP case where model is wrapped
700
+ if hasattr(model, "module"):
701
+ # DDP case
702
+ peft_model = model.module
703
+ else:
704
+ # Non-DDP case
705
+ peft_model = model
706
+
707
+ # Check if rank_pattern exists before calling update_and_allocate
708
+ if (
709
+ hasattr(peft_model, "peft_config")
710
+ and peft_model.peft_config["default"].rank_pattern is not None
711
+ and global_step >= args.tinit # Only start updating after tinit steps
712
+ ):
713
+ peft_model.update_and_allocate(global_step)
714
+
715
+ optimizer.zero_grad()
716
+ global_step += 1
717
+ progress_bar.update(1)
718
+
719
+ if args.with_tracking:
720
+ step_loss = accelerator.reduce(loss.detach().clone()).item()
721
+ total_loss += step_loss
722
+ running_loss += step_loss
723
+
724
+ if global_step % args.checkpointing_steps == 0:
725
+ output_dir = os.path.join(args.output_dir, f"step_{global_step}")
726
+ accelerator.save_state(output_dir)
727
+
728
+ if global_step % args.logging_steps == 0:
729
+ if args.with_tracking:
730
+ accelerator.log({"train/running_loss": running_loss / args.logging_steps}, step=global_step)
731
+ running_loss = 0
732
+
733
+ if global_step % args.evaluation_steps == 0:
734
+ eval_metrics = evaluation_loop(
735
+ model, eval_dataloader, processor, normalizer, metric, forced_decoder_ids, accelerator
736
+ )
737
+ if args.with_tracking:
738
+ logger.info(f"Step {global_step} eval metrics: {eval_metrics}")
739
+ accelerator.log(eval_metrics, step=global_step)
740
+ if best_metric is None or eval_metrics["eval/wer"] < best_metric:
741
+ best_metric = eval_metrics["eval/wer"]
742
+ accelerator.save_state(os.path.join(args.output_dir, "best_checkpoint"))
743
+ model.train()
744
+
745
+ if global_step >= args.max_train_steps:
746
+ break
747
+
748
+ if args.with_tracking:
749
+ train_epoch_loss = total_loss / (step + 1)
750
+ logger.info(f"Epoch {epoch} train loss: {train_epoch_loss}")
751
+ accelerator.log({"epoch/train_loss": train_epoch_loss}, step=epoch)
752
+
753
+ if args.push_to_hub and epoch <= args.num_train_epochs - 1:
754
+ accelerator.wait_for_everyone()
755
+ unwrapped_model = accelerator.unwrap_model(model)
756
+ unwrapped_model.save_pretrained(args.output_dir, is_main_process=accelerator.is_main_process)
757
+ # evaluate the model at the end of training
758
+ eval_metrics = evaluation_loop(
759
+ model, eval_dataloader, processor, normalizer, metric, forced_decoder_ids, accelerator
760
+ )
761
+ if args.with_tracking:
762
+ logger.info(f"Step {global_step} eval metrics: {eval_metrics}")
763
+ accelerator.log(eval_metrics, step=global_step)
764
+ if best_metric is None or eval_metrics["eval/wer"] < best_metric:
765
+ best_metric = eval_metrics["eval/wer"]
766
+ accelerator.save_state(os.path.join(args.output_dir, "best_checkpoint"))
767
+
768
+ if accelerator.is_main_process:
769
+ processor.tokenizer.save_pretrained(args.output_dir)
770
+ api.upload_folder(
771
+ repo_id=repo_id,
772
+ folder_path=args.output_dir,
773
+ commit_message=f"Training in progress epoch {epoch}",
774
+ run_as_future=True,
775
+ )
776
+
777
+ if args.load_best_model:
778
+ # load the best model
779
+ accelerator.load_state(os.path.join(args.output_dir, "best_checkpoint"))
780
+ # Handle DDP case where model is wrapped
781
+ if hasattr(model, "module"):
782
+ # DDP case
783
+ peft_model = model.module
784
+ else:
785
+ # Non-DDP case
786
+ peft_model = model
787
+
788
+ # Only resize if rank_pattern exists
789
+ if hasattr(peft_model, "peft_config") and peft_model.peft_config["default"].rank_pattern is not None:
790
+ peft_model.resize_modules_by_rank_pattern(peft_model.peft_config["default"].rank_pattern, "default")
791
+
792
+ eval_metrics = evaluation_loop(
793
+ model, eval_dataloader, processor, normalizer, metric, forced_decoder_ids, accelerator
794
+ )
795
+ if args.with_tracking:
796
+ best_metrics = {"best_" + k: v for k, v in eval_metrics.items()}
797
+ accelerator.log(best_metrics, step=global_step)
798
+
799
+ accelerator.wait_for_everyone()
800
+ unwrapped_model = accelerator.unwrap_model(model)
801
+ unwrapped_model.save_pretrained(args.output_dir, is_main_process=accelerator.is_main_process)
802
+ if accelerator.is_main_process:
803
+ processor.tokenizer.save_pretrained(args.output_dir)
804
+ if args.push_to_hub:
805
+ api.upload_folder(
806
+ repo_id=repo_id,
807
+ folder_path=args.output_dir,
808
+ commit_message="End of training",
809
+ )
810
+
811
+ with open(os.path.join(args.output_dir, "all_results.json"), "w") as f:
812
+ eval_metrics.pop("eval_samples")
813
+ json.dump(eval_metrics, f)
814
+
815
+
816
+ if __name__ == "__main__":
817
+ main()
tasks/tasksmith-c488fc138ba1/tests/source/examples/int8_training/peft_bnb_whisper_large_v2_training.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
tasks/tasksmith-c488fc138ba1/tests/source/examples/int8_training/requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ accelerate
2
+ git+https://github.com/bitsandbytes-foundation/bitsandbytes.git
3
+ datasets==3.6.0
4
+ evaluate
5
+ jiwer
6
+ librosa
7
+ soundfile
8
+ transformers==4.52.4
9
+ wandb
tasks/tasksmith-c488fc138ba1/tests/source/examples/int8_training/run_adalora_whisper_int8.sh ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ accelerate launch --config_file config.yaml peft_adalora_whisper_large_training.py \
2
+ --model_name_or_path "openai/whisper-large-v2" \
3
+ --language "Marathi" \
4
+ --language_abbr "mr" \
5
+ --task "transcribe" \
6
+ --dataset_name "mozilla-foundation/common_voice_11_0" \
7
+ --push_to_hub \
8
+ --preprocessing_num_workers 2 \
9
+ --per_device_train_batch_size 8 \
10
+ --per_device_eval_batch_size 8 \
11
+ --dataloader_pin_memory \
12
+ --dataloader_num_workers 2 \
13
+ --learning_rate 1e-3 \
14
+ --weight_decay 1e-4 \
15
+ --num_train_epochs 3 \
16
+ --gradient_accumulation_steps 1 \
17
+ --lr_scheduler_type "linear" \
18
+ --num_warmup_steps 50 \
19
+ --output_dir "adalora_whisper_large_marathi_multi_adapter" \
20
+ --seed 42 \
21
+ --load_best_model \
22
+ --with_tracking \
23
+ --report_to "wandb" \
24
+ --hub_token $HUB_TOKEN \
25
+ --checkpointing_steps 2000 \
26
+ --evaluation_steps 2000 \
27
+ --logging_steps 25 \
28
+ --use_peft \
29
+ --use_adalora \
30
+ --init_r 12 \
31
+ --target_r 8 \
32
+ --tinit 100 \
33
+ --tfinal 800 \
34
+ --delta_t 10 \
35
+ --lora_alpha 32 \
36
+ --lora_dropout 0.1 \
37
+ --orth_reg_weight 0.5
tasks/tasksmith-c488fc138ba1/tests/source/examples/lily_finetuning/README.md ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Lily: Low-Rank Interconnected Adaptation Across Layers
2
+
3
+ ## Introduction
4
+ [**Lily**](https://arxiv.org/abs/2407.09946) is a PEFT method that introduces **cross-layer parameter sharing** to improve parameter efficiency. Unlike LoRA, which assigns independent adapter pairs to each layer, Lily shares adapter components across layers in two ways:
5
+
6
+ - **A sharing**: consecutive blocks of `stride_A` layers share the same A adapter, reducing the number of distinct input projections.
7
+ - **B sharing**: a small pool of `num_B` B adapters is shared globally across all layers. For each forward pass, a lightweight **router** computes a softmax-weighted combination of all B adapters to produce a layer-specific output projection.
8
+
9
+ This design allows Lily to cover more layers with fewer parameters, making it possible to use larger rank for each adapter without increasing parameter count and enabling information sharing across layers.
10
+
11
+ ## Quick start
12
+
13
+ With respect to your standard PEFT training procedure with LoRA, simply swap your `LoraConfig` for a `LilyConfig`.
14
+
15
+ ```python
16
+ import torch
17
+ from datasets import load_dataset
18
+ from transformers import AutoTokenizer, AutoModelForCausalLM
19
+ from trl import SFTTrainer, SFTConfig
20
+ from peft import LilyConfig
21
+
22
+ model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.2-3B", dtype=torch.bfloat16, device_map="auto")
23
+ tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.2-3B")
24
+ dataset = load_dataset("timdettmers/openassistant-guanaco", split="train")
25
+ lily_config = LilyConfig()
26
+
27
+ trainer = SFTTrainer(
28
+ model=model,
29
+ train_dataset=dataset,
30
+ processing_class=tokenizer,
31
+ peft_config=lily_config,
32
+ args=SFTConfig(
33
+ max_length=2048,
34
+ dataset_text_field="text",
35
+ per_device_train_batch_size=2,
36
+ ),
37
+ )
38
+ trainer.train()
39
+ trainer.model.save_pretrained("lily-llama-3.2-3b")
40
+ ```
41
+
42
+ Run the finetuning script simply by running:
43
+ ```sh
44
+ python examples/lily_finetuning/lily_finetuning.py --base_model meta-llama/Llama-3.2-3B --data_path timdettmers/openassistant-guanaco
45
+ ```
46
+
47
+ ## Use the model on 🤗
48
+ You can load and use the model as any other 🤗 models.
49
+ ```python
50
+ import torch
51
+ from peft import PeftModel
52
+ from transformers import AutoModelForCausalLM
53
+
54
+ model = AutoModelForCausalLM.from_pretrained(
55
+ "meta-llama/Llama-3.2-3B", dtype=torch.bfloat16, device_map="auto"
56
+ )
57
+ peft_model = PeftModel.from_pretrained(model, "lily-llama-3.2-3b")
58
+ ```
59
+
60
+ ## Additional Notes
61
+
62
+ - `r` controls the rank (inner hidden dimension). Since Lily typically uses fewer adapter instances than LoRA, it is recommended to use a **larger `r`** — typically `2x`–`4x` the rank you would use in LoRA.
63
+ - `stride_A` controls how many consecutive layers share one A adapter. Larger `stride_A` means fewer distinct A adapters and fewer trainable parameters. Suggested values: `2`, `3`, or `4`. Make sure that `total_layers` is divisible by `stride_A` to ensure even sharing.
64
+ - `num_B` controls the size of the shared B adapter pool. It is recommended to set `num_B` to roughly `total_layers / stride_A`. Note that `num_B >= 2` is required.
65
+ - `scaling` is a direct scalar multiplier on the adapter output (analogous to `alpha / r` in LoRA). It is recommended to start with `2.0` and treat it as a hyperparameter.
66
+ - The general rule of thumb: **prefer larger `r` with larger `stride_A` and smaller `num_B`** over smaller `r` with smaller `stride_A` and larger `num_B`.
67
+
68
+ ## Citation
69
+ ```
70
+ @inproceedings{zhong-etal-2025-low,
71
+ title = "Low-Rank Interconnected Adaptation across Layers",
72
+ author = "Zhong, Yibo and
73
+ Zhao, Jinman and
74
+ Zhou, Yao",
75
+ editor = "Che, Wanxiang and
76
+ Nabende, Joyce and
77
+ Shutova, Ekaterina and
78
+ Pilehvar, Mohammad Taher",
79
+ booktitle = "Findings of the Association for Computational Linguistics: ACL 2025",
80
+ month = jul,
81
+ year = "2025",
82
+ address = "Vienna, Austria",
83
+ publisher = "Association for Computational Linguistics",
84
+ url = "https://aclanthology.org/2025.findings-acl.874/",
85
+ doi = "10.18653/v1/2025.findings-acl.874",
86
+ pages = "17005--17029",
87
+ ISBN = "979-8-89176-256-5",
88
+ abstract = "Low-rank adaptation (LoRA) is a widely used parameter-efficient fine-tuning (PEFT) method that learns weight updates $\Delta W = AB$ for pretrained weights $W$ through low-rank adapters $A$ and $B$. While LoRA ensures hardware efficiency, its low-rank weight updates limit adaptation performance. In this paper, we propose low-rank interconnected adaptation across layers (Lily), a novel PEFT method that introduces an interconnected framework with locally shared $A$ and globally shared $B$ experts. This structure eliminates redundant per-layer $AB$ pairs, enabling higher-rank $\Delta W$ with equal or fewer parameters. To enhance expressiveness, we use data-dependent routers to determine $A$-$B$ interconnections, preventing $B$ experts from converging to the same behavior and improving representational power across domains. Experiments across modalities, architectures, and model sizes demonstrate Lily{'}s superior performance and efficiency."
89
+ }
90
+ ```
tasks/tasksmith-c488fc138ba1/tests/source/examples/lily_finetuning/lily_finetuning.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This script is based on examples/gralora_finetuning/gralora_finetuning.py
2
+ import os
3
+
4
+ import torch
5
+ from datasets import load_dataset
6
+ from transformers import (
7
+ AutoModelForCausalLM,
8
+ AutoTokenizer,
9
+ DataCollatorForLanguageModeling,
10
+ Trainer,
11
+ TrainingArguments,
12
+ )
13
+
14
+ from peft import LilyConfig, get_peft_model
15
+
16
+
17
+ def train_model(
18
+ base_model: str,
19
+ data_path: str,
20
+ output_dir: str,
21
+ batch_size: int,
22
+ num_epochs: int,
23
+ learning_rate: float,
24
+ cutoff_len: int,
25
+ val_set_size: int,
26
+ eval_step: int,
27
+ save_step: int,
28
+ device: str,
29
+ lily_r: int,
30
+ lily_scaling: float,
31
+ lily_stride_A: int,
32
+ lily_num_B: int,
33
+ lily_target_modules: str,
34
+ hub_model_id: str,
35
+ push_to_hub: bool,
36
+ ):
37
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
38
+ hf_token = os.getenv("HF_TOKEN")
39
+
40
+ # Setup device
41
+ if device == "auto":
42
+ device = torch.accelerator.current_accelerator().type if hasattr(torch, "accelerator") else "cuda"
43
+ else:
44
+ device = torch.device(device)
45
+ print(f"Using device: {device}")
46
+
47
+ # load tokenizer
48
+ tokenizer = AutoTokenizer.from_pretrained(base_model, token=hf_token)
49
+
50
+ model = AutoModelForCausalLM.from_pretrained(base_model, token=hf_token)
51
+
52
+ # Lily config for the PEFT model
53
+ lily_config = LilyConfig(
54
+ r=lily_r,
55
+ scaling=lily_scaling,
56
+ stride_A=lily_stride_A,
57
+ num_B=lily_num_B,
58
+ target_modules=(
59
+ lily_target_modules.split(",")
60
+ if lily_target_modules
61
+ else ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
62
+ ),
63
+ )
64
+
65
+ # get the peft model with Lily config
66
+ model = get_peft_model(model, lily_config)
67
+ model.print_trainable_parameters()
68
+
69
+ model.to(device)
70
+ tokenizer.pad_token = tokenizer.eos_token
71
+
72
+ # Load the dataset
73
+ dataset = load_dataset(data_path)
74
+
75
+ def tokenize_function(examples):
76
+ inputs = tokenizer(examples["text"], padding="max_length", truncation=True, max_length=cutoff_len)
77
+ inputs["labels"] = inputs["input_ids"].copy() # setting labels for a language modeling task
78
+ return inputs
79
+
80
+ # Tokenize the dataset and prepare for training
81
+ tokenized_datasets = dataset.map(tokenize_function, batched=True, remove_columns=dataset["train"].column_names)
82
+
83
+ # Data collator to dynamically pad the batched examples
84
+ data_collator = DataCollatorForLanguageModeling(tokenizer, mlm=False)
85
+
86
+ # Define training arguments
87
+ training_args = TrainingArguments(
88
+ output_dir=output_dir,
89
+ num_train_epochs=num_epochs,
90
+ per_device_train_batch_size=batch_size,
91
+ per_device_eval_batch_size=batch_size,
92
+ warmup_steps=100,
93
+ weight_decay=0.01,
94
+ logging_steps=eval_step,
95
+ save_steps=save_step,
96
+ save_total_limit=2,
97
+ push_to_hub=push_to_hub,
98
+ hub_model_id=hub_model_id,
99
+ gradient_accumulation_steps=16,
100
+ fp16=True,
101
+ learning_rate=learning_rate,
102
+ hub_token=hf_token,
103
+ )
104
+
105
+ # Clear device cache to free memory
106
+ if torch.cuda.is_available():
107
+ torch.cuda.empty_cache()
108
+ elif torch.xpu.is_available():
109
+ torch.xpu.empty_cache()
110
+
111
+ # Initialize the Trainer
112
+ trainer = Trainer(
113
+ model=model,
114
+ args=training_args,
115
+ train_dataset=tokenized_datasets["train"],
116
+ eval_dataset=tokenized_datasets["test"],
117
+ data_collator=data_collator,
118
+ )
119
+
120
+ # Start model training
121
+ trainer.train()
122
+
123
+ # Save and push the trained model and tokenizer
124
+ if push_to_hub:
125
+ trainer.push_to_hub(commit_message="Fine-tuned model with Lily")
126
+
127
+ # Save the model and tokenizer locally
128
+ model.save_pretrained(output_dir)
129
+ tokenizer.save_pretrained(output_dir)
130
+
131
+
132
+ if __name__ == "__main__":
133
+ import argparse
134
+
135
+ parser = argparse.ArgumentParser(description="Fine-tune LLaMA with Lily and PEFT")
136
+ parser.add_argument("--base_model", type=str, default="meta-llama/Llama-3.2-3B", help="Base model path or name")
137
+ parser.add_argument(
138
+ "--data_path", type=str, default="timdettmers/openassistant-guanaco", help="Dataset path or name"
139
+ )
140
+ parser.add_argument(
141
+ "--output_dir", type=str, default="path/to/output", help="Output directory for the fine-tuned model"
142
+ )
143
+ parser.add_argument("--batch_size", type=int, default=1, help="Batch size")
144
+ parser.add_argument("--num_epochs", type=int, default=1, help="Number of training epochs")
145
+ parser.add_argument("--learning_rate", type=float, default=1e-4, help="Learning rate")
146
+ parser.add_argument("--cutoff_len", type=int, default=512, help="Cutoff length for tokenization")
147
+ parser.add_argument("--val_set_size", type=int, default=500, help="Validation set size")
148
+ parser.add_argument("--eval_step", type=int, default=10, help="Evaluation step interval")
149
+ parser.add_argument("--save_step", type=int, default=100, help="Save step interval")
150
+ parser.add_argument("--device", type=str, default="auto", help="Device to use for training")
151
+ parser.add_argument("--lily_r", type=int, default=32, help="Lily rank")
152
+ parser.add_argument(
153
+ "--lily_scaling", type=float, default=2.0, help="Lily scaling factor applied to adapter output"
154
+ )
155
+ parser.add_argument(
156
+ "--lily_stride_A", type=int, default=4, help="Number of consecutive layers sharing one A adapter"
157
+ )
158
+ parser.add_argument("--lily_num_B", type=int, default=7, help="Number of shared B adapters (must be >= 2)")
159
+ parser.add_argument(
160
+ "--lily_target_modules", type=str, default=None, help="Comma-separated list of target modules for Lily"
161
+ )
162
+ parser.add_argument(
163
+ "--hub_model_id",
164
+ type=str,
165
+ default="path/to/repo",
166
+ help="Repository name to push the model on the Hugging Face Hub",
167
+ )
168
+ parser.add_argument("--push_to_hub", action="store_true", help="Whether to push the model to Hugging Face Hub")
169
+ args = parser.parse_args()
170
+
171
+ train_model(
172
+ base_model=args.base_model,
173
+ data_path=args.data_path,
174
+ output_dir=args.output_dir,
175
+ batch_size=args.batch_size,
176
+ num_epochs=args.num_epochs,
177
+ learning_rate=args.learning_rate,
178
+ cutoff_len=args.cutoff_len,
179
+ val_set_size=args.val_set_size,
180
+ eval_step=args.eval_step,
181
+ save_step=args.save_step,
182
+ device=args.device,
183
+ lily_r=args.lily_r,
184
+ lily_scaling=args.lily_scaling,
185
+ lily_stride_A=args.lily_stride_A,
186
+ lily_num_B=args.lily_num_B,
187
+ lily_target_modules=args.lily_target_modules,
188
+ hub_model_id=args.hub_model_id,
189
+ push_to_hub=args.push_to_hub,
190
+ )
tasks/tasksmith-c488fc138ba1/tests/source/examples/loftq_finetuning/LoftQ_weight_replacement.ipynb ADDED
@@ -0,0 +1,801 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "546b6c6d-f949-4387-9c41-6989223911f8",
6
+ "metadata": {},
7
+ "source": [
8
+ "# Initializing weights with LoftQ by replacing LoRA weights in-place"
9
+ ]
10
+ },
11
+ {
12
+ "cell_type": "markdown",
13
+ "id": "d041ecb4-6957-467e-8f3e-d4a12c674e9f",
14
+ "metadata": {},
15
+ "source": [
16
+ "This notebook shows how to apply [LoftQ](https://huggingface.co/papers/2310.08659) initialization on our QLoRA model.\n",
17
+ "\n",
18
+ "In short, the idea behind LoftQ is the following. When we use QLoRA, i.e. we quantize the base model with bitsandbytes to save memory, and then train LoRA weights on top of this base model, we expect a certain performance gap. This is partly due to the fact that quantization is onyl an approximation of the \"real\" weights and thus introduces a quantization error. By default, LoRA weights are initialized such that they are a no-op at the start of the training. However, we can instead initialize them so that they minimize the quantization error. This is the idea behind LoftQ.\n",
19
+ "\n",
20
+ "Note that this only influences the initialization of the model. Everything that follows stays the same as always."
21
+ ]
22
+ },
23
+ {
24
+ "cell_type": "markdown",
25
+ "id": "90d5420f-de32-42fa-8792-247f60e3647d",
26
+ "metadata": {},
27
+ "source": [
28
+ "## Imports"
29
+ ]
30
+ },
31
+ {
32
+ "cell_type": "code",
33
+ "execution_count": 1,
34
+ "id": "a2c69b7c-c922-405f-aae1-ccc4f6911155",
35
+ "metadata": {},
36
+ "outputs": [],
37
+ "source": [
38
+ "import os\n",
39
+ "import torch"
40
+ ]
41
+ },
42
+ {
43
+ "cell_type": "code",
44
+ "execution_count": 2,
45
+ "id": "22be0432-8798-44a2-9014-d929525e3059",
46
+ "metadata": {},
47
+ "outputs": [],
48
+ "source": [
49
+ "from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig"
50
+ ]
51
+ },
52
+ {
53
+ "cell_type": "code",
54
+ "execution_count": 3,
55
+ "id": "f087ce0f-71b4-45ec-b2f9-197677bbc1ee",
56
+ "metadata": {},
57
+ "outputs": [],
58
+ "source": [
59
+ "from peft import get_peft_model, LoraConfig, replace_lora_weights_loftq"
60
+ ]
61
+ },
62
+ {
63
+ "cell_type": "markdown",
64
+ "id": "63fdf18e-4ac4-409e-8475-88147cf85067",
65
+ "metadata": {},
66
+ "source": [
67
+ "## Functions"
68
+ ]
69
+ },
70
+ {
71
+ "cell_type": "code",
72
+ "execution_count": 4,
73
+ "id": "af14bd0a-597e-446c-800b-619fc0599ee0",
74
+ "metadata": {},
75
+ "outputs": [],
76
+ "source": [
77
+ "def get_mae(x, y):\n",
78
+ " return (x - y).abs().mean()\n",
79
+ "\n",
80
+ "\n",
81
+ "def get_mse(x, y):\n",
82
+ " return torch.pow(x - y, 2).mean()\n",
83
+ "\n",
84
+ "\n",
85
+ "def error_report(x, y):\n",
86
+ " mae = get_mae(x, y)\n",
87
+ " mse = get_mse(x, y)\n",
88
+ " print(\n",
89
+ " f\"Mean absolute error: {mae:>8.5f}\\n\"\n",
90
+ " f\"Mean squared error: {mse:>8.5f}\"\n",
91
+ " )"
92
+ ]
93
+ },
94
+ {
95
+ "cell_type": "markdown",
96
+ "id": "1bc01a5f-7ee8-400f-8e80-3f2b7df29882",
97
+ "metadata": {},
98
+ "source": [
99
+ "## Base model"
100
+ ]
101
+ },
102
+ {
103
+ "cell_type": "markdown",
104
+ "id": "fdc447d9-2f4f-4d0f-afdb-1cf5c4237321",
105
+ "metadata": {},
106
+ "source": [
107
+ "First, let's load a base model and calculate some logits. These logits are the baseline, i.e. we try to match their values as best as possible. We only need these logits for demonstration purposes. In practice, it is not necessary to load the non-quantized weights to apply LoftQ initialization.\n",
108
+ "\n",
109
+ "**Note**: We have to choose a model with a `model.safetensors` file. As PyTorch checkpoints (pickle) cannot be loaded lazily, we have to use [safetensors](https://huggingface.co/docs/safetensors/index). If those don't exist for your model, save the pretrained model as a safetensors file using `safe_pretrained` and pass the model path to `replace_lora_weights_loftq`."
110
+ ]
111
+ },
112
+ {
113
+ "cell_type": "code",
114
+ "execution_count": 5,
115
+ "id": "0cb29074-d180-4fdc-8a47-27d2b9857264",
116
+ "metadata": {},
117
+ "outputs": [],
118
+ "source": [
119
+ "model_id = \"bigscience/bloomz-560m\""
120
+ ]
121
+ },
122
+ {
123
+ "cell_type": "code",
124
+ "execution_count": 6,
125
+ "id": "e7ddd6a2-04dd-42ec-9f48-100a3946ae04",
126
+ "metadata": {},
127
+ "outputs": [],
128
+ "source": [
129
+ "tokenizer = AutoTokenizer.from_pretrained(model_id)"
130
+ ]
131
+ },
132
+ {
133
+ "cell_type": "code",
134
+ "execution_count": 7,
135
+ "id": "1f5b27db-51cc-41da-a21d-049ff747a149",
136
+ "metadata": {},
137
+ "outputs": [],
138
+ "source": [
139
+ "model = AutoModelForCausalLM.from_pretrained(model_id)"
140
+ ]
141
+ },
142
+ {
143
+ "cell_type": "code",
144
+ "execution_count": 8,
145
+ "id": "51548b6a-945c-4797-b02a-0e3fc77d1242",
146
+ "metadata": {},
147
+ "outputs": [],
148
+ "source": [
149
+ "s = \"\"\"Beautiful is better than ugly.\n",
150
+ "Explicit is better than implicit.\n",
151
+ "Simple is better than complex.\n",
152
+ "Complex is better than complicated.\n",
153
+ "Flat is better than nested.\n",
154
+ "Sparse is better than dense.\n",
155
+ "Readability counts.\n",
156
+ "Special cases aren't special enough to break the rules.\n",
157
+ "Although practicality beats purity.\n",
158
+ "Errors should never pass silently.\n",
159
+ "Unless explicitly silenced.\n",
160
+ "In the face of ambiguity, refuse the temptation to guess.\n",
161
+ "There should be one-- and preferably only one --obvious way to do it.\n",
162
+ "Although that way may not be obvious at first unless you're Dutch.\n",
163
+ "Now is better than never.\n",
164
+ "Although never is often better than *right* now.\n",
165
+ "If the implementation is hard to explain, it's a bad idea.\n",
166
+ "If the implementation is easy to explain, it may be a good idea.\n",
167
+ "Namespaces are one honking great idea -- let's do more of those!\"\"\""
168
+ ]
169
+ },
170
+ {
171
+ "cell_type": "code",
172
+ "execution_count": 9,
173
+ "id": "ce72d923-5283-48ba-96ef-7f859309ad84",
174
+ "metadata": {},
175
+ "outputs": [],
176
+ "source": [
177
+ "inputs = tokenizer(s.splitlines(), return_tensors=\"pt\", padding=True)"
178
+ ]
179
+ },
180
+ {
181
+ "cell_type": "markdown",
182
+ "id": "3bfe54cb-76ef-4981-ba25-3e544d264c62",
183
+ "metadata": {},
184
+ "source": [
185
+ "Our baseline logits:"
186
+ ]
187
+ },
188
+ {
189
+ "cell_type": "code",
190
+ "execution_count": 10,
191
+ "id": "04bebcaa-3a05-4621-9a03-e25de72fa27c",
192
+ "metadata": {},
193
+ "outputs": [],
194
+ "source": [
195
+ "logits_base = model(**inputs).logits"
196
+ ]
197
+ },
198
+ {
199
+ "cell_type": "markdown",
200
+ "id": "fa9c9001-8ade-422d-92f8-bcafa50917c7",
201
+ "metadata": {},
202
+ "source": [
203
+ "## Normal LoRA model"
204
+ ]
205
+ },
206
+ {
207
+ "cell_type": "markdown",
208
+ "id": "8024390b-736a-4b21-848b-aa4f30951d51",
209
+ "metadata": {},
210
+ "source": [
211
+ "Now we load the model quantized with bitsandbytes. For now, only 4bit is supported."
212
+ ]
213
+ },
214
+ {
215
+ "cell_type": "code",
216
+ "execution_count": 11,
217
+ "id": "01d1912a-646e-42d2-8292-6702b77d1948",
218
+ "metadata": {},
219
+ "outputs": [],
220
+ "source": [
221
+ "bnb_config = BitsAndBytesConfig(\n",
222
+ " load_in_4bit=True,\n",
223
+ " bnb_4bit_use_double_quant=True,\n",
224
+ " bnb_4bit_compute_dtype=torch.float16,\n",
225
+ ")"
226
+ ]
227
+ },
228
+ {
229
+ "cell_type": "code",
230
+ "execution_count": 12,
231
+ "id": "b1218717-4db4-48ce-978d-c05dc190fa91",
232
+ "metadata": {},
233
+ "outputs": [
234
+ {
235
+ "name": "stderr",
236
+ "output_type": "stream",
237
+ "text": [
238
+ "`low_cpu_mem_usage` was None, now set to True since model is quantized.\n"
239
+ ]
240
+ }
241
+ ],
242
+ "source": [
243
+ "model = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=bnb_config)"
244
+ ]
245
+ },
246
+ {
247
+ "cell_type": "markdown",
248
+ "id": "a0b4e4c5-3932-4d9a-9457-41a05f24d556",
249
+ "metadata": {},
250
+ "source": [
251
+ "Next we create a LoRA model using PEFT and compute the logits of that model."
252
+ ]
253
+ },
254
+ {
255
+ "cell_type": "code",
256
+ "execution_count": 13,
257
+ "id": "4741bce0-cd2b-4f05-a50c-4f9e56b43e72",
258
+ "metadata": {},
259
+ "outputs": [],
260
+ "source": [
261
+ "lora_config = LoraConfig(task_type=\"CAUSAL_LM\", target_modules=\"all-linear\")"
262
+ ]
263
+ },
264
+ {
265
+ "cell_type": "code",
266
+ "execution_count": 14,
267
+ "id": "cf55cc48-b55d-4806-b6ab-e9b8035ed526",
268
+ "metadata": {},
269
+ "outputs": [],
270
+ "source": [
271
+ "peft_model = get_peft_model(model, lora_config)"
272
+ ]
273
+ },
274
+ {
275
+ "cell_type": "code",
276
+ "execution_count": 15,
277
+ "id": "f2f11e25-4a1e-485b-be4c-65aec62ac207",
278
+ "metadata": {},
279
+ "outputs": [
280
+ {
281
+ "name": "stderr",
282
+ "output_type": "stream",
283
+ "text": [
284
+ ".../bitsandbytes/nn/modules.py:391: UserWarning: Input type into Linear4bit is torch.float16, but bnb_4bit_compute_dtype=torch.float32 (default). This will lead to slow inference or training speed.\n",
285
+ " warnings.warn('Input type into Linear4bit is torch.float16, but bnb_4bit_compute_dtype=torch.float32 (default). This will lead to slow inference or training speed.')\n"
286
+ ]
287
+ }
288
+ ],
289
+ "source": [
290
+ "logits_lora = peft_model(**inputs).logits"
291
+ ]
292
+ },
293
+ {
294
+ "cell_type": "markdown",
295
+ "id": "5bc0cde7-0b9f-4305-ac0e-e3a6d2cfa401",
296
+ "metadata": {},
297
+ "source": [
298
+ "Let's check the influence of the quantization error on our logits:"
299
+ ]
300
+ },
301
+ {
302
+ "cell_type": "code",
303
+ "execution_count": 16,
304
+ "id": "6f404c0d-f428-4923-9122-7b830410f089",
305
+ "metadata": {},
306
+ "outputs": [
307
+ {
308
+ "name": "stdout",
309
+ "output_type": "stream",
310
+ "text": [
311
+ "Mean absolute error: 3.61113\n",
312
+ "Mean squared error: 36.53259\n"
313
+ ]
314
+ }
315
+ ],
316
+ "source": [
317
+ "error_report(logits_base, logits_lora)"
318
+ ]
319
+ },
320
+ {
321
+ "cell_type": "markdown",
322
+ "id": "58c437e1-4fae-4a2f-9c42-ada6bedb9a4d",
323
+ "metadata": {},
324
+ "source": [
325
+ "## LoftQ"
326
+ ]
327
+ },
328
+ {
329
+ "cell_type": "markdown",
330
+ "id": "1af05376-c8b0-48ec-8d80-7d7f4d32bbd7",
331
+ "metadata": {},
332
+ "source": [
333
+ "Next, let's use LoftQ initialization and see if it helps reduce the error."
334
+ ]
335
+ },
336
+ {
337
+ "cell_type": "code",
338
+ "execution_count": 17,
339
+ "id": "890e6108-3f02-469c-9e7d-f2144448227c",
340
+ "metadata": {},
341
+ "outputs": [],
342
+ "source": [
343
+ "replace_lora_weights_loftq(peft_model)"
344
+ ]
345
+ },
346
+ {
347
+ "cell_type": "code",
348
+ "execution_count": 18,
349
+ "id": "b452db0e-a510-42d3-bef5-f567186e26c2",
350
+ "metadata": {},
351
+ "outputs": [],
352
+ "source": [
353
+ "logits_loftq = peft_model(**inputs).logits"
354
+ ]
355
+ },
356
+ {
357
+ "cell_type": "code",
358
+ "execution_count": 19,
359
+ "id": "456dc564-f268-4cf3-9d59-a6942d3733ad",
360
+ "metadata": {},
361
+ "outputs": [
362
+ {
363
+ "name": "stdout",
364
+ "output_type": "stream",
365
+ "text": [
366
+ "Mean absolute error: 3.24111\n",
367
+ "Mean squared error: 31.13725\n"
368
+ ]
369
+ }
370
+ ],
371
+ "source": [
372
+ "error_report(logits_base, logits_loftq)"
373
+ ]
374
+ },
375
+ {
376
+ "cell_type": "markdown",
377
+ "id": "1ddf9e0f-3f78-426c-be59-77c6481674ec",
378
+ "metadata": {},
379
+ "source": [
380
+ "We can see that LoftQ initialization helped a little bit, but the difference is not huge."
381
+ ]
382
+ },
383
+ {
384
+ "cell_type": "markdown",
385
+ "id": "0dd344f2-249c-4fe9-8357-7fe3bcd1e82f",
386
+ "metadata": {},
387
+ "source": [
388
+ "## LoftQ with callback"
389
+ ]
390
+ },
391
+ {
392
+ "cell_type": "markdown",
393
+ "id": "e2fd7dd5-88b3-40b8-95c2-3f3895d8093d",
394
+ "metadata": {},
395
+ "source": [
396
+ "To help with this, let's write a small callback function and pass it to `replace_lora_weights_loftq`. What this function does is that each time one weight is being replaced with LoftQ-initialized weights, we perform a test if the quantization error is actually reduced. If it it is not, we roll back the replacement. This way, we keep only those replacements that improve the results."
397
+ ]
398
+ },
399
+ {
400
+ "cell_type": "code",
401
+ "execution_count": 20,
402
+ "id": "1f882802-22b7-4969-919e-120b1f2893d2",
403
+ "metadata": {},
404
+ "outputs": [
405
+ {
406
+ "name": "stderr",
407
+ "output_type": "stream",
408
+ "text": [
409
+ "`low_cpu_mem_usage` was None, now set to True since model is quantized.\n"
410
+ ]
411
+ }
412
+ ],
413
+ "source": [
414
+ "# Since PEFT has modified the base model, we should reload it\n",
415
+ "model = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=bnb_config)"
416
+ ]
417
+ },
418
+ {
419
+ "cell_type": "code",
420
+ "execution_count": 21,
421
+ "id": "c6438363-b66e-4507-8667-5a6df379a03f",
422
+ "metadata": {},
423
+ "outputs": [],
424
+ "source": [
425
+ "peft_model = get_peft_model(model, lora_config)"
426
+ ]
427
+ },
428
+ {
429
+ "cell_type": "code",
430
+ "execution_count": 22,
431
+ "id": "7b93d082-0fcb-4b20-982e-c1aaf0c71d13",
432
+ "metadata": {},
433
+ "outputs": [],
434
+ "source": [
435
+ "current_mse = float(\"inf\")"
436
+ ]
437
+ },
438
+ {
439
+ "cell_type": "code",
440
+ "execution_count": 23,
441
+ "id": "e22eb18d-b06e-47fe-91ba-ff34cbf62f60",
442
+ "metadata": {},
443
+ "outputs": [],
444
+ "source": [
445
+ "def my_callback(model, module_name):\n",
446
+ " \"\"\"Callable to replace weights with LoFTQ if the mse is lower than the current best one.\"\"\"\n",
447
+ " global current_mse\n",
448
+ "\n",
449
+ " logits = model(**inputs).logits\n",
450
+ " mse = get_mse(logits_base, logits)\n",
451
+ " if mse < current_mse:\n",
452
+ " current_mse = mse\n",
453
+ " print(f\"MSE improved for module {module_name}\")\n",
454
+ " return True\n",
455
+ " print(f\"MSE did not improve for module {module_name}\")\n",
456
+ " return False"
457
+ ]
458
+ },
459
+ {
460
+ "cell_type": "code",
461
+ "execution_count": 24,
462
+ "id": "44ee90d1-e15a-4740-a39d-ebf9e7adb79c",
463
+ "metadata": {
464
+ "scrolled": true
465
+ },
466
+ "outputs": [
467
+ {
468
+ "name": "stdout",
469
+ "output_type": "stream",
470
+ "text": [
471
+ "MSE improved for module transformer.h.0.self_attention.query_key_value\n",
472
+ "MSE did not improve for module transformer.h.0.self_attention.dense\n",
473
+ "MSE improved for module transformer.h.0.mlp.dense_h_to_4h\n",
474
+ "MSE improved for module transformer.h.0.mlp.dense_4h_to_h\n",
475
+ "MSE did not improve for module transformer.h.1.self_attention.query_key_value\n",
476
+ "MSE did not improve for module transformer.h.1.self_attention.dense\n",
477
+ "MSE did not improve for module transformer.h.1.mlp.dense_h_to_4h\n",
478
+ "MSE improved for module transformer.h.1.mlp.dense_4h_to_h\n",
479
+ "MSE improved for module transformer.h.2.self_attention.query_key_value\n",
480
+ "MSE improved for module transformer.h.2.self_attention.dense\n",
481
+ "MSE improved for module transformer.h.2.mlp.dense_h_to_4h\n",
482
+ "MSE did not improve for module transformer.h.2.mlp.dense_4h_to_h\n",
483
+ "MSE improved for module transformer.h.3.self_attention.query_key_value\n",
484
+ "MSE did not improve for module transformer.h.3.self_attention.dense\n",
485
+ "MSE improved for module transformer.h.3.mlp.dense_h_to_4h\n",
486
+ "MSE improved for module transformer.h.3.mlp.dense_4h_to_h\n",
487
+ "MSE improved for module transformer.h.4.self_attention.query_key_value\n",
488
+ "MSE did not improve for module transformer.h.4.self_attention.dense\n",
489
+ "MSE improved for module transformer.h.4.mlp.dense_h_to_4h\n",
490
+ "MSE did not improve for module transformer.h.4.mlp.dense_4h_to_h\n",
491
+ "MSE did not improve for module transformer.h.5.self_attention.query_key_value\n",
492
+ "MSE improved for module transformer.h.5.self_attention.dense\n",
493
+ "MSE improved for module transformer.h.5.mlp.dense_h_to_4h\n",
494
+ "MSE did not improve for module transformer.h.5.mlp.dense_4h_to_h\n",
495
+ "MSE improved for module transformer.h.6.self_attention.query_key_value\n",
496
+ "MSE did not improve for module transformer.h.6.self_attention.dense\n",
497
+ "MSE improved for module transformer.h.6.mlp.dense_h_to_4h\n",
498
+ "MSE did not improve for module transformer.h.6.mlp.dense_4h_to_h\n",
499
+ "MSE improved for module transformer.h.7.self_attention.query_key_value\n",
500
+ "MSE improved for module transformer.h.7.self_attention.dense\n",
501
+ "MSE did not improve for module transformer.h.7.mlp.dense_h_to_4h\n",
502
+ "MSE did not improve for module transformer.h.7.mlp.dense_4h_to_h\n",
503
+ "MSE did not improve for module transformer.h.8.self_attention.query_key_value\n",
504
+ "MSE did not improve for module transformer.h.8.self_attention.dense\n",
505
+ "MSE improved for module transformer.h.8.mlp.dense_h_to_4h\n",
506
+ "MSE did not improve for module transformer.h.8.mlp.dense_4h_to_h\n",
507
+ "MSE improved for module transformer.h.9.self_attention.query_key_value\n",
508
+ "MSE did not improve for module transformer.h.9.self_attention.dense\n",
509
+ "MSE did not improve for module transformer.h.9.mlp.dense_h_to_4h\n",
510
+ "MSE did not improve for module transformer.h.9.mlp.dense_4h_to_h\n",
511
+ "MSE did not improve for module transformer.h.10.self_attention.query_key_value\n",
512
+ "MSE did not improve for module transformer.h.10.self_attention.dense\n",
513
+ "MSE did not improve for module transformer.h.10.mlp.dense_h_to_4h\n",
514
+ "MSE improved for module transformer.h.10.mlp.dense_4h_to_h\n",
515
+ "MSE did not improve for module transformer.h.11.self_attention.query_key_value\n",
516
+ "MSE did not improve for module transformer.h.11.self_attention.dense\n",
517
+ "MSE did not improve for module transformer.h.11.mlp.dense_h_to_4h\n",
518
+ "MSE improved for module transformer.h.11.mlp.dense_4h_to_h\n",
519
+ "MSE improved for module transformer.h.12.self_attention.query_key_value\n",
520
+ "MSE did not improve for module transformer.h.12.self_attention.dense\n",
521
+ "MSE improved for module transformer.h.12.mlp.dense_h_to_4h\n",
522
+ "MSE did not improve for module transformer.h.12.mlp.dense_4h_to_h\n",
523
+ "MSE improved for module transformer.h.13.self_attention.query_key_value\n",
524
+ "MSE improved for module transformer.h.13.self_attention.dense\n",
525
+ "MSE did not improve for module transformer.h.13.mlp.dense_h_to_4h\n",
526
+ "MSE improved for module transformer.h.13.mlp.dense_4h_to_h\n",
527
+ "MSE did not improve for module transformer.h.14.self_attention.query_key_value\n",
528
+ "MSE improved for module transformer.h.14.self_attention.dense\n",
529
+ "MSE did not improve for module transformer.h.14.mlp.dense_h_to_4h\n",
530
+ "MSE improved for module transformer.h.14.mlp.dense_4h_to_h\n",
531
+ "MSE did not improve for module transformer.h.15.self_attention.query_key_value\n",
532
+ "MSE did not improve for module transformer.h.15.self_attention.dense\n",
533
+ "MSE did not improve for module transformer.h.15.mlp.dense_h_to_4h\n",
534
+ "MSE improved for module transformer.h.15.mlp.dense_4h_to_h\n",
535
+ "MSE did not improve for module transformer.h.16.self_attention.query_key_value\n",
536
+ "MSE did not improve for module transformer.h.16.self_attention.dense\n",
537
+ "MSE improved for module transformer.h.16.mlp.dense_h_to_4h\n",
538
+ "MSE improved for module transformer.h.16.mlp.dense_4h_to_h\n",
539
+ "MSE did not improve for module transformer.h.17.self_attention.query_key_value\n",
540
+ "MSE did not improve for module transformer.h.17.self_attention.dense\n",
541
+ "MSE improved for module transformer.h.17.mlp.dense_h_to_4h\n",
542
+ "MSE did not improve for module transformer.h.17.mlp.dense_4h_to_h\n",
543
+ "MSE improved for module transformer.h.18.self_attention.query_key_value\n",
544
+ "MSE did not improve for module transformer.h.18.self_attention.dense\n",
545
+ "MSE did not improve for module transformer.h.18.mlp.dense_h_to_4h\n",
546
+ "MSE did not improve for module transformer.h.18.mlp.dense_4h_to_h\n",
547
+ "MSE did not improve for module transformer.h.19.self_attention.query_key_value\n",
548
+ "MSE improved for module transformer.h.19.self_attention.dense\n",
549
+ "MSE improved for module transformer.h.19.mlp.dense_h_to_4h\n",
550
+ "MSE improved for module transformer.h.19.mlp.dense_4h_to_h\n",
551
+ "MSE improved for module transformer.h.20.self_attention.query_key_value\n",
552
+ "MSE did not improve for module transformer.h.20.self_attention.dense\n",
553
+ "MSE did not improve for module transformer.h.20.mlp.dense_h_to_4h\n",
554
+ "MSE improved for module transformer.h.20.mlp.dense_4h_to_h\n",
555
+ "MSE did not improve for module transformer.h.21.self_attention.query_key_value\n",
556
+ "MSE improved for module transformer.h.21.self_attention.dense\n",
557
+ "MSE did not improve for module transformer.h.21.mlp.dense_h_to_4h\n",
558
+ "MSE did not improve for module transformer.h.21.mlp.dense_4h_to_h\n",
559
+ "MSE improved for module transformer.h.22.self_attention.query_key_value\n",
560
+ "MSE improved for module transformer.h.22.self_attention.dense\n",
561
+ "MSE improved for module transformer.h.22.mlp.dense_h_to_4h\n",
562
+ "MSE improved for module transformer.h.22.mlp.dense_4h_to_h\n",
563
+ "MSE improved for module transformer.h.23.self_attention.query_key_value\n",
564
+ "MSE did not improve for module transformer.h.23.self_attention.dense\n",
565
+ "MSE improved for module transformer.h.23.mlp.dense_h_to_4h\n",
566
+ "MSE did not improve for module transformer.h.23.mlp.dense_4h_to_h\n"
567
+ ]
568
+ }
569
+ ],
570
+ "source": [
571
+ "replace_lora_weights_loftq(peft_model, callback=my_callback)"
572
+ ]
573
+ },
574
+ {
575
+ "cell_type": "code",
576
+ "execution_count": 25,
577
+ "id": "e31adc81-a090-49b2-90f6-9906743c76ae",
578
+ "metadata": {},
579
+ "outputs": [],
580
+ "source": [
581
+ "logits_loftq_callback = peft_model(**inputs).logits"
582
+ ]
583
+ },
584
+ {
585
+ "cell_type": "code",
586
+ "execution_count": 26,
587
+ "id": "7c640092-1f26-48be-bea4-487511205440",
588
+ "metadata": {},
589
+ "outputs": [
590
+ {
591
+ "name": "stdout",
592
+ "output_type": "stream",
593
+ "text": [
594
+ "Mean absolute error: 1.79576\n",
595
+ "Mean squared error: 8.47075\n"
596
+ ]
597
+ }
598
+ ],
599
+ "source": [
600
+ "error_report(logits_base, logits_loftq_callback)"
601
+ ]
602
+ },
603
+ {
604
+ "cell_type": "markdown",
605
+ "id": "1896857e-3d87-44a9-887f-90c765bc8d91",
606
+ "metadata": {},
607
+ "source": [
608
+ "We can see that applying LoftQ with the help of the callback reduced the error quite significantly."
609
+ ]
610
+ },
611
+ {
612
+ "cell_type": "markdown",
613
+ "id": "8eaf86cf-4fb4-455d-ab07-892591564303",
614
+ "metadata": {},
615
+ "source": [
616
+ "## Applying LoftQ multiple times"
617
+ ]
618
+ },
619
+ {
620
+ "cell_type": "markdown",
621
+ "id": "70836a75-5c6d-4b7b-9175-f395aef8383b",
622
+ "metadata": {},
623
+ "source": [
624
+ "It is possible to run `replace_lora_weights_loftq` multiple times on the same model when using the callback."
625
+ ]
626
+ },
627
+ {
628
+ "cell_type": "code",
629
+ "execution_count": 27,
630
+ "id": "8e5ee38c-007c-4c75-9248-005d94b19445",
631
+ "metadata": {
632
+ "scrolled": true
633
+ },
634
+ "outputs": [
635
+ {
636
+ "name": "stdout",
637
+ "output_type": "stream",
638
+ "text": [
639
+ "MSE did not improve for module transformer.h.0.self_attention.query_key_value\n",
640
+ "MSE did not improve for module transformer.h.0.self_attention.dense\n",
641
+ "MSE did not improve for module transformer.h.0.mlp.dense_h_to_4h\n",
642
+ "MSE did not improve for module transformer.h.0.mlp.dense_4h_to_h\n",
643
+ "MSE improved for module transformer.h.1.self_attention.query_key_value\n",
644
+ "MSE did not improve for module transformer.h.1.self_attention.dense\n",
645
+ "MSE did not improve for module transformer.h.1.mlp.dense_h_to_4h\n",
646
+ "MSE did not improve for module transformer.h.1.mlp.dense_4h_to_h\n",
647
+ "MSE did not improve for module transformer.h.2.self_attention.query_key_value\n",
648
+ "MSE did not improve for module transformer.h.2.self_attention.dense\n",
649
+ "MSE did not improve for module transformer.h.2.mlp.dense_h_to_4h\n",
650
+ "MSE did not improve for module transformer.h.2.mlp.dense_4h_to_h\n",
651
+ "MSE did not improve for module transformer.h.3.self_attention.query_key_value\n",
652
+ "MSE did not improve for module transformer.h.3.self_attention.dense\n",
653
+ "MSE did not improve for module transformer.h.3.mlp.dense_h_to_4h\n",
654
+ "MSE did not improve for module transformer.h.3.mlp.dense_4h_to_h\n",
655
+ "MSE did not improve for module transformer.h.4.self_attention.query_key_value\n",
656
+ "MSE did not improve for module transformer.h.4.self_attention.dense\n",
657
+ "MSE did not improve for module transformer.h.4.mlp.dense_h_to_4h\n",
658
+ "MSE did not improve for module transformer.h.4.mlp.dense_4h_to_h\n",
659
+ "MSE did not improve for module transformer.h.5.self_attention.query_key_value\n",
660
+ "MSE did not improve for module transformer.h.5.self_attention.dense\n",
661
+ "MSE did not improve for module transformer.h.5.mlp.dense_h_to_4h\n",
662
+ "MSE did not improve for module transformer.h.5.mlp.dense_4h_to_h\n",
663
+ "MSE did not improve for module transformer.h.6.self_attention.query_key_value\n",
664
+ "MSE improved for module transformer.h.6.self_attention.dense\n",
665
+ "MSE did not improve for module transformer.h.6.mlp.dense_h_to_4h\n",
666
+ "MSE did not improve for module transformer.h.6.mlp.dense_4h_to_h\n",
667
+ "MSE did not improve for module transformer.h.7.self_attention.query_key_value\n",
668
+ "MSE did not improve for module transformer.h.7.self_attention.dense\n",
669
+ "MSE did not improve for module transformer.h.7.mlp.dense_h_to_4h\n",
670
+ "MSE did not improve for module transformer.h.7.mlp.dense_4h_to_h\n",
671
+ "MSE did not improve for module transformer.h.8.self_attention.query_key_value\n",
672
+ "MSE did not improve for module transformer.h.8.self_attention.dense\n",
673
+ "MSE did not improve for module transformer.h.8.mlp.dense_h_to_4h\n",
674
+ "MSE did not improve for module transformer.h.8.mlp.dense_4h_to_h\n",
675
+ "MSE did not improve for module transformer.h.9.self_attention.query_key_value\n",
676
+ "MSE did not improve for module transformer.h.9.self_attention.dense\n",
677
+ "MSE did not improve for module transformer.h.9.mlp.dense_h_to_4h\n",
678
+ "MSE did not improve for module transformer.h.9.mlp.dense_4h_to_h\n",
679
+ "MSE did not improve for module transformer.h.10.self_attention.query_key_value\n",
680
+ "MSE did not improve for module transformer.h.10.self_attention.dense\n",
681
+ "MSE improved for module transformer.h.10.mlp.dense_h_to_4h\n",
682
+ "MSE did not improve for module transformer.h.10.mlp.dense_4h_to_h\n",
683
+ "MSE did not improve for module transformer.h.11.self_attention.query_key_value\n",
684
+ "MSE did not improve for module transformer.h.11.self_attention.dense\n",
685
+ "MSE did not improve for module transformer.h.11.mlp.dense_h_to_4h\n",
686
+ "MSE did not improve for module transformer.h.11.mlp.dense_4h_to_h\n",
687
+ "MSE did not improve for module transformer.h.12.self_attention.query_key_value\n",
688
+ "MSE improved for module transformer.h.12.self_attention.dense\n",
689
+ "MSE did not improve for module transformer.h.12.mlp.dense_h_to_4h\n",
690
+ "MSE did not improve for module transformer.h.12.mlp.dense_4h_to_h\n",
691
+ "MSE did not improve for module transformer.h.13.self_attention.query_key_value\n",
692
+ "MSE did not improve for module transformer.h.13.self_attention.dense\n",
693
+ "MSE did not improve for module transformer.h.13.mlp.dense_h_to_4h\n",
694
+ "MSE did not improve for module transformer.h.13.mlp.dense_4h_to_h\n",
695
+ "MSE did not improve for module transformer.h.14.self_attention.query_key_value\n",
696
+ "MSE did not improve for module transformer.h.14.self_attention.dense\n",
697
+ "MSE did not improve for module transformer.h.14.mlp.dense_h_to_4h\n",
698
+ "MSE did not improve for module transformer.h.14.mlp.dense_4h_to_h\n",
699
+ "MSE did not improve for module transformer.h.15.self_attention.query_key_value\n",
700
+ "MSE did not improve for module transformer.h.15.self_attention.dense\n",
701
+ "MSE did not improve for module transformer.h.15.mlp.dense_h_to_4h\n",
702
+ "MSE did not improve for module transformer.h.15.mlp.dense_4h_to_h\n",
703
+ "MSE improved for module transformer.h.16.self_attention.query_key_value\n",
704
+ "MSE did not improve for module transformer.h.16.self_attention.dense\n",
705
+ "MSE did not improve for module transformer.h.16.mlp.dense_h_to_4h\n",
706
+ "MSE did not improve for module transformer.h.16.mlp.dense_4h_to_h\n",
707
+ "MSE improved for module transformer.h.17.self_attention.query_key_value\n",
708
+ "MSE did not improve for module transformer.h.17.self_attention.dense\n",
709
+ "MSE did not improve for module transformer.h.17.mlp.dense_h_to_4h\n",
710
+ "MSE did not improve for module transformer.h.17.mlp.dense_4h_to_h\n",
711
+ "MSE did not improve for module transformer.h.18.self_attention.query_key_value\n",
712
+ "MSE did not improve for module transformer.h.18.self_attention.dense\n",
713
+ "MSE did not improve for module transformer.h.18.mlp.dense_h_to_4h\n",
714
+ "MSE did not improve for module transformer.h.18.mlp.dense_4h_to_h\n",
715
+ "MSE did not improve for module transformer.h.19.self_attention.query_key_value\n",
716
+ "MSE did not improve for module transformer.h.19.self_attention.dense\n",
717
+ "MSE did not improve for module transformer.h.19.mlp.dense_h_to_4h\n",
718
+ "MSE did not improve for module transformer.h.19.mlp.dense_4h_to_h\n",
719
+ "MSE did not improve for module transformer.h.20.self_attention.query_key_value\n",
720
+ "MSE did not improve for module transformer.h.20.self_attention.dense\n",
721
+ "MSE did not improve for module transformer.h.20.mlp.dense_h_to_4h\n",
722
+ "MSE did not improve for module transformer.h.20.mlp.dense_4h_to_h\n",
723
+ "MSE did not improve for module transformer.h.21.self_attention.query_key_value\n",
724
+ "MSE did not improve for module transformer.h.21.self_attention.dense\n",
725
+ "MSE did not improve for module transformer.h.21.mlp.dense_h_to_4h\n",
726
+ "MSE did not improve for module transformer.h.21.mlp.dense_4h_to_h\n",
727
+ "MSE did not improve for module transformer.h.22.self_attention.query_key_value\n",
728
+ "MSE did not improve for module transformer.h.22.self_attention.dense\n",
729
+ "MSE did not improve for module transformer.h.22.mlp.dense_h_to_4h\n",
730
+ "MSE did not improve for module transformer.h.22.mlp.dense_4h_to_h\n",
731
+ "MSE did not improve for module transformer.h.23.self_attention.query_key_value\n",
732
+ "MSE did not improve for module transformer.h.23.self_attention.dense\n",
733
+ "MSE did not improve for module transformer.h.23.mlp.dense_h_to_4h\n",
734
+ "MSE did not improve for module transformer.h.23.mlp.dense_4h_to_h\n"
735
+ ]
736
+ }
737
+ ],
738
+ "source": [
739
+ "replace_lora_weights_loftq(peft_model, callback=my_callback)"
740
+ ]
741
+ },
742
+ {
743
+ "cell_type": "code",
744
+ "execution_count": 28,
745
+ "id": "2abe2702-9510-4814-b5f2-63140a102c17",
746
+ "metadata": {},
747
+ "outputs": [],
748
+ "source": [
749
+ "logits_loftq_callback_twice = peft_model(**inputs).logits"
750
+ ]
751
+ },
752
+ {
753
+ "cell_type": "code",
754
+ "execution_count": 29,
755
+ "id": "e908de14-01f9-4fdc-91b5-61118a3ce6cb",
756
+ "metadata": {},
757
+ "outputs": [
758
+ {
759
+ "name": "stdout",
760
+ "output_type": "stream",
761
+ "text": [
762
+ "Mean absolute error: 1.76357\n",
763
+ "Mean squared error: 8.33938\n"
764
+ ]
765
+ }
766
+ ],
767
+ "source": [
768
+ "error_report(logits_base, logits_loftq_callback_twice)"
769
+ ]
770
+ },
771
+ {
772
+ "cell_type": "markdown",
773
+ "id": "5b8b09fe-d369-4444-b6e2-cd514e775637",
774
+ "metadata": {},
775
+ "source": [
776
+ "There are further gains, but they are not very big."
777
+ ]
778
+ }
779
+ ],
780
+ "metadata": {
781
+ "kernelspec": {
782
+ "display_name": "Python 3 (ipykernel)",
783
+ "language": "python",
784
+ "name": "python3"
785
+ },
786
+ "language_info": {
787
+ "codemirror_mode": {
788
+ "name": "ipython",
789
+ "version": 3
790
+ },
791
+ "file_extension": ".py",
792
+ "mimetype": "text/x-python",
793
+ "name": "python",
794
+ "nbconvert_exporter": "python",
795
+ "pygments_lexer": "ipython3",
796
+ "version": "3.10.11"
797
+ }
798
+ },
799
+ "nbformat": 4,
800
+ "nbformat_minor": 5
801
+ }
tasks/tasksmith-c488fc138ba1/tests/source/examples/loftq_finetuning/README.md ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LoftQ: LoRA-fine-tuning-aware Quantization
2
+
3
+ ## Introduction
4
+
5
+ LoftQ finds quantized LoRA initialization: quantized backbone Q and LoRA adapters A and B, given a pre-trained weight W.
6
+
7
+ ## Quick Start
8
+ Steps:
9
+
10
+ 1. Apply LoftQ to a full-precision pre-trained weight and save.
11
+ 2. Load LoftQ initialization and train.
12
+
13
+ For step 1, we have provided off-the-shelf LoftQ initializations (see [supported model list](#appendix-off-the-shelf-model-list))
14
+ in [Huggingface Hub LoftQ](https://huggingface.co/LoftQ).
15
+ If you want to do it yourself, jump to [LoftQ DIY](#loftq-diy).
16
+
17
+ For step 2, below is an example of loading 4bit Mistral-7B with 64rank LoRA adapters from Huggingface Hub.
18
+ ```python
19
+ import torch
20
+ from transformers import AutoModelForCausalLM, BitsAndBytesConfig
21
+ from peft import PeftModel
22
+
23
+ MODEL_ID = "LoftQ/Mistral-7B-v0.1-4bit-64rank"
24
+
25
+ base_model = AutoModelForCausalLM.from_pretrained(
26
+ MODEL_ID,
27
+ dtype=torch.bfloat16, # you may change it with different models
28
+ quantization_config=BitsAndBytesConfig(
29
+ load_in_4bit=True,
30
+ bnb_4bit_compute_dtype=torch.bfloat16, # bfloat16 is recommended
31
+ bnb_4bit_use_double_quant=False,
32
+ bnb_4bit_quant_type='nf4',
33
+ ),
34
+ )
35
+ peft_model = PeftModel.from_pretrained(
36
+ base_model,
37
+ MODEL_ID,
38
+ subfolder="loftq_init",
39
+ is_trainable=True,
40
+ )
41
+
42
+ # Do training with peft_model ...
43
+ ```
44
+
45
+ ## LoftQ DIY
46
+
47
+ ### Apply LoftQ and save
48
+ We provide [quantize_save_load.py](quantize_save_load.py) as an example to apply LoftQ with
49
+ different bits(`--bits`), ranks(`--rank`), and alternating steps (`--iter`, a hyper-parameter in LoftQ, see Algorithm 1 in [LoftQ paper](https://huggingface.co/papers/2310.08659)). Currently, this example supports
50
+ `llama-2`, `falcon`, `mistral`, `bart`, `t5`, `deberta`, `bert`, `roberta`.
51
+
52
+ Below is an example of obtaining 4bit LLAMA-2-7b with 16-rank LoRA adapters by 5 alternating steps.
53
+ ```sh
54
+ SAVE_DIR="model_zoo/loftq/"
55
+ python quantize_save_load.py \
56
+ --model_name_or_path meta-llama/Llama-2-7b-hf \ # high-precision model id in HF
57
+ --token HF_TOKEN \ # your HF token if the model is private, e.g., llama-2
58
+ --bits 4 \
59
+ --iter 5 \
60
+ --rank 16 \
61
+ --save_dir $SAVE_DIR
62
+ ```
63
+
64
+ The above commands end up with creating the model directory under `$SAVE_DIR`.
65
+ Specifically, the model directory is named as
66
+
67
+ `MODEL_DIR = SAVE_DIR + f"{args.model_name_or_path.split('/')[-1]}-{args.bits}bits-{args.rank}rank"`
68
+
69
+ In this example, `MODEL_DIR="model_zoo/loftq/Llama-2-7b-hf-4bit-16rank"`, where the backbone is stored in `$MODEL_DIR`
70
+ and the LoRA adapters are at the sub-folder `$MODEL_DIR/loftq_init`.
71
+
72
+ ### Load and train
73
+ Similar to loading from Huggingface Hub, we only need to change the `MODEL_ID` to the `MODEL_DIR`.
74
+
75
+ ```python
76
+ import torch
77
+ from transformers import AutoModelForCausalLM, BitsAndBytesConfig
78
+ from peft import PeftModel
79
+
80
+ MODEL_DIR = "model_zoo/loftq/Llama-2-7b-hf-4bit-16rank"
81
+
82
+ base_model = AutoModelForCausalLM.from_pretrained(
83
+ MODEL_DIR,
84
+ dtype=torch.bfloat16,
85
+ quantization_config=BitsAndBytesConfig(
86
+ load_in_4bit=True,
87
+ bnb_4bit_compute_dtype=torch.bfloat16,
88
+ bnb_4bit_use_double_quant=False,
89
+ bnb_4bit_quant_type='nf4',
90
+ ),
91
+ )
92
+ peft_model = PeftModel.from_pretrained(
93
+ base_model,
94
+ MODEL_DIR,
95
+ subfolder="loftq_init",
96
+ is_trainable=True,
97
+ )
98
+ # Do training with peft_model ...
99
+ ```
100
+
101
+ ## LoftQ Fine-tuning
102
+
103
+ We also provide an example to fine-tune LoftQ on GSM8K.
104
+ We load the quantized backbone and LoRA adapters from the [LoftQ Huggingface hub](https://huggingface.co/LoftQ).
105
+
106
+ ```sh
107
+ python train_gsm8k_llama.py \
108
+ --model_name_or_path LoftQ/Llama-2-13b-hf-4bit-64rank \
109
+ --output_dir exp_results/gsm8k/llama-2-13b/bit4-rank64/lr1e-4 \
110
+ --learning_rate 1e-4 \
111
+ --weight_decay 0.1 \
112
+ --lr_scheduler_type cosine \
113
+ --num_warmup_steps 100 \
114
+ --seed 202 \
115
+ --dataset_name gsm8k \
116
+ --dataset_config main \
117
+ --pad_to_max_length \
118
+ --max_source_length 128 \
119
+ --max_target_length 256 \
120
+ --num_train_epochs 5 \
121
+ --per_device_train_batch_size 4 \
122
+ --per_device_eval_batch_size 4 \
123
+ --gradient_accumulation_steps 4 \
124
+ --with_tracking \
125
+ --report_to tensorboard
126
+ ```
127
+
128
+
129
+ ## Appendix: Off-the-shelf Model List
130
+ | Model Name | Bits | Ranks |
131
+ | ----------- | ---- | ----- |
132
+ | LLAMA-2-7b | 4 | 64 |
133
+ | LLAMA-2-13b | 4 | 64 |
134
+ | LLAMA-2-70b | 4 | 64 |
135
+ | Mistral | 4 | 64 |
136
+ | Mistral | 4 | 32 |
137
+ | BART-large | 4 | 8 |
138
+ | BART-large | 4 | 16 |
139
+ | BART-large | 4 | 32 |
140
+ | BART-large | 2 | 8 |
141
+
142
+ ## In-place application of LoftQ initialization
143
+
144
+ PEFT provides a convenience function `replace_lora_weights_loftq` to apply LoftQ initialization in-place to the quantized model. Check out [this notebook](https://github.com/huggingface/peft/blob/main/examples/loftq_finetuning/LoftQ_weight_replacement.ipynb) for an example.
tasks/tasksmith-c488fc138ba1/tests/source/examples/loftq_finetuning/int8_correction.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """
3
+ Script to show-case how to offset quantization error with LoRA / LoftQ
4
+ when dealing with quantizations that both quantize weights and activations.
5
+ This is the case for bnb int8, for example, but also other quantizations
6
+ such as BitNet do this.
7
+
8
+ The math for how this works is explained in MyLinear8bitLt.forward and
9
+ can be seen quickly when defining W_q = W + E_W (quantized weight is the
10
+ sum of the original weights plus an error term) and the same for
11
+ x_q = x + e_x.
12
+
13
+ To demonstrate the effectiveness, we load a unquantized model, generate
14
+ logits for reference inputs and then do the same for a quantized model
15
+ and a quantized model with LoftQ and our mitigations applied. The
16
+ error between reference model logits and LoftQ logits is significantly
17
+ smaller compared to the logits produced by the quantized model without
18
+ mitigation.
19
+
20
+ Note: set llm_int8_threshold=0 in your BitsAndBytesConfig. The thresholding
21
+ enables dynamic fp16 quantization (for x values above that threshold).
22
+ The quantization error for the affected values is much lower and not
23
+ static anymore, LoftQ is not able to deal with this. While technically
24
+ possible, this script doesn't filter out these masked values and it
25
+ is probably not worth the effort.
26
+
27
+ Note: Some rudimentary testing showed that the LoftQ mitigation is still
28
+ more effective than tuning threshold values but YMMV.
29
+
30
+ Note: LoftQ is not doing the heavy lifting in this script's case. The error
31
+ between LoftQ and zeroed LoRA is only about two percent points (check this
32
+ yourself by using the `--no-loftq` flag). This effect is probably dependent
33
+ on the quantization strength.
34
+
35
+ Examples of experiments you can do:
36
+
37
+ - check the difference between applying no-op LoRA and LoftQ initialized
38
+ LoRA by running the following two commands:
39
+ * ./int8_correction.py --no-mitigation
40
+ * ./int8_correction.py --no-mitigation --no-loftq
41
+
42
+ - check the effect of the mitigation vs. the static compenstation by LoftQ:
43
+ * ./int8_correction.py
44
+ * ./int8_correction.py --no-loftq
45
+
46
+ - check the rank contribution for LoftQ:
47
+ * for r in 8 16 32 64 128; do ./int8_correction.py --rank $i --no-mitigation; done
48
+
49
+ """
50
+
51
+ import argparse
52
+ from pathlib import Path
53
+ from tempfile import TemporaryDirectory
54
+
55
+ import bitsandbytes as bnb
56
+ import torch
57
+ from transformers import AutoModelForCausalLM, AutoModelForSeq2SeqLM, AutoTokenizer, BitsAndBytesConfig
58
+
59
+ import peft.tuners.lora.bnb
60
+ from peft import LoftQConfig, LoraConfig, PeftModel, TaskType, get_peft_model
61
+
62
+
63
+ torch.backends.cudnn.deterministic = True
64
+ torch.backends.cudnn.benchmark = False
65
+
66
+
67
+ class MyLinear8bitLt(peft.tuners.lora.bnb.Linear8bitLt):
68
+ def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor:
69
+ self._check_forward_args(x, *args, **kwargs)
70
+ adapter_names = kwargs.pop("adapter_names", None)
71
+
72
+ if self.disable_adapters:
73
+ if self.merged:
74
+ self.unmerge()
75
+ result = self.base_layer(x, *args, **kwargs)
76
+ elif adapter_names is not None:
77
+ result = self._mixed_batch_forward(x, *args, adapter_names=adapter_names, **kwargs)
78
+ elif self.merged:
79
+ result = self.base_layer(x, *args, **kwargs)
80
+ else:
81
+ result = self.base_layer(x, *args, **kwargs)
82
+ for active_adapter in self.active_adapters:
83
+ if active_adapter not in self.lora_A.keys():
84
+ continue
85
+ lora_A = self.lora_A[active_adapter]
86
+ lora_B = self.lora_B[active_adapter]
87
+ dropout = self.lora_dropout[active_adapter]
88
+ scaling = self.scaling[active_adapter]
89
+
90
+ requires_conversion = not torch.is_autocast_enabled()
91
+ if requires_conversion:
92
+ expected_dtype = result.dtype
93
+ x = self._cast_input_dtype(x, lora_A.weight.dtype)
94
+
95
+ # The premise of this is that when we quantize, we introduce an
96
+ # error. This means that quantizing x to xq we can state that
97
+ # x = x_q + e_x or x_q = x - e_x. The same goes for W: W = W_q + E_W
98
+ # or W_q = W - E_W.
99
+ #
100
+ # LoftQ computes E_W, applies SVD and initializes LoRA's B and A with
101
+ # self.r ranks of E_W, giving us ~E_W. For our forward this means:
102
+ # y = W_q x + BAx = (W_q + BA) x = (W_q + ~E_W) x = W x
103
+ # if ~E_W is close enough to E_W.
104
+ #
105
+ # This breaks down if x is also quantized (as is the case for bnb int8):
106
+ # y = W_q x_q + BA x_q = (W_q + ~E_W) x_q = W x_q = W (x - e_x) = Wx - W e_x
107
+ #
108
+ # Since e_x is non-zero and W is relatively large, it is a non-negligible
109
+ # error term. But we can offset this, since we can compute e_x and we can
110
+ # approximate W with W_q - or - in the case of LoftQ with ~E_W. Both work.
111
+ # I didn't see a difference empirically but with other quantizations this
112
+ # might change. In any case, we can compute ex_mitigation = W_q e_x and
113
+ # add it along with the LoRA to remove the W e_x term and be left with
114
+ # y = Wx.
115
+ #
116
+ # This is the term yielding the most error correction gain. There's a
117
+ # smaller gain to be had by passing x_q to the LoRA's layers. Let's
118
+ # revisit the quantized base layer definition:
119
+ # y = W_q x_q = (W - E_W) (x - e_x) = Wx - W e_x - E_W x + E_W e_x
120
+ #
121
+ # (W e_x) we handled before, (- E_W x) is what we approximate with (~E_W x)
122
+ # and is subsequently removed as well but this leaves us (E_W e_x).
123
+ # It turns out, if you pass x_q into the LoRA modules, you will end up
124
+ # with (~E_W x - ~E_W e_x) - which removes this term as well.
125
+
126
+ # Compute x_q (int8 quantized x) to pass it into the LoRA's forward.
127
+ CB, SCB, _ = bnb.functional.int8_vectorwise_quant(x.half())
128
+ CB = CB.reshape(-1, CB.shape[-1])
129
+ x_q = bnb.functional.int8_vectorwise_dequant(CB, SCB).to(lora_A.weight.dtype)
130
+ x_q = x_q.reshape(*x.shape)
131
+
132
+ e_x = x - x_q
133
+ W_dq = bnb.functional.int8_vectorwise_dequant(self.base_layer.state.CB, self.base_layer.state.SCB).to(
134
+ e_x.dtype
135
+ )
136
+ e_x_mitigation = e_x @ W_dq.T
137
+ # e_x_mitigation = e_x @ (W_dq.T + (lora_B.weight @ lora_A.weight * scaling).T)
138
+
139
+ output = lora_B(lora_A(dropout(x_q))) * scaling
140
+ output += e_x_mitigation
141
+ if requires_conversion:
142
+ output = output.to(expected_dtype)
143
+ result = result + output
144
+
145
+ return result
146
+
147
+
148
+ parser = argparse.ArgumentParser()
149
+ parser.add_argument(
150
+ "--no-loftq", action="store_true", default=False, help="Disable LoftQ initialization (LoRA no-op init instead)"
151
+ )
152
+ parser.add_argument(
153
+ "--no-mitigation", action="store_true", default=False, help="Disable activation quantization mitigiation"
154
+ )
155
+ parser.add_argument(
156
+ "--model",
157
+ choices=["t5-small", "t5-base", "t5-large", "facebook/opt-125m"],
158
+ default="t5-base",
159
+ help="What model to test.",
160
+ )
161
+ parser.add_argument("--rank", type=int, default=64)
162
+ parser.add_argument("--device", type=str, default="cuda")
163
+ parser.add_argument(
164
+ "--int8-threshold", type=float, default=0.0, help="To demonstrate that int8 threshold > 0 doesn't work"
165
+ )
166
+
167
+ args = parser.parse_args()
168
+
169
+ device = args.device
170
+ qconf = BitsAndBytesConfig(
171
+ load_in_8bit=True,
172
+ llm_int8_threshold=args.int8_threshold,
173
+ )
174
+ input_texts = [
175
+ "All I need",
176
+ "All I want is",
177
+ "Forever yours truly: ",
178
+ "Translate French to German: Tu l'as lu?",
179
+ "Translate German to French: Last du es?",
180
+ (
181
+ "Beautiful is better than ugly.\n"
182
+ "Explicit is better than implicit.\n"
183
+ "Simple is better than complex.\n"
184
+ "Complex is better than complicated.\n"
185
+ ),
186
+ ]
187
+ bits = 8
188
+ loftq_iter = 1
189
+ rank = args.rank
190
+
191
+ model_id = args.model
192
+
193
+ if "t5" in args.model:
194
+ target_modules = ["o", "k", "wi", "q", "v"]
195
+ task_type = TaskType.SEQ_2_SEQ_LM
196
+ else:
197
+ target_modules = "all-linear"
198
+ task_type = TaskType.CAUSAL_LM
199
+
200
+ # ----
201
+
202
+
203
+ def get_logits(model, inputs):
204
+ torch.manual_seed(0)
205
+ if task_type == TaskType.CAUSAL_LM:
206
+ return model(**inputs).logits
207
+
208
+ with torch.inference_mode():
209
+ return model(**inputs, labels=inputs["input_ids"]).logits
210
+
211
+
212
+ def mse(a, b, attention_mask=None):
213
+ squared_error = torch.pow(a - b, 2)
214
+ if attention_mask is not None:
215
+ # attention_mask shape: [batch_size, seq_len]
216
+ # squared_error shape: [batch_size, seq_len, vocab_size]
217
+ # apply the mask (zeros out the squared error for padding tokens)
218
+ mask = attention_mask.unsqueeze(-1).expand_as(squared_error)
219
+ masked_squared_error = squared_error * mask
220
+ return (masked_squared_error.sum() / mask.sum()).item()
221
+ return squared_error.mean().item()
222
+
223
+
224
+ def get_model(*args, **kwargs):
225
+ if task_type == TaskType.CAUSAL_LM:
226
+ return AutoModelForCausalLM.from_pretrained(*args, **kwargs)
227
+ return AutoModelForSeq2SeqLM.from_pretrained(*args, **kwargs)
228
+
229
+
230
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
231
+ inputs = tokenizer(input_texts, padding=True, return_tensors="pt").to(device)
232
+
233
+ ref_model = get_model(model_id, dtype=torch.float32, device_map=device)
234
+ qref_model = get_model(model_id, quantization_config=qconf, dtype=torch.float32, device_map=device)
235
+
236
+ loftq_config = LoftQConfig(loftq_bits=bits, loftq_iter=loftq_iter)
237
+ lora_config = LoraConfig(
238
+ task_type=task_type,
239
+ r=rank,
240
+ init_lora_weights=True if args.no_loftq else "loftq",
241
+ loftq_config=loftq_config,
242
+ target_modules=target_modules,
243
+ )
244
+
245
+ base_model = get_model(model_id, dtype=torch.float32, device_map=device)
246
+ loftq_model = get_peft_model(base_model, lora_config)
247
+
248
+ print("APPLYING SAVED ADAPTER TO QUANTIZED MODEL")
249
+ with TemporaryDirectory() as tmp_path:
250
+ tmp_path = Path(tmp_path)
251
+ loftq_model.base_model.peft_config["default"].init_lora_weights = True
252
+ loftq_model.save_pretrained(tmp_path / "loftq_model")
253
+
254
+ lora_config = LoraConfig.from_pretrained(tmp_path / "loftq_model")
255
+ model_id = args.model
256
+
257
+ if not args.no_mitigation:
258
+ custom_module_mapping = {bnb.nn.Linear8bitLt: MyLinear8bitLt}
259
+ lora_config._register_custom_module(custom_module_mapping)
260
+
261
+ base_model = get_model(model_id, quantization_config=qconf, dtype=torch.float32, device_map=device)
262
+ loftq_model = PeftModel.from_pretrained(
263
+ base_model, tmp_path / "loftq_model", is_trainable=True, config=lora_config
264
+ )
265
+
266
+
267
+ ref_logits = get_logits(ref_model, inputs)
268
+
269
+ qref_logits = get_logits(qref_model, inputs)
270
+ loftq_logits = get_logits(loftq_model, inputs)
271
+
272
+ mse_loftq = mse(ref_logits, loftq_logits, attention_mask=inputs["attention_mask"])
273
+ mse_qref = mse(ref_logits, qref_logits, attention_mask=inputs["attention_mask"])
274
+
275
+
276
+ print(f"{model_id=}{device=}")
277
+ print(f"{mse_qref=}, {mse_loftq=}")
278
+ assert mse_loftq < (mse_qref / 1.05), f"{mse_loftq} >= {mse_qref / 1.05}"
279
+ print(f"relative reduction of error: {(mse_qref - mse_loftq) / mse_qref * 100:.2f}%")
tasks/tasksmith-c488fc138ba1/tests/source/examples/loftq_finetuning/quantize_save_load.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 argparse
16
+ import os
17
+
18
+ import torch
19
+ from torch import nn
20
+ from transformers import (
21
+ AutoModelForCausalLM,
22
+ AutoModelForSeq2SeqLM,
23
+ AutoModelForSequenceClassification,
24
+ AutoTokenizer,
25
+ )
26
+
27
+ from peft import LoftQConfig, LoraConfig, TaskType, get_peft_model
28
+
29
+
30
+ class Shell(nn.Module):
31
+ def __init__(self, weight, bias=None):
32
+ super().__init__()
33
+ self.weight = nn.Parameter(weight, requires_grad=False)
34
+ if bias is not None:
35
+ self.bias = nn.Parameter(bias, requires_grad=False)
36
+
37
+
38
+ def unwrap_model(model, sub_module_name=".base_layer"):
39
+ sub_module_name_list = [k.split(sub_module_name)[0] for k in model.state_dict().keys() if sub_module_name in k]
40
+ sub_module_name_set = set(sub_module_name_list)
41
+ for name in sub_module_name_set:
42
+ # get the parent of the submodule
43
+ name_parent = ".".join(name.split(".")[:-1])
44
+ name_child = name.split(".")[-1]
45
+ sub_module = model.get_submodule(name_parent)
46
+ print(sub_module)
47
+
48
+ # replace with shell
49
+ child = getattr(sub_module, name_child)
50
+ weight = getattr(child.base_layer, "weight", None)
51
+ bias = getattr(child.base_layer, "bias", None)
52
+ shell = Shell(weight, bias)
53
+
54
+ setattr(sub_module, name_child, shell)
55
+
56
+ print("You have unwrapped the model. Use it on your own risk.")
57
+
58
+
59
+ def print_model(model, name):
60
+ print("=" * 10 + name + "=" * 10)
61
+ print(model)
62
+ for param_name, param in model.named_parameters():
63
+ if torch.is_tensor(param):
64
+ if param.dtype in [torch.float32, torch.float16]:
65
+ print(
66
+ param_name,
67
+ param.shape,
68
+ param.device,
69
+ param.dtype,
70
+ param.requires_grad,
71
+ param.mean().item(),
72
+ param.max().item(),
73
+ )
74
+ else:
75
+ print(name, param.shape, param.device, param.dtype, param.requires_grad)
76
+
77
+
78
+ def arg_parse():
79
+ parser = argparse.ArgumentParser(description="Quantize a model with LoftQ.")
80
+ parser.add_argument(
81
+ "--model_name_or_path",
82
+ type=str,
83
+ default=None,
84
+ required=True,
85
+ help="The name or path of the fp32/16 model.",
86
+ )
87
+ parser.add_argument(
88
+ "--token",
89
+ type=str,
90
+ default=None,
91
+ help="The access token to download model from HuggingFace Hub.",
92
+ )
93
+ parser.add_argument(
94
+ "--bits",
95
+ type=int,
96
+ default=4,
97
+ help="The quantized bits",
98
+ )
99
+ parser.add_argument(
100
+ "--iter",
101
+ type=int,
102
+ default=1,
103
+ help="The alternating steps in LoftQ",
104
+ )
105
+ parser.add_argument(
106
+ "--rank",
107
+ type=int,
108
+ default=16,
109
+ help="The rank of the LoRA adapter",
110
+ )
111
+ parser.add_argument(
112
+ "--save_dir",
113
+ type=str,
114
+ default="./model_zoo/loftq/",
115
+ help="The rank of the LoRA adapter",
116
+ )
117
+ args = parser.parse_args()
118
+ return args
119
+
120
+
121
+ def quantize_and_save():
122
+ args = arg_parse()
123
+
124
+ # Download weights and configure LoRA
125
+ tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path, token=args.token, trust_remote_code=True)
126
+ if any(name in args.model_name_or_path.lower() for name in ["llama", "mistral", "falcon"]):
127
+ model = AutoModelForCausalLM.from_pretrained(args.model_name_or_path, token=args.token, trust_remote_code=True)
128
+ task_type = TaskType.CAUSAL_LM
129
+ target_modules = ["q_proj", "k_proj", "v_proj", "o_proj", "up_proj", "down_proj", "gate_proj"]
130
+
131
+ elif any(name in args.model_name_or_path.lower() for name in ["bart", "t5"]):
132
+ model = AutoModelForSeq2SeqLM.from_pretrained(args.model_name_or_path, token=args.token)
133
+ task_type = TaskType.SEQ_2_SEQ_LM
134
+ target_modules = ["q_proj", "k_proj", "v_proj", "fc1", "fc2", "out_proj"]
135
+
136
+ elif any(name in args.model_name_or_path.lower() for name in ["deberta", "roberta", "bert"]):
137
+ model = AutoModelForSequenceClassification.from_pretrained(args.model_name_or_path, token=args.token)
138
+ task_type = TaskType.SEQ_CLS
139
+ target_modules = ["query_proj", "key_proj", "value_proj", "dense"] # embeddings not supported by peft
140
+ else:
141
+ raise NotImplementedError("Other models not supported yet.")
142
+
143
+ # Config of LoftQ
144
+ loftq_config = LoftQConfig(loftq_bits=args.bits, loftq_iter=args.iter)
145
+
146
+ lora_config = LoraConfig(
147
+ task_type=task_type,
148
+ inference_mode=True,
149
+ r=args.rank,
150
+ lora_alpha=16 if task_type is TaskType.CAUSAL_LM else args.rank,
151
+ lora_dropout=0.1,
152
+ target_modules=target_modules,
153
+ init_lora_weights="loftq",
154
+ loftq_config=loftq_config,
155
+ )
156
+
157
+ # Obtain LoftQ model
158
+ lora_model = get_peft_model(model, lora_config)
159
+ base_model = lora_model.get_base_model()
160
+
161
+ # Save LoftQ model
162
+ model_name = args.model_name_or_path.split("/")[-1] + f"-{args.bits}bit" + f"-{args.rank}rank"
163
+ base_model_dir = os.path.join(args.save_dir, model_name)
164
+ lora_model_dir = os.path.join(args.save_dir, model_name, "loft_init")
165
+
166
+ # save lora adapters first
167
+ lora_model.base_model.peft_config[
168
+ "default"
169
+ ].base_model_name_or_path = base_model_dir # This can be a local path or Hub model id
170
+ lora_model.base_model.peft_config["default"].init_lora_weights = True # Don't apply LoftQ when loading again
171
+
172
+ lora_model.save_pretrained(lora_model_dir)
173
+ print_model(lora_model, "lora_model")
174
+
175
+ # remove lora adapters and save the backbone
176
+ unwrap_model(base_model)
177
+ base_model.save_pretrained(base_model_dir)
178
+ tokenizer.save_pretrained(base_model_dir)
179
+
180
+ print_model(base_model, "base_model")
181
+
182
+ return base_model_dir, lora_model_dir
183
+
184
+
185
+ if __name__ == "__main__":
186
+ base_dir, lora_dir = quantize_and_save()
187
+
188
+ # example command:
189
+ # python quantize_save_load.py \
190
+ # --model_name_or_path meta-llama/Llama-2-7b-hf \
191
+ # --token XXX \
192
+ # --bits 4 --iter 5 --rank 16 \
193
+ # --save_dir ./model_zoo/loftq/
tasks/tasksmith-c488fc138ba1/tests/source/examples/loftq_finetuning/train_gsm8k_llama.py ADDED
@@ -0,0 +1,851 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 argparse
16
+ import copy
17
+ import logging
18
+ import math
19
+ import os
20
+ import random
21
+ import re
22
+ from pathlib import Path
23
+
24
+ import datasets
25
+ import torch
26
+ import transformers
27
+ from accelerate import Accelerator, DistributedType
28
+ from accelerate.logging import get_logger
29
+ from accelerate.utils import set_seed
30
+ from datasets import load_dataset
31
+ from huggingface_hub import HfApi
32
+ from torch.utils.data import DataLoader
33
+ from tqdm.auto import tqdm
34
+ from transformers import (
35
+ CONFIG_MAPPING,
36
+ MODEL_MAPPING,
37
+ AutoConfig,
38
+ AutoModelForCausalLM,
39
+ AutoTokenizer,
40
+ BitsAndBytesConfig,
41
+ SchedulerType,
42
+ default_data_collator,
43
+ get_scheduler,
44
+ )
45
+ from transformers.utils import send_example_telemetry
46
+ from transformers.utils.versions import require_version
47
+
48
+ from peft import PeftModel
49
+
50
+
51
+ # Will error if the minimal version of Transformers is not installed. Remove at your own risks.
52
+ # check_min_version("4.32.0.dev0")
53
+
54
+ logger = get_logger(__name__)
55
+
56
+ require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/language-modeling/requirements.txt")
57
+
58
+ MODEL_CONFIG_CLASSES = list(MODEL_MAPPING.keys())
59
+ MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
60
+
61
+
62
+ def parse_args():
63
+ parser = argparse.ArgumentParser(description="Finetune a transformers model on a causal language modeling task")
64
+ parser.add_argument(
65
+ "--dataset_name",
66
+ type=str,
67
+ default=None,
68
+ help="The name of the dataset to use (via the datasets library).",
69
+ )
70
+ parser.add_argument(
71
+ "--dataset_config_name",
72
+ type=str,
73
+ default=None,
74
+ help="The configuration name of the dataset to use (via the datasets library).",
75
+ )
76
+ parser.add_argument(
77
+ "--train_file", type=str, default=None, help="A csv, txt or a json file containing the training data."
78
+ )
79
+ parser.add_argument(
80
+ "--validation_file", type=str, default=None, help="A csv, txt or a json file containing the validation data."
81
+ )
82
+ parser.add_argument(
83
+ "--validation_split_percentage",
84
+ default=5,
85
+ help="The percentage of the train set used as validation set in case there's no validation split",
86
+ )
87
+ parser.add_argument(
88
+ "--model_name_or_path",
89
+ type=str,
90
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
91
+ required=False,
92
+ )
93
+ parser.add_argument(
94
+ "--config_name",
95
+ type=str,
96
+ default=None,
97
+ help="Pretrained config name or path if not the same as model_name",
98
+ )
99
+ parser.add_argument(
100
+ "--tokenizer_name",
101
+ type=str,
102
+ default=None,
103
+ help="Pretrained tokenizer name or path if not the same as model_name",
104
+ )
105
+ parser.add_argument(
106
+ "--use_slow_tokenizer",
107
+ action="store_true",
108
+ help="If passed, will use a slow tokenizer (not backed by the 🤗 Tokenizers library).",
109
+ )
110
+ parser.add_argument(
111
+ "--per_device_train_batch_size",
112
+ type=int,
113
+ default=8,
114
+ help="Batch size (per device) for the training dataloader.",
115
+ )
116
+ parser.add_argument(
117
+ "--per_device_eval_batch_size",
118
+ type=int,
119
+ default=8,
120
+ help="Batch size (per device) for the evaluation dataloader.",
121
+ )
122
+ parser.add_argument(
123
+ "--learning_rate",
124
+ type=float,
125
+ default=5e-5,
126
+ help="Initial learning rate (after the potential warmup period) to use.",
127
+ )
128
+ parser.add_argument("--weight_decay", type=float, default=0.0, help="Weight decay to use.")
129
+ parser.add_argument("--num_train_epochs", type=int, default=3, help="Total number of training epochs to perform.")
130
+ parser.add_argument(
131
+ "--max_train_steps",
132
+ type=int,
133
+ default=None,
134
+ help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
135
+ )
136
+ parser.add_argument(
137
+ "--gradient_accumulation_steps",
138
+ type=int,
139
+ default=1,
140
+ help="Number of updates steps to accumulate before performing a backward/update pass.",
141
+ )
142
+ parser.add_argument(
143
+ "--lr_scheduler_type",
144
+ type=SchedulerType,
145
+ default="linear",
146
+ help="The scheduler type to use.",
147
+ choices=["linear", "cosine", "cosine_with_restarts", "polynomial", "constant", "constant_with_warmup"],
148
+ )
149
+ parser.add_argument(
150
+ "--num_warmup_steps", type=int, default=0, help="Number of steps for the warmup in the lr scheduler."
151
+ )
152
+ parser.add_argument("--output_dir", type=str, default=None, help="Where to store the final model.")
153
+ parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
154
+ parser.add_argument(
155
+ "--model_type",
156
+ type=str,
157
+ default=None,
158
+ help="Model type to use if training from scratch.",
159
+ choices=MODEL_TYPES,
160
+ )
161
+ parser.add_argument(
162
+ "--ignore_pad_token_for_loss",
163
+ type=bool,
164
+ default=True,
165
+ help="Whether to ignore the tokens corresponding to padded labels in the loss computation or not.",
166
+ )
167
+ parser.add_argument(
168
+ "--max_source_length",
169
+ type=int,
170
+ default=128,
171
+ help=(
172
+ "The maximum total input sequence length after "
173
+ "tokenization.Sequences longer than this will be truncated, sequences shorter will be padded."
174
+ ),
175
+ )
176
+ parser.add_argument(
177
+ "--max_target_length",
178
+ type=int,
179
+ default=128,
180
+ help=(
181
+ "The maximum total sequence length for target text after "
182
+ "tokenization. Sequences longer than this will be truncated, sequences shorter will be padded."
183
+ "during ``evaluate`` and ``predict``."
184
+ ),
185
+ )
186
+ parser.add_argument(
187
+ "--pad_to_max_length",
188
+ action="store_true",
189
+ help="If passed, pad all samples to `max_length`. Otherwise, dynamic padding is used.",
190
+ )
191
+ parser.add_argument(
192
+ "--preprocessing_num_workers",
193
+ type=int,
194
+ default=None,
195
+ help="The number of processes to use for the preprocessing.",
196
+ )
197
+ parser.add_argument(
198
+ "--overwrite_cache", action="store_true", help="Overwrite the cached training and evaluation sets"
199
+ )
200
+ parser.add_argument(
201
+ "--no_keep_linebreaks", action="store_true", help="Do not keep line breaks when using TXT files."
202
+ )
203
+ parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
204
+ parser.add_argument(
205
+ "--hub_model_id", type=str, help="The name of the repository to keep in sync with the local `output_dir`."
206
+ )
207
+ parser.add_argument("--hub_token", type=str, help="The token to use to push to the Model Hub.")
208
+ parser.add_argument(
209
+ "--trust_remote_code",
210
+ type=bool,
211
+ default=False,
212
+ help=(
213
+ "Whether or not to allow for custom models defined on the Hub in their own modeling files. This option"
214
+ "should only be set to `True` for repositories you trust and in which you have read the code, as it will"
215
+ "execute code present on the Hub on your local machine."
216
+ ),
217
+ )
218
+ parser.add_argument(
219
+ "--checkpointing_steps",
220
+ type=str,
221
+ default=None,
222
+ help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.",
223
+ )
224
+ parser.add_argument(
225
+ "--resume_from_checkpoint",
226
+ type=str,
227
+ default=None,
228
+ help="If the training should continue from a checkpoint folder.",
229
+ )
230
+ parser.add_argument(
231
+ "--with_tracking",
232
+ action="store_true",
233
+ help="Whether to enable experiment trackers for logging.",
234
+ )
235
+ parser.add_argument(
236
+ "--report_to",
237
+ type=str,
238
+ default="tensorboard",
239
+ help=(
240
+ 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`,'
241
+ ' `"wandb"`, `"comet_ml"` and `"clearml"`. Use `"all"` (default) to report to all integrations.'
242
+ "Only applicable when `--with_tracking` is passed."
243
+ ),
244
+ )
245
+ parser.add_argument(
246
+ "--low_cpu_mem_usage",
247
+ action="store_true",
248
+ help=(
249
+ "It is an option to create the model as an empty shell, then only materialize its parameters when the pretrained weights are loaded."
250
+ "If passed, LLM loading time and RAM consumption will be benefited."
251
+ ),
252
+ )
253
+ ##########################
254
+ # Generation Config #
255
+ ##########################
256
+ parser.add_argument(
257
+ "--temperature",
258
+ type=float,
259
+ default=0.8,
260
+ help="temperature of 1.0 has no effect, lower tend toward greedy sampling",
261
+ )
262
+ parser.add_argument("--k", type=int, default=40, help="Choose k candidate words")
263
+ parser.add_argument("--p", type=float, default=0.95, help="The sum of probability of candidate words is 0.9 ")
264
+
265
+ ##########################
266
+ # Exp Args #
267
+ ##########################
268
+ parser.add_argument(
269
+ "--adapter_name_or_path",
270
+ type=str,
271
+ default=None,
272
+ help=(
273
+ "The LoRA adapter checkpoint. Set None if you want to fine-tune from LoftQ."
274
+ "Specify a path if you want to evaluate."
275
+ ),
276
+ )
277
+
278
+ args = parser.parse_args()
279
+
280
+ # Sanity checks
281
+ if args.dataset_name is None and args.train_file is None and args.validation_file is None:
282
+ raise ValueError("Need either a dataset name or a training/validation file.")
283
+ else:
284
+ if args.train_file is not None:
285
+ extension = args.train_file.split(".")[-1]
286
+ assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, json or txt file."
287
+ if args.validation_file is not None:
288
+ extension = args.validation_file.split(".")[-1]
289
+ assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, json or txt file."
290
+
291
+ if args.push_to_hub:
292
+ assert args.output_dir is not None, "Need an `output_dir` to create a repo when `--push_to_hub` is passed."
293
+
294
+ return args
295
+
296
+
297
+ def main():
298
+ args = parse_args()
299
+
300
+ # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
301
+ # information sent is the one passed as arguments along with your Python/PyTorch versions.
302
+ send_example_telemetry("run_clm_no_trainer", args)
303
+
304
+ # Initialize the accelerator. We will let the accelerator handle device placement for us in this example.
305
+ # If we're using tracking, we also need to initialize it here and it will by default pick up all supported trackers
306
+ # in the environment
307
+ accelerator_log_kwargs = {}
308
+
309
+ if args.with_tracking:
310
+ accelerator_log_kwargs["log_with"] = args.report_to
311
+ accelerator_log_kwargs["project_dir"] = args.output_dir
312
+
313
+ accelerator = Accelerator(gradient_accumulation_steps=args.gradient_accumulation_steps, **accelerator_log_kwargs)
314
+
315
+ # Make one log on every process with the configuration for debugging.
316
+ logging.basicConfig(
317
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
318
+ datefmt="%m/%d/%Y %H:%M:%S",
319
+ level=logging.INFO,
320
+ )
321
+ logger.info(accelerator.state, main_process_only=False)
322
+ if accelerator.is_local_main_process:
323
+ datasets.utils.logging.set_verbosity_warning()
324
+ transformers.utils.logging.set_verbosity_info()
325
+ else:
326
+ datasets.utils.logging.set_verbosity_error()
327
+ transformers.utils.logging.set_verbosity_error()
328
+
329
+ # If passed along, set the training seed now.
330
+ if args.seed is not None:
331
+ set_seed(args.seed)
332
+
333
+ # Handle the repository creation
334
+ if accelerator.is_main_process:
335
+ if args.push_to_hub:
336
+ api = HfApi(token=args.hub_token)
337
+
338
+ # Create repo (repo_name from args or inferred)
339
+ repo_name = args.hub_model_id
340
+ if repo_name is None:
341
+ repo_name = Path(args.output_dir).absolute().name
342
+ repo_id = api.create_repo(repo_name, exist_ok=True).repo_id
343
+
344
+ with open(os.path.join(args.output_dir, ".gitignore"), "w+") as gitignore:
345
+ if "step_*" not in gitignore:
346
+ gitignore.write("step_*\n")
347
+ if "epoch_*" not in gitignore:
348
+ gitignore.write("epoch_*\n")
349
+ elif args.output_dir is not None:
350
+ os.makedirs(args.output_dir, exist_ok=True)
351
+ accelerator.wait_for_everyone()
352
+
353
+ # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
354
+ # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
355
+ # (the dataset will be downloaded automatically from the datasets Hub).
356
+ #
357
+ # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
358
+ # 'text' is found. You can easily tweak this behavior (see below).
359
+ #
360
+ # In distributed training, the load_dataset function guarantee that only one local process can concurrently
361
+ # download the dataset.
362
+ if args.dataset_name is not None:
363
+ # Downloading and loading a dataset from the hub.
364
+ raw_datasets = load_dataset(args.dataset_name, args.dataset_config_name)
365
+ if "validation" not in raw_datasets.keys():
366
+ raw_datasets["validation"] = load_dataset(
367
+ args.dataset_name,
368
+ args.dataset_config_name,
369
+ split=f"train[:{args.validation_split_percentage}%]",
370
+ )
371
+ raw_datasets["train"] = load_dataset(
372
+ args.dataset_name,
373
+ args.dataset_config_name,
374
+ split=f"train[{args.validation_split_percentage}%:]",
375
+ )
376
+ else:
377
+ data_files = {}
378
+ dataset_args = {}
379
+ if args.train_file is not None:
380
+ data_files["train"] = args.train_file
381
+ if args.validation_file is not None:
382
+ data_files["validation"] = args.validation_file
383
+ extension = args.train_file.split(".")[-1]
384
+ if extension == "txt":
385
+ extension = "text"
386
+ dataset_args["keep_linebreaks"] = not args.no_keep_linebreaks
387
+ raw_datasets = load_dataset(extension, data_files=data_files, **dataset_args)
388
+ # If no validation data is there, validation_split_percentage will be used to divide the dataset.
389
+ if "validation" not in raw_datasets.keys():
390
+ raw_datasets["validation"] = load_dataset(
391
+ extension,
392
+ data_files=data_files,
393
+ split=f"train[:{args.validation_split_percentage}%]",
394
+ **dataset_args,
395
+ )
396
+ raw_datasets["train"] = load_dataset(
397
+ extension,
398
+ data_files=data_files,
399
+ split=f"train[{args.validation_split_percentage}%:]",
400
+ **dataset_args,
401
+ )
402
+
403
+ # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
404
+ # https://huggingface.co/docs/datasets/loading_datasets.html.
405
+
406
+ # Load pretrained model and tokenizer
407
+ #
408
+ # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
409
+ # download model & vocab.
410
+ if args.config_name:
411
+ config = AutoConfig.from_pretrained(
412
+ args.config_name,
413
+ trust_remote_code=args.trust_remote_code,
414
+ )
415
+ elif args.model_name_or_path:
416
+ config = AutoConfig.from_pretrained(
417
+ args.model_name_or_path,
418
+ trust_remote_code=args.trust_remote_code,
419
+ )
420
+ else:
421
+ config = CONFIG_MAPPING[args.model_type]()
422
+ logger.warning("You are instantiating a new config instance from scratch.")
423
+
424
+ if args.tokenizer_name:
425
+ tokenizer = AutoTokenizer.from_pretrained(
426
+ args.tokenizer_name, use_fast=not args.use_slow_tokenizer, trust_remote_code=args.trust_remote_code
427
+ )
428
+ elif args.model_name_or_path:
429
+ tokenizer = AutoTokenizer.from_pretrained(
430
+ args.model_name_or_path,
431
+ use_fast=not args.use_slow_tokenizer,
432
+ trust_remote_code=args.trust_remote_code,
433
+ )
434
+ else:
435
+ raise ValueError(
436
+ "You are instantiating a new tokenizer from scratch. This is not supported by this script."
437
+ "You can do it from another script, save it, and load it from here, using --tokenizer_name."
438
+ )
439
+
440
+ ##########################
441
+ # Tokenizer #
442
+ ##########################
443
+ tokenizer.pad_token_id = 0 # unk. we want this to be different from the eos token
444
+ tokenizer.padding_side = "left" # Allow batched inference
445
+ tokenizer.truncation_side = "left"
446
+
447
+ if args.model_name_or_path:
448
+ model = AutoModelForCausalLM.from_pretrained(
449
+ args.model_name_or_path,
450
+ from_tf=bool(".ckpt" in args.model_name_or_path),
451
+ config=config,
452
+ low_cpu_mem_usage=True,
453
+ quantization_config=BitsAndBytesConfig(
454
+ load_in_4bit=True,
455
+ bnb_4bit_use_double_quant=False,
456
+ bnb_4bit_quant_type="nf4",
457
+ bnb_4bit_compute_dtype=config.dtype,
458
+ ),
459
+ )
460
+ else:
461
+ logger.info("Training new model from scratch")
462
+ model = AutoModelForCausalLM.from_config(config, trust_remote_code=args.trust_remote_code)
463
+
464
+ ##########################
465
+ # Peft Model #
466
+ ##########################
467
+ if args.adapter_name_or_path is None:
468
+ model = PeftModel.from_pretrained(model, args.model_name_or_path, subfolder="loftq_init", is_trainable=True)
469
+ else:
470
+ model = PeftModel.from_pretrained(model, args.adapter_name_or_path, is_trainable=True)
471
+ model.print_trainable_parameters()
472
+
473
+ # We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch
474
+ # on a small vocab and want a smaller embedding size, remove this test.
475
+ embedding_size = model.get_input_embeddings().weight.shape[0]
476
+ if len(tokenizer) > embedding_size:
477
+ model.resize_token_embeddings(len(tokenizer))
478
+
479
+ # Preprocessing the datasets.
480
+ # First we tokenize all the texts.
481
+ ##########################
482
+ # GSM8K dataset #
483
+ ##########################
484
+
485
+ # Preprocessing the datasets.
486
+ # First we tokenize all the texts.
487
+ column_names = raw_datasets["train"].column_names
488
+
489
+ # Get the column names for source/target.
490
+ source_column, target_column = "question", "answer"
491
+
492
+ # Temporarily set max_target_length for training.
493
+ padding = "max_length" if args.pad_to_max_length else False
494
+ task_prompt = "\nAnswer the above question. First think step by step and then answer the final number.\n"
495
+
496
+ def prompt_process(sent_1, sent_2, prompt_1="", prompt_2="", prompt_3=""):
497
+ sent_2 = sent_2.replace("####", "The final answer is")
498
+ return prompt_1 + sent_1 + prompt_2 + sent_2 + prompt_3
499
+
500
+ def preprocess_function_train(examples):
501
+ sources = examples[source_column]
502
+ targets = examples[target_column]
503
+
504
+ inputs = [prompt_process(source, target, prompt_2=task_prompt) for (source, target) in zip(sources, targets)]
505
+
506
+ model_inputs = tokenizer(
507
+ inputs,
508
+ max_length=args.max_source_length + args.max_target_length,
509
+ padding=padding,
510
+ truncation=True,
511
+ return_tensors="pt",
512
+ )
513
+
514
+ labels = copy.deepcopy(model_inputs)
515
+
516
+ # If we are padding here, replace all tokenizer.pad_token_id in the labels by -100 when we want to ignore
517
+ # padding in the loss.
518
+ if padding == "max_length" and args.ignore_pad_token_for_loss:
519
+ # get the length of the target tokens. -1 to kick out the <BOS> token
520
+ target_tokens = tokenizer(targets, padding=False)
521
+ target_len = [len(label) - 1 for label in target_tokens["input_ids"]]
522
+
523
+ # don't calculate the loss from source and padding (left padding)
524
+ for i in range(len(labels["input_ids"])):
525
+ labels["input_ids"][i, : -target_len[i]] = -100
526
+
527
+ model_inputs["labels"] = labels["input_ids"]
528
+ return model_inputs
529
+
530
+ def preprocess_function_test(examples):
531
+ sources = examples[source_column]
532
+ labels = examples[target_column]
533
+
534
+ inputs = [source + task_prompt for source in sources]
535
+
536
+ model_inputs = tokenizer(inputs, max_length=args.max_source_length, padding=padding, truncation=True)
537
+ labels = tokenizer(labels, max_length=args.max_target_length, padding=padding, truncation=True)
538
+
539
+ model_inputs["labels"] = labels["input_ids"]
540
+
541
+ return model_inputs
542
+
543
+ with accelerator.main_process_first():
544
+ train_dataset = raw_datasets["train"].map(
545
+ preprocess_function_train,
546
+ batched=True,
547
+ num_proc=args.preprocessing_num_workers,
548
+ remove_columns=column_names,
549
+ load_from_cache_file=not args.overwrite_cache,
550
+ desc="Running tokenizer on training dataset",
551
+ )
552
+
553
+ eval_dataset = raw_datasets["test"].map(
554
+ preprocess_function_test,
555
+ batched=True,
556
+ num_proc=args.preprocessing_num_workers,
557
+ remove_columns=column_names,
558
+ load_from_cache_file=not args.overwrite_cache,
559
+ desc="Running tokenizer on test dataset",
560
+ )
561
+
562
+ # Log a few random samples from the set:
563
+ for index in random.sample(range(len(train_dataset)), 2):
564
+ logger.info(f"Sample {index} of the training set: {train_dataset[index]}.")
565
+ for index in random.sample(range(len(eval_dataset)), 2):
566
+ logger.info(f"Sample {index} of the validation set: {eval_dataset[index]}.")
567
+
568
+ # DataLoaders creation:
569
+ train_dataloader = DataLoader(
570
+ train_dataset, shuffle=True, collate_fn=default_data_collator, batch_size=args.per_device_train_batch_size
571
+ )
572
+ eval_dataloader = DataLoader(
573
+ eval_dataset, collate_fn=default_data_collator, batch_size=args.per_device_eval_batch_size
574
+ )
575
+
576
+ # Optimizer
577
+ # Split weights in two groups, one with weight decay and the other not.
578
+ no_decay = ["bias", "layer_norm.weight"]
579
+ optimizer_grouped_parameters = [
580
+ {
581
+ "params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay) and "lora" in n],
582
+ "weight_decay": args.weight_decay,
583
+ },
584
+ {
585
+ "params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)],
586
+ "weight_decay": 0.0,
587
+ },
588
+ ]
589
+ optimizer = torch.optim.AdamW(optimizer_grouped_parameters, lr=args.learning_rate)
590
+
591
+ # Scheduler and math around the number of training steps.
592
+ overrode_max_train_steps = False
593
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
594
+ if args.max_train_steps is None:
595
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
596
+ overrode_max_train_steps = True
597
+
598
+ lr_scheduler = get_scheduler(
599
+ name=args.lr_scheduler_type,
600
+ optimizer=optimizer,
601
+ num_warmup_steps=args.num_warmup_steps * args.gradient_accumulation_steps,
602
+ num_training_steps=args.max_train_steps * args.gradient_accumulation_steps,
603
+ )
604
+
605
+ # Prepare everything with our `accelerator`.
606
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
607
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
608
+ )
609
+
610
+ # On TPU, the tie weights in our model have been disconnected, so we need to restore the ties.
611
+ if accelerator.distributed_type == DistributedType.TPU:
612
+ model.tie_weights()
613
+
614
+ # We need to recalculate our total training steps as the size of the training dataloader may have changed.
615
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
616
+ if overrode_max_train_steps:
617
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
618
+ # Afterwards we recalculate our number of training epochs
619
+ args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
620
+
621
+ # Figure out how many steps we should save the Accelerator states
622
+ checkpointing_steps = args.checkpointing_steps
623
+ if checkpointing_steps is not None and checkpointing_steps.isdigit():
624
+ checkpointing_steps = int(checkpointing_steps)
625
+
626
+ # We need to initialize the trackers we use, and also store our configuration.
627
+ # The trackers initializes automatically on the main process.
628
+ if args.with_tracking:
629
+ experiment_config = vars(args)
630
+ # TensorBoard cannot log Enums, need the raw value
631
+ experiment_config["lr_scheduler_type"] = experiment_config["lr_scheduler_type"].value
632
+ accelerator.init_trackers("clm_no_trainer", experiment_config)
633
+
634
+ # Train!
635
+ total_batch_size = args.per_device_train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
636
+
637
+ logger.info("***** Running training *****")
638
+ logger.info(f" Num examples = {len(train_dataset)}")
639
+ logger.info(f" Num Epochs = {args.num_train_epochs}")
640
+ logger.info(f" Instantaneous batch size per device = {args.per_device_train_batch_size}")
641
+ logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
642
+ logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
643
+ logger.info(f" Total optimization steps = {args.max_train_steps}")
644
+ # Only show the progress bar once on each machine.
645
+ progress_bar = tqdm(range(args.max_train_steps), disable=not accelerator.is_local_main_process)
646
+ completed_steps = 0
647
+ starting_epoch = 0
648
+
649
+ # Potentially load in the weights and states from a previous save
650
+ if args.resume_from_checkpoint:
651
+ if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
652
+ checkpoint_path = args.resume_from_checkpoint
653
+ path = os.path.basename(args.resume_from_checkpoint)
654
+ else:
655
+ # Get the most recent checkpoint
656
+ dirs = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()]
657
+ dirs.sort(key=os.path.getctime)
658
+ path = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last
659
+ checkpoint_path = path
660
+ path = os.path.basename(checkpoint_path)
661
+
662
+ accelerator.print(f"Resumed from checkpoint: {checkpoint_path}")
663
+ accelerator.load_state(path)
664
+ # Extract `epoch_{i}` or `step_{i}`
665
+ training_difference = os.path.splitext(path)[0]
666
+
667
+ if "epoch" in training_difference:
668
+ starting_epoch = int(training_difference.replace("epoch_", "")) + 1
669
+ resume_step = None
670
+ completed_steps = starting_epoch * num_update_steps_per_epoch
671
+ else:
672
+ # need to multiply `gradient_accumulation_steps` to reflect real steps
673
+ resume_step = int(training_difference.replace("step_", "")) * args.gradient_accumulation_steps
674
+ starting_epoch = resume_step // len(train_dataloader)
675
+ resume_step -= starting_epoch * len(train_dataloader)
676
+ completed_steps = resume_step // args.gradient_accumulation_steps
677
+
678
+ # update the progress_bar if load from checkpoint
679
+ progress_bar.update(completed_steps)
680
+
681
+ for epoch in range(starting_epoch, args.num_train_epochs):
682
+ model.train()
683
+ if args.with_tracking:
684
+ total_loss = 0
685
+ if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None:
686
+ # We skip the first `n` batches in the dataloader when resuming from a checkpoint
687
+ active_dataloader = accelerator.skip_first_batches(train_dataloader, resume_step)
688
+ else:
689
+ active_dataloader = train_dataloader
690
+ for step, batch in enumerate(active_dataloader):
691
+ with accelerator.accumulate(model):
692
+ outputs = model(**batch)
693
+ loss = outputs.loss
694
+ # We keep track of the loss at each epoch
695
+ if args.with_tracking:
696
+ total_loss += loss.detach().float()
697
+ accelerator.backward(loss)
698
+ if completed_steps % 50:
699
+ accelerator.print(f"Epoch: {epoch} | Step: {completed_steps} | Loss: {loss}")
700
+ optimizer.step()
701
+ lr_scheduler.step()
702
+ optimizer.zero_grad()
703
+
704
+ # Checks if the accelerator has performed an optimization step behind the scenes
705
+ if accelerator.sync_gradients:
706
+ progress_bar.update(1)
707
+ completed_steps += 1
708
+
709
+ if isinstance(checkpointing_steps, int):
710
+ if completed_steps % checkpointing_steps == 0:
711
+ output_dir = f"step_{completed_steps}"
712
+ if args.output_dir is not None:
713
+ output_dir = os.path.join(args.output_dir, output_dir)
714
+ accelerator.save_state(output_dir)
715
+ if completed_steps >= args.max_train_steps:
716
+ break
717
+
718
+ model.eval()
719
+ gen_kwargs = {
720
+ "max_new_tokens": args.max_target_length,
721
+ "temperature": args.temperature,
722
+ "top_k": args.k,
723
+ "top_p": args.p,
724
+ "do_sample": True,
725
+ }
726
+ ans_pred_list = []
727
+ ans_gold_list = []
728
+ for step, batch in enumerate(eval_dataloader):
729
+ with torch.no_grad():
730
+ gen_kwargs["input_ids"] = batch["input_ids"]
731
+ gen_kwargs["attention_mask"] = batch["attention_mask"]
732
+ generated_tokens = accelerator.unwrap_model(model).generate(**gen_kwargs)
733
+
734
+ pred_tokens = generated_tokens[:, args.max_source_length :]
735
+ pred_tokens = accelerator.pad_across_processes(pred_tokens, dim=1, pad_index=tokenizer.pad_token_id)
736
+ gold_tokens = batch["labels"]
737
+
738
+ if not args.pad_to_max_length:
739
+ # If we did not pad to max length, we need to pad the labels too
740
+ gold_tokens = accelerator.pad_across_processes(
741
+ batch["labels"], dim=1, pad_index=tokenizer.pad_token_id
742
+ )
743
+
744
+ pred_tokens, gold_tokens = accelerator.gather_for_metrics((pred_tokens, gold_tokens))
745
+ pred_tokens, gold_tokens = pred_tokens.cpu().numpy(), gold_tokens.cpu().numpy()
746
+
747
+ if isinstance(pred_tokens, tuple):
748
+ pred_tokens = pred_tokens[0]
749
+ decoded_pred = tokenizer.batch_decode(pred_tokens, skip_special_tokens=True)
750
+ decoded_gold = tokenizer.batch_decode(gold_tokens, skip_special_tokens=True)
751
+
752
+ # Extract the numbers in sentences
753
+ accelerator.print(decoded_pred)
754
+ ans_pred_list += [extract_answer_number(sentence_pred) for sentence_pred in decoded_pred]
755
+ ans_gold_list += [extract_answer_number(sentence_gold) for sentence_gold in decoded_gold]
756
+
757
+ accelerator.print(ans_pred_list)
758
+ accelerator.print(ans_gold_list)
759
+ accuracy = compute_accuracy(ans_gold_list, ans_pred_list)
760
+
761
+ logger.info(f"epoch {epoch}: accuracy: {accuracy}")
762
+
763
+ if args.with_tracking:
764
+ accelerator.log(
765
+ {
766
+ "accuracy": accuracy,
767
+ "train_loss": total_loss.item() / len(train_dataloader),
768
+ "epoch": epoch,
769
+ "step": completed_steps,
770
+ },
771
+ step=completed_steps,
772
+ )
773
+
774
+ if args.push_to_hub and epoch < args.num_train_epochs - 1:
775
+ accelerator.wait_for_everyone()
776
+ unwrapped_model = accelerator.unwrap_model(model)
777
+ unwrapped_model.save_pretrained(
778
+ args.output_dir, is_main_process=accelerator.is_main_process, save_function=accelerator.save
779
+ )
780
+ if accelerator.is_main_process:
781
+ tokenizer.save_pretrained(args.output_dir)
782
+ api.upload_folder(
783
+ repo_id=repo_id,
784
+ folder_path=args.output_dir,
785
+ commit_message=f"Training in progress epoch {epoch}",
786
+ run_as_future=True,
787
+ )
788
+
789
+ if args.checkpointing_steps == "epoch":
790
+ output_dir = f"epoch_{epoch}"
791
+ if args.output_dir is not None:
792
+ output_dir = os.path.join(args.output_dir, output_dir)
793
+ accelerator.save_state(output_dir)
794
+
795
+ if args.with_tracking:
796
+ accelerator.end_training()
797
+
798
+ if args.output_dir is not None:
799
+ accelerator.wait_for_everyone()
800
+ unwrapped_model = accelerator.unwrap_model(model)
801
+ unwrapped_model.save_pretrained(
802
+ args.output_dir, is_main_process=accelerator.is_main_process, save_function=accelerator.save
803
+ )
804
+ if accelerator.is_main_process:
805
+ tokenizer.save_pretrained(args.output_dir)
806
+ if args.push_to_hub:
807
+ api.upload_folder(
808
+ repo_id=repo_id,
809
+ folder_path=args.output_dir,
810
+ commit_message="End of training",
811
+ )
812
+
813
+
814
+ PATTERN_NUMBER = re.compile(r"-?\d+\.?\d*")
815
+
816
+
817
+ def extract_answer_number(sentence: str) -> float:
818
+ sentence = sentence.replace(",", "")
819
+ pred = PATTERN_NUMBER.findall(sentence)
820
+ if not pred:
821
+ return float("inf")
822
+ segment = sentence.split("The final answer is ")
823
+ if len(segment) > 1:
824
+ pred_answer = segment[1]
825
+ pred_answer = PATTERN_NUMBER.findall(pred_answer)
826
+ if len(pred_answer) > 0:
827
+ pred_answer = pred_answer[0]
828
+ else:
829
+ pred_answer = float(pred[-1])
830
+ else:
831
+ pred_answer = float(pred[-1])
832
+
833
+ if isinstance(pred_answer, str):
834
+ try:
835
+ pred_answer = float(pred_answer)
836
+ except ValueError:
837
+ pred_answer = float("inf")
838
+ return pred_answer
839
+
840
+
841
+ def compute_accuracy(pred: list, gold: list):
842
+ acc = 0.0
843
+ for p, g in zip(pred, gold):
844
+ if p == g:
845
+ acc += 1
846
+
847
+ return acc / len(pred)
848
+
849
+
850
+ if __name__ == "__main__":
851
+ main()
tasks/tasksmith-c488fc138ba1/tests/source/examples/lora_dreambooth/colab_notebook.ipynb ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "metadata": {
7
+ "id": "kdOhtpergLCQ"
8
+ },
9
+ "outputs": [],
10
+ "source": [
11
+ "!git clone https://huggingface.co/spaces/smangrul/peft-lora-sd-dreambooth"
12
+ ]
13
+ },
14
+ {
15
+ "cell_type": "code",
16
+ "execution_count": null,
17
+ "metadata": {
18
+ "id": "_LuGk9mihPx7"
19
+ },
20
+ "outputs": [],
21
+ "source": [
22
+ "%cd \"peft-lora-sd-dreambooth\"\n",
23
+ "!pip install -r requirements.txt"
24
+ ]
25
+ },
26
+ {
27
+ "cell_type": "code",
28
+ "execution_count": null,
29
+ "metadata": {
30
+ "id": "BYKO8e5ElJOX"
31
+ },
32
+ "outputs": [],
33
+ "source": [
34
+ "!python colab.py"
35
+ ]
36
+ }
37
+ ],
38
+ "metadata": {
39
+ "accelerator": "GPU",
40
+ "colab": {
41
+ "provenance": []
42
+ },
43
+ "gpuClass": "premium",
44
+ "kernelspec": {
45
+ "display_name": "Python 3",
46
+ "name": "python3"
47
+ },
48
+ "language_info": {
49
+ "name": "python"
50
+ }
51
+ },
52
+ "nbformat": 4,
53
+ "nbformat_minor": 0
54
+ }
tasks/tasksmith-c488fc138ba1/tests/source/examples/lora_dreambooth/convert_kohya_ss_sd_lora_to_peft.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ from collections import Counter
4
+ from dataclasses import dataclass
5
+ from typing import Optional
6
+
7
+ import safetensors
8
+ import torch
9
+ from diffusers import UNet2DConditionModel
10
+ from transformers import CLIPTextModel
11
+
12
+ from peft import LoraConfig, get_peft_model, get_peft_model_state_dict, set_peft_model_state_dict
13
+
14
+
15
+ # Default kohya_ss LoRA replacement modules
16
+ # https://github.com/kohya-ss/sd-scripts/blob/c924c47f374ac1b6e33e71f82948eb1853e2243f/networks/lora.py#L661
17
+ UNET_TARGET_REPLACE_MODULE = ["Transformer2DModel", "Attention"]
18
+ UNET_TARGET_REPLACE_MODULE_CONV2D_3X3 = ["ResnetBlock2D", "Downsample2D", "Upsample2D"]
19
+ TEXT_ENCODER_TARGET_REPLACE_MODULE = ["CLIPAttention", "CLIPMLP"]
20
+ LORA_PREFIX_UNET = "lora_unet"
21
+ LORA_PREFIX_TEXT_ENCODER = "lora_te"
22
+
23
+
24
+ @dataclass
25
+ class LoRAInfo:
26
+ kohya_key: str
27
+ peft_key: str
28
+ alpha: Optional[float] = None
29
+ rank: Optional[int] = None
30
+ lora_A: Optional[torch.Tensor] = None
31
+ lora_B: Optional[torch.Tensor] = None
32
+
33
+ def peft_state_dict(self) -> dict[str, torch.Tensor]:
34
+ if self.lora_A is None or self.lora_B is None:
35
+ raise ValueError("At least one of lora_A or lora_B is None, they must both be provided")
36
+ return {f"{peft_key}.lora_A.weight": self.lora_A, f"{peft_key}.lora_B.weight": self.lora_A}
37
+
38
+
39
+ def construct_peft_loraconfig(info: dict[str, LoRAInfo]) -> LoraConfig:
40
+ """Constructs LoraConfig from data extracted from kohya checkpoint
41
+
42
+ Args:
43
+ info (Dict[str, LoRAInfo]): Information extracted from kohya checkpoint
44
+
45
+ Returns:
46
+ LoraConfig: config for constructing LoRA
47
+ """
48
+
49
+ # Unpack all ranks and alphas
50
+ ranks = {x[0]: x[1].rank for x in info.items()}
51
+ alphas = {x[0]: x[1].alpha or x[1].rank for x in info.items()}
52
+
53
+ # Determine which modules needs to be transformed
54
+ target_modules = list(info.keys())
55
+
56
+ # Determine most common rank and alpha
57
+ r = Counter(ranks.values()).most_common(1)[0]
58
+ lora_alpha = Counter(alphas.values()).most_common(1)[0]
59
+
60
+ # Determine which modules have different rank and alpha
61
+ rank_pattern = dict(filter(lambda x: x[1] != r, ranks.items()))
62
+ alpha_pattern = dict(filter(lambda x: x[1] != lora_alpha, alphas.items()))
63
+
64
+ config = LoraConfig(
65
+ r=r,
66
+ lora_alpha=lora_alpha,
67
+ target_modules=target_modules,
68
+ lora_dropout=0.0,
69
+ bias="none",
70
+ init_lora_weights=False,
71
+ rank_pattern=rank_pattern,
72
+ alpha_pattern=alpha_pattern,
73
+ )
74
+
75
+ return config
76
+
77
+
78
+ def combine_peft_state_dict(info: dict[str, LoRAInfo]) -> dict[str, torch.Tensor]:
79
+ result = {}
80
+ for key_name, key_info in info.items():
81
+ result[f"base_model.model.{key_name}.lora_A.weight"] = key_info.lora_A
82
+ result[f"base_model.model.{key_name}.lora_B.weight"] = key_info.lora_B
83
+ return result
84
+
85
+
86
+ if __name__ == "__main__":
87
+ parser = argparse.ArgumentParser()
88
+
89
+ parser.add_argument("--sd_checkpoint", default=None, type=str, required=True, help="SD checkpoint to use")
90
+
91
+ parser.add_argument(
92
+ "--kohya_lora_path", default=None, type=str, required=True, help="Path to kohya_ss trained LoRA"
93
+ )
94
+
95
+ parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.")
96
+
97
+ parser.add_argument("--half", action="store_true", help="Save weights in half precision.")
98
+ args = parser.parse_args()
99
+
100
+ # Load all models that we need to add adapter to
101
+ text_encoder = CLIPTextModel.from_pretrained(args.sd_checkpoint, subfolder="text_encoder")
102
+ unet = UNet2DConditionModel.from_pretrained(args.sd_checkpoint, subfolder="unet")
103
+
104
+ # Construct possible mapping from kohya keys to peft keys
105
+ models_keys = {}
106
+ for model, model_key, model_name in [
107
+ (text_encoder, LORA_PREFIX_TEXT_ENCODER, "text_encoder"),
108
+ (unet, LORA_PREFIX_UNET, "unet"),
109
+ ]:
110
+ models_keys.update(
111
+ {
112
+ f"{model_key}.{peft_key}".replace(".", "_"): peft_key
113
+ for peft_key in (x[0] for x in model.named_modules())
114
+ }
115
+ )
116
+
117
+ # Store conversion info (model_type -> peft_key -> LoRAInfo)
118
+ lora_info: dict[str, dict[str, LoRAInfo]] = {
119
+ "text_encoder": {},
120
+ "unet": {},
121
+ }
122
+
123
+ # Open kohya_ss checkpoint
124
+ with safetensors.safe_open(args.kohya_lora_path, framework="pt", device="cpu") as f:
125
+ # Extract information about LoRA structure
126
+ metadata = f.metadata()
127
+
128
+ # Iterate through available info and unpack all the values
129
+ for key in f.keys():
130
+ kohya_key, kohya_type = key.split(".")[:2]
131
+
132
+ # Find which model this key belongs to
133
+ if kohya_key.startswith(LORA_PREFIX_TEXT_ENCODER):
134
+ model_type = "text_encoder"
135
+ elif kohya_key.startswith(LORA_PREFIX_UNET):
136
+ model_type = "unet"
137
+ else:
138
+ raise ValueError(f"Cannot determine model for key: {key}")
139
+
140
+ # Find corresponding peft key
141
+ if kohya_key not in models_keys:
142
+ raise ValueError(f"Cannot find corresponding key for diffusers/transformers model: {kohya_key}")
143
+ peft_key = models_keys[kohya_key]
144
+
145
+ if peft_key not in lora_info[model_type]:
146
+ lora_info[model_type][peft_key] = LoRAInfo(kohya_key=kohya_key, peft_key=peft_key)
147
+
148
+ if kohya_type == "alpha":
149
+ lora_info[model_type][peft_key].alpha = f.get_tensor(key).item()
150
+ elif kohya_type == "lora_down":
151
+ tensor = f.get_tensor(key)
152
+ lora_info[model_type][peft_key].lora_A = tensor
153
+ lora_info[model_type][peft_key].rank = tensor.shape[0]
154
+ elif kohya_type == "lora_up":
155
+ tensor = f.get_tensor(key)
156
+ lora_info[model_type][peft_key].lora_B = f.get_tensor(key)
157
+ lora_info[model_type][peft_key].rank = tensor.shape[1]
158
+ else:
159
+ raise ValueError(f"Unknown weight name in key: {key} - {kohya_type}")
160
+
161
+ # Process each model
162
+ for model, model_name in [(text_encoder, "text_encoder"), (unet, "unet")]:
163
+ config = construct_peft_loraconfig(lora_info[model_name])
164
+ model = get_peft_model(model, config)
165
+
166
+ keys_peft = list(get_peft_model_state_dict(model).keys())
167
+ keys_new = list(combine_peft_state_dict(lora_info[model_name]).keys())
168
+
169
+ set_peft_model_state_dict(model, combine_peft_state_dict(lora_info[model_name]))
170
+
171
+ if args.half:
172
+ model.to(torch.float16)
173
+
174
+ # Save model to disk
175
+ model.save_pretrained(os.path.join(args.dump_path, model_name))
tasks/tasksmith-c488fc138ba1/tests/source/examples/lora_dreambooth/convert_peft_sd_lora_to_kohya_ss.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+
4
+ import torch
5
+ from diffusers import UNet2DConditionModel
6
+ from safetensors.torch import save_file
7
+ from transformers import CLIPTextModel
8
+
9
+ from peft import PeftModel, get_peft_model_state_dict
10
+
11
+
12
+ # Default kohya_ss LoRA replacement modules
13
+ # https://github.com/kohya-ss/sd-scripts/blob/c924c47f374ac1b6e33e71f82948eb1853e2243f/networks/lora.py#L664
14
+ LORA_PREFIX_UNET = "lora_unet"
15
+ LORA_PREFIX_TEXT_ENCODER = "lora_te"
16
+ LORA_ADAPTER_NAME = "default"
17
+
18
+
19
+ def get_module_kohya_state_dict(
20
+ module: PeftModel, prefix: str, dtype: torch.dtype, adapter_name: str = LORA_ADAPTER_NAME
21
+ ) -> dict[str, torch.Tensor]:
22
+ kohya_ss_state_dict = {}
23
+ for peft_key, weight in get_peft_model_state_dict(module, adapter_name=adapter_name).items():
24
+ kohya_key = peft_key.replace("base_model.model", prefix)
25
+ kohya_key = kohya_key.replace("lora_A", "lora_down")
26
+ kohya_key = kohya_key.replace("lora_B", "lora_up")
27
+ kohya_key = kohya_key.replace(".", "_", kohya_key.count(".") - 2)
28
+ kohya_ss_state_dict[kohya_key] = weight.to(dtype)
29
+
30
+ # Set alpha parameter
31
+ if "lora_down" in kohya_key:
32
+ alpha_key = f"{kohya_key.split('.')[0]}.alpha"
33
+ kohya_ss_state_dict[alpha_key] = torch.tensor(module.peft_config[adapter_name].lora_alpha).to(dtype)
34
+
35
+ return kohya_ss_state_dict
36
+
37
+
38
+ if __name__ == "__main__":
39
+ parser = argparse.ArgumentParser()
40
+
41
+ parser.add_argument(
42
+ "--sd_checkpoint",
43
+ default=None,
44
+ type=str,
45
+ required=True,
46
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
47
+ )
48
+
49
+ parser.add_argument(
50
+ "--sd_checkpoint_revision",
51
+ type=str,
52
+ default=None,
53
+ required=False,
54
+ help="Revision of pretrained model identifier from huggingface.co/models.",
55
+ )
56
+
57
+ parser.add_argument("--peft_lora_path", default=None, type=str, required=True, help="Path to peft trained LoRA")
58
+
59
+ parser.add_argument(
60
+ "--dump_path",
61
+ default=None,
62
+ type=str,
63
+ required=True,
64
+ help="Path to the output safetensors file for use with webui.",
65
+ )
66
+
67
+ parser.add_argument("--half", action="store_true", help="Save weights in half precision.")
68
+ args = parser.parse_args()
69
+
70
+ # Store kohya_ss state dict
71
+ kohya_ss_state_dict = {}
72
+ dtype = torch.float16 if args.half else torch.float32
73
+
74
+ # Load Text Encoder LoRA model
75
+ text_encoder_peft_lora_path = os.path.join(args.peft_lora_path, "text_encoder")
76
+ if os.path.exists(text_encoder_peft_lora_path):
77
+ text_encoder = CLIPTextModel.from_pretrained(
78
+ args.sd_checkpoint, subfolder="text_encoder", revision=args.sd_checkpoint_revision
79
+ )
80
+ text_encoder = PeftModel.from_pretrained(
81
+ text_encoder, text_encoder_peft_lora_path, adapter_name=LORA_ADAPTER_NAME
82
+ )
83
+ kohya_ss_state_dict.update(
84
+ get_module_kohya_state_dict(text_encoder, LORA_PREFIX_TEXT_ENCODER, dtype, LORA_ADAPTER_NAME)
85
+ )
86
+
87
+ # Load UNet LoRA model
88
+ unet_peft_lora_path = os.path.join(args.peft_lora_path, "unet")
89
+ if os.path.exists(unet_peft_lora_path):
90
+ unet = UNet2DConditionModel.from_pretrained(
91
+ args.sd_checkpoint, subfolder="unet", revision=args.sd_checkpoint_revision
92
+ )
93
+ unet = PeftModel.from_pretrained(unet, unet_peft_lora_path, adapter_name=LORA_ADAPTER_NAME)
94
+ kohya_ss_state_dict.update(get_module_kohya_state_dict(unet, LORA_PREFIX_UNET, dtype, LORA_ADAPTER_NAME))
95
+
96
+ # Save state dict
97
+ save_file(
98
+ kohya_ss_state_dict,
99
+ args.dump_path,
100
+ )
tasks/tasksmith-c488fc138ba1/tests/source/examples/lora_dreambooth/lora_dreambooth_inference.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
tasks/tasksmith-c488fc138ba1/tests/source/examples/lora_dreambooth/requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ transformers
2
+ accelerate
3
+ evaluate
4
+ tqdm
5
+ datasets
6
+ diffusers
7
+ Pillow
8
+ torchvision
9
+ huggingface_hub
10
+ safetensors
11
+ wandb
tasks/tasksmith-c488fc138ba1/tests/source/examples/lora_dreambooth/train_dreambooth.py ADDED
@@ -0,0 +1,1107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 contextlib import nullcontext
11
+ from pathlib import Path
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 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 = ["to_q", "to_v", "query", "value"] # , "ff.net.0.proj"]
50
+ TEXT_ENCODER_TARGET_MODULES = ["q_proj", "v_proj"]
51
+
52
+
53
+ def import_model_class_from_model_name_or_path(pretrained_model_name_or_path: str, revision: str):
54
+ text_encoder_config = PretrainedConfig.from_pretrained(
55
+ pretrained_model_name_or_path,
56
+ subfolder="text_encoder",
57
+ revision=revision,
58
+ )
59
+ model_class = text_encoder_config.architectures[0]
60
+
61
+ if model_class == "CLIPTextModel":
62
+ from transformers import CLIPTextModel
63
+
64
+ return CLIPTextModel
65
+ elif model_class == "RobertaSeriesModelWithTransformation":
66
+ from diffusers.pipelines.alt_diffusion.modeling_roberta_series import RobertaSeriesModelWithTransformation
67
+
68
+ return RobertaSeriesModelWithTransformation
69
+ else:
70
+ raise ValueError(f"{model_class} is not supported.")
71
+
72
+
73
+ def parse_args(input_args=None):
74
+ parser = argparse.ArgumentParser(description="Simple example of a training script.")
75
+ parser.add_argument(
76
+ "--pretrained_model_name_or_path",
77
+ type=str,
78
+ default=None,
79
+ required=True,
80
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
81
+ )
82
+ parser.add_argument(
83
+ "--revision",
84
+ type=str,
85
+ default=None,
86
+ required=False,
87
+ help="Revision of pretrained model identifier from huggingface.co/models.",
88
+ )
89
+ parser.add_argument(
90
+ "--tokenizer_name",
91
+ type=str,
92
+ default=None,
93
+ help="Pretrained tokenizer name or path if not the same as model_name",
94
+ )
95
+ parser.add_argument(
96
+ "--instance_data_dir",
97
+ type=str,
98
+ default=None,
99
+ required=True,
100
+ help="A folder containing the training data of instance images.",
101
+ )
102
+ parser.add_argument(
103
+ "--class_data_dir",
104
+ type=str,
105
+ default=None,
106
+ required=False,
107
+ help="A folder containing the training data of class images.",
108
+ )
109
+ parser.add_argument(
110
+ "--instance_prompt",
111
+ type=str,
112
+ default=None,
113
+ required=True,
114
+ help="The prompt with identifier specifying the instance",
115
+ )
116
+ parser.add_argument(
117
+ "--class_prompt",
118
+ type=str,
119
+ default=None,
120
+ help="The prompt to specify images in the same class as provided instance images.",
121
+ )
122
+ parser.add_argument(
123
+ "--with_prior_preservation",
124
+ default=False,
125
+ action="store_true",
126
+ help="Flag to add prior preservation loss.",
127
+ )
128
+ parser.add_argument("--prior_loss_weight", type=float, default=1.0, help="The weight of prior preservation loss.")
129
+ parser.add_argument(
130
+ "--num_class_images",
131
+ type=int,
132
+ default=100,
133
+ help=(
134
+ "Minimal class images for prior preservation loss. If there are not enough images already present in"
135
+ " class_data_dir, additional images will be sampled with class_prompt."
136
+ ),
137
+ )
138
+ parser.add_argument(
139
+ "--validation_prompt",
140
+ type=str,
141
+ default=None,
142
+ help="A prompt that is used during validation to verify that the model is learning.",
143
+ )
144
+ parser.add_argument(
145
+ "--num_validation_images",
146
+ type=int,
147
+ default=4,
148
+ help="Number of images that should be generated during validation with `validation_prompt`.",
149
+ )
150
+ parser.add_argument(
151
+ "--validation_steps",
152
+ type=int,
153
+ default=100,
154
+ help=(
155
+ "Run dreambooth validation every X steps. Dreambooth validation consists of running the prompt"
156
+ " `args.validation_prompt` multiple times: `args.num_validation_images`."
157
+ ),
158
+ )
159
+ parser.add_argument(
160
+ "--output_dir",
161
+ type=str,
162
+ default="text-inversion-model",
163
+ help="The output directory where the model predictions and checkpoints will be written.",
164
+ )
165
+ parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
166
+ parser.add_argument(
167
+ "--resolution",
168
+ type=int,
169
+ default=512,
170
+ help=(
171
+ "The resolution for input images, all the images in the train/validation dataset will be resized to this"
172
+ " resolution"
173
+ ),
174
+ )
175
+ parser.add_argument(
176
+ "--center_crop", action="store_true", help="Whether to center crop images before resizing to resolution"
177
+ )
178
+ parser.add_argument("--train_text_encoder", action="store_true", help="Whether to train the text encoder")
179
+
180
+ # lora args
181
+ parser.add_argument("--use_lora", action="store_true", help="Whether to use Lora for parameter efficient tuning")
182
+ parser.add_argument("--lora_r", type=int, default=8, help="Lora rank, only used if use_lora is True")
183
+ parser.add_argument("--lora_alpha", type=int, default=32, help="Lora alpha, only used if use_lora is True")
184
+ parser.add_argument("--lora_dropout", type=float, default=0.0, help="Lora dropout, only used if use_lora is True")
185
+ parser.add_argument(
186
+ "--lora_bias",
187
+ type=str,
188
+ default="none",
189
+ help="Bias type for Lora. Can be 'none', 'all' or 'lora_only', only used if use_lora is True",
190
+ )
191
+ parser.add_argument(
192
+ "--lora_text_encoder_r",
193
+ type=int,
194
+ default=8,
195
+ help="Lora rank for text encoder, only used if `use_lora` and `train_text_encoder` are True",
196
+ )
197
+ parser.add_argument(
198
+ "--lora_text_encoder_alpha",
199
+ type=int,
200
+ default=32,
201
+ help="Lora alpha for text encoder, only used if `use_lora` and `train_text_encoder` are True",
202
+ )
203
+ parser.add_argument(
204
+ "--lora_text_encoder_dropout",
205
+ type=float,
206
+ default=0.0,
207
+ help="Lora dropout for text encoder, only used if `use_lora` and `train_text_encoder` are True",
208
+ )
209
+ parser.add_argument(
210
+ "--lora_text_encoder_bias",
211
+ type=str,
212
+ default="none",
213
+ help="Bias type for Lora. Can be 'none', 'all' or 'lora_only', only used if use_lora and `train_text_encoder` are True",
214
+ )
215
+
216
+ parser.add_argument(
217
+ "--num_dataloader_workers", type=int, default=1, help="Num of workers for the training dataloader."
218
+ )
219
+
220
+ parser.add_argument(
221
+ "--no_tracemalloc",
222
+ default=False,
223
+ action="store_true",
224
+ help="Flag to stop memory allocation tracing during training. This could speed up training on Windows.",
225
+ )
226
+
227
+ parser.add_argument(
228
+ "--train_batch_size", type=int, default=4, help="Batch size (per device) for the training dataloader."
229
+ )
230
+ parser.add_argument(
231
+ "--sample_batch_size", type=int, default=4, help="Batch size (per device) for sampling images."
232
+ )
233
+ parser.add_argument("--num_train_epochs", type=int, default=1)
234
+ parser.add_argument(
235
+ "--max_train_steps",
236
+ type=int,
237
+ default=None,
238
+ help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
239
+ )
240
+ parser.add_argument(
241
+ "--checkpointing_steps",
242
+ type=int,
243
+ default=500,
244
+ help=(
245
+ "Save a checkpoint of the training state every X updates. These checkpoints can be used both as final"
246
+ " checkpoints in case they are better than the last checkpoint, and are also suitable for resuming"
247
+ " training using `--resume_from_checkpoint`."
248
+ ),
249
+ )
250
+ parser.add_argument(
251
+ "--resume_from_checkpoint",
252
+ type=str,
253
+ default=None,
254
+ help=(
255
+ "Whether training should be resumed from a previous checkpoint. Use a path saved by"
256
+ ' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
257
+ ),
258
+ )
259
+ parser.add_argument(
260
+ "--gradient_accumulation_steps",
261
+ type=int,
262
+ default=1,
263
+ help="Number of updates steps to accumulate before performing a backward/update pass.",
264
+ )
265
+ parser.add_argument(
266
+ "--gradient_checkpointing",
267
+ action="store_true",
268
+ help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
269
+ )
270
+ parser.add_argument(
271
+ "--learning_rate",
272
+ type=float,
273
+ default=5e-6,
274
+ help="Initial learning rate (after the potential warmup period) to use.",
275
+ )
276
+ parser.add_argument(
277
+ "--scale_lr",
278
+ action="store_true",
279
+ default=False,
280
+ help="Scale the learning rate by the number of accelerators, gradient accumulation steps, and batch size.",
281
+ )
282
+ parser.add_argument(
283
+ "--lr_scheduler",
284
+ type=str,
285
+ default="constant",
286
+ help=(
287
+ 'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
288
+ ' "constant", "constant_with_warmup"]'
289
+ ),
290
+ )
291
+ parser.add_argument(
292
+ "--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
293
+ )
294
+ parser.add_argument(
295
+ "--lr_num_cycles",
296
+ type=int,
297
+ default=1,
298
+ help="Number of hard resets of the lr in cosine_with_restarts scheduler.",
299
+ )
300
+ parser.add_argument("--lr_power", type=float, default=1.0, help="Power factor of the polynomial scheduler.")
301
+ parser.add_argument(
302
+ "--use_8bit_adam", action="store_true", help="Whether or not to use 8-bit Adam from bitsandbytes."
303
+ )
304
+ parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
305
+ parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
306
+ parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
307
+ parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
308
+ parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
309
+ parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
310
+ parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
311
+ parser.add_argument(
312
+ "--hub_model_id",
313
+ type=str,
314
+ default=None,
315
+ help="The name of the repository to keep in sync with the local `output_dir`.",
316
+ )
317
+ parser.add_argument(
318
+ "--logging_dir",
319
+ type=str,
320
+ default="logs",
321
+ help=(
322
+ "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
323
+ " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
324
+ ),
325
+ )
326
+ parser.add_argument(
327
+ "--allow_tf32",
328
+ action="store_true",
329
+ help=(
330
+ "Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
331
+ " https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
332
+ ),
333
+ )
334
+ parser.add_argument(
335
+ "--report_to",
336
+ type=str,
337
+ default="tensorboard",
338
+ help=(
339
+ 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
340
+ ' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
341
+ ),
342
+ )
343
+ parser.add_argument(
344
+ "--wandb_key",
345
+ type=str,
346
+ default=None,
347
+ help=("If report to option is set to wandb, api-key for wandb used for login to wandb "),
348
+ )
349
+ parser.add_argument(
350
+ "--wandb_project_name",
351
+ type=str,
352
+ default=None,
353
+ help=("If report to option is set to wandb, project name in wandb for log tracking "),
354
+ )
355
+ parser.add_argument(
356
+ "--mixed_precision",
357
+ type=str,
358
+ default=None,
359
+ choices=["no", "fp16", "bf16"],
360
+ help=(
361
+ "Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
362
+ " 1.10.and an Nvidia Ampere GPU or Intel XPU. Default to the value of accelerate config of the current system or the"
363
+ " flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
364
+ ),
365
+ )
366
+ parser.add_argument(
367
+ "--prior_generation_precision",
368
+ type=str,
369
+ default=None,
370
+ choices=["no", "fp32", "fp16", "bf16"],
371
+ help=(
372
+ "Choose prior generation precision between fp32, fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
373
+ " 1.10.and an Nvidia Ampere GPU or Intel XPU. Default to fp16 if a GPU is available else fp32."
374
+ ),
375
+ )
376
+ parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
377
+ parser.add_argument(
378
+ "--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
379
+ )
380
+
381
+ if input_args is not None:
382
+ args = parser.parse_args(input_args)
383
+ else:
384
+ args = parser.parse_args()
385
+
386
+ env_local_rank = int(os.environ.get("LOCAL_RANK", "-1"))
387
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
388
+ args.local_rank = env_local_rank
389
+
390
+ if args.with_prior_preservation:
391
+ if args.class_data_dir is None:
392
+ raise ValueError("You must specify a data directory for class images.")
393
+ if args.class_prompt is None:
394
+ raise ValueError("You must specify prompt for class images.")
395
+ else:
396
+ # logger is not available yet
397
+ if args.class_data_dir is not None:
398
+ warnings.warn("You need not use --class_data_dir without --with_prior_preservation.")
399
+ if args.class_prompt is not None:
400
+ warnings.warn("You need not use --class_prompt without --with_prior_preservation.")
401
+
402
+ return args
403
+
404
+
405
+ # Converting Bytes to Megabytes
406
+ def b2mb(x):
407
+ return int(x / 2**20)
408
+
409
+
410
+ # This context manager is used to track the peak memory usage of the process
411
+ class TorchTracemalloc:
412
+ def __enter__(self):
413
+ gc.collect()
414
+ self.device_type = torch.accelerator.current_accelerator().type if hasattr(torch, "accelerator") else "cuda"
415
+ self.device_module = getattr(torch, self.device_type, torch.cuda)
416
+ self.device_module.empty_cache()
417
+ self.device_module.reset_peak_memory_stats() # reset the peak gauge to zero
418
+ self.begin = self.device_module.memory_allocated()
419
+ self.process = psutil.Process()
420
+
421
+ self.cpu_begin = self.cpu_mem_used()
422
+ self.peak_monitoring = True
423
+ peak_monitor_thread = threading.Thread(target=self.peak_monitor_func)
424
+ peak_monitor_thread.daemon = True
425
+ peak_monitor_thread.start()
426
+ return self
427
+
428
+ def cpu_mem_used(self):
429
+ """get resident set size memory for the current process"""
430
+ return self.process.memory_info().rss
431
+
432
+ def peak_monitor_func(self):
433
+ self.cpu_peak = -1
434
+
435
+ while True:
436
+ self.cpu_peak = max(self.cpu_mem_used(), self.cpu_peak)
437
+
438
+ # can't sleep or will not catch the peak right (this comment is here on purpose)
439
+ # time.sleep(0.001) # 1msec
440
+
441
+ if not self.peak_monitoring:
442
+ break
443
+
444
+ def __exit__(self, *exc):
445
+ self.peak_monitoring = False
446
+
447
+ gc.collect()
448
+ self.device_module.empty_cache()
449
+ self.end = self.device_module.memory_allocated()
450
+ self.peak = self.device_module.max_memory_allocated()
451
+ self.used = b2mb(self.end - self.begin)
452
+ self.peaked = b2mb(self.peak - self.begin)
453
+
454
+ self.cpu_end = self.cpu_mem_used()
455
+ self.cpu_used = b2mb(self.cpu_end - self.cpu_begin)
456
+ self.cpu_peaked = b2mb(self.cpu_peak - self.cpu_begin)
457
+ # print(f"delta used/peak {self.used:4d}/{self.peaked:4d}")
458
+
459
+
460
+ class DreamBoothDataset(Dataset):
461
+ """
462
+ A dataset to prepare the instance and class images with the prompts for fine-tuning the model.
463
+ It pre-processes the images and the tokenizes prompts.
464
+ """
465
+
466
+ def __init__(
467
+ self,
468
+ instance_data_root,
469
+ instance_prompt,
470
+ tokenizer,
471
+ class_data_root=None,
472
+ class_prompt=None,
473
+ size=512,
474
+ center_crop=False,
475
+ ):
476
+ self.size = size
477
+ self.center_crop = center_crop
478
+ self.tokenizer = tokenizer
479
+
480
+ self.instance_data_root = Path(instance_data_root)
481
+ if not self.instance_data_root.exists():
482
+ raise ValueError("Instance images root doesn't exists.")
483
+
484
+ self.instance_images_path = list(Path(instance_data_root).iterdir())
485
+ self.num_instance_images = len(self.instance_images_path)
486
+ self.instance_prompt = instance_prompt
487
+ self._length = self.num_instance_images
488
+
489
+ if class_data_root is not None:
490
+ self.class_data_root = Path(class_data_root)
491
+ self.class_data_root.mkdir(parents=True, exist_ok=True)
492
+ self.class_images_path = list(self.class_data_root.iterdir())
493
+ self.num_class_images = len(self.class_images_path)
494
+ self._length = max(self.num_class_images, self.num_instance_images)
495
+ self.class_prompt = class_prompt
496
+ else:
497
+ self.class_data_root = None
498
+
499
+ self.image_transforms = transforms.Compose(
500
+ [
501
+ transforms.Resize(size, interpolation=transforms.InterpolationMode.BILINEAR),
502
+ transforms.CenterCrop(size) if center_crop else transforms.RandomCrop(size),
503
+ transforms.ToTensor(),
504
+ transforms.Normalize([0.5], [0.5]),
505
+ ]
506
+ )
507
+
508
+ def __len__(self):
509
+ return self._length
510
+
511
+ def __getitem__(self, index):
512
+ example = {}
513
+ instance_image = Image.open(self.instance_images_path[index % self.num_instance_images])
514
+ if instance_image.mode != "RGB":
515
+ instance_image = instance_image.convert("RGB")
516
+ example["instance_images"] = self.image_transforms(instance_image)
517
+ example["instance_prompt_ids"] = self.tokenizer(
518
+ self.instance_prompt,
519
+ truncation=True,
520
+ padding="max_length",
521
+ max_length=self.tokenizer.model_max_length,
522
+ return_tensors="pt",
523
+ ).input_ids
524
+
525
+ if self.class_data_root:
526
+ class_image = Image.open(self.class_images_path[index % self.num_class_images])
527
+ if class_image.mode != "RGB":
528
+ class_image = class_image.convert("RGB")
529
+ example["class_images"] = self.image_transforms(class_image)
530
+ example["class_prompt_ids"] = self.tokenizer(
531
+ self.class_prompt,
532
+ truncation=True,
533
+ padding="max_length",
534
+ max_length=self.tokenizer.model_max_length,
535
+ return_tensors="pt",
536
+ ).input_ids
537
+
538
+ return example
539
+
540
+
541
+ def collate_fn(examples, with_prior_preservation=False):
542
+ input_ids = [example["instance_prompt_ids"] for example in examples]
543
+ pixel_values = [example["instance_images"] for example in examples]
544
+
545
+ # Concat class and instance examples for prior preservation.
546
+ # We do this to avoid doing two forward passes.
547
+ if with_prior_preservation:
548
+ input_ids += [example["class_prompt_ids"] for example in examples]
549
+ pixel_values += [example["class_images"] for example in examples]
550
+
551
+ pixel_values = torch.stack(pixel_values)
552
+ pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float()
553
+
554
+ input_ids = torch.cat(input_ids, dim=0)
555
+
556
+ batch = {
557
+ "input_ids": input_ids,
558
+ "pixel_values": pixel_values,
559
+ }
560
+ return batch
561
+
562
+
563
+ class PromptDataset(Dataset):
564
+ "A simple dataset to prepare the prompts to generate class images on multiple accelerators."
565
+
566
+ def __init__(self, prompt, num_samples):
567
+ self.prompt = prompt
568
+ self.num_samples = num_samples
569
+
570
+ def __len__(self):
571
+ return self.num_samples
572
+
573
+ def __getitem__(self, index):
574
+ example = {}
575
+ example["prompt"] = self.prompt
576
+ example["index"] = index
577
+ return example
578
+
579
+
580
+ def main(args):
581
+ logging_dir = Path(args.output_dir, args.logging_dir)
582
+
583
+ accelerator = Accelerator(
584
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
585
+ mixed_precision=args.mixed_precision,
586
+ log_with=args.report_to,
587
+ project_dir=logging_dir,
588
+ )
589
+ if args.report_to == "wandb":
590
+ import wandb
591
+
592
+ wandb.login(key=args.wandb_key)
593
+ wandb.init(project=args.wandb_project_name)
594
+ # Currently, it's not possible to do gradient accumulation when training two models with accelerate.accumulate
595
+ # This will be enabled soon in accelerate. For now, we don't allow gradient accumulation when training two models.
596
+ # TODO (patil-suraj): Remove this check when gradient accumulation with two models is enabled in accelerate.
597
+ if args.train_text_encoder and args.gradient_accumulation_steps > 1 and accelerator.num_processes > 1:
598
+ raise ValueError(
599
+ "Gradient accumulation is not supported when training the text encoder in distributed training. "
600
+ "Please set gradient_accumulation_steps to 1. This feature will be supported in the future."
601
+ )
602
+
603
+ # Make one log on every process with the configuration for debugging.
604
+ logging.basicConfig(
605
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
606
+ datefmt="%m/%d/%Y %H:%M:%S",
607
+ level=logging.INFO,
608
+ )
609
+ logger.info(accelerator.state, main_process_only=False)
610
+ if accelerator.is_local_main_process:
611
+ datasets.utils.logging.set_verbosity_warning()
612
+ transformers.utils.logging.set_verbosity_warning()
613
+ diffusers.utils.logging.set_verbosity_info()
614
+ else:
615
+ datasets.utils.logging.set_verbosity_error()
616
+ transformers.utils.logging.set_verbosity_error()
617
+ diffusers.utils.logging.set_verbosity_error()
618
+
619
+ # If passed along, set the training seed now.
620
+ if args.seed is not None:
621
+ set_seed(args.seed)
622
+
623
+ # Generate class images if prior preservation is enabled.
624
+ if args.with_prior_preservation:
625
+ class_images_dir = Path(args.class_data_dir)
626
+ if not class_images_dir.exists():
627
+ class_images_dir.mkdir(parents=True)
628
+ cur_class_images = len(list(class_images_dir.iterdir()))
629
+
630
+ if cur_class_images < args.num_class_images:
631
+ dtype = torch.float16 if accelerator.device.type in ["cuda", "xpu"] else torch.float32
632
+ if args.prior_generation_precision == "fp32":
633
+ dtype = torch.float32
634
+ elif args.prior_generation_precision == "fp16":
635
+ dtype = torch.float16
636
+ elif args.prior_generation_precision == "bf16":
637
+ dtype = torch.bfloat16
638
+ pipeline = DiffusionPipeline.from_pretrained(
639
+ args.pretrained_model_name_or_path,
640
+ dtype=dtype,
641
+ safety_checker=None,
642
+ revision=args.revision,
643
+ )
644
+ pipeline.set_progress_bar_config(disable=True)
645
+
646
+ num_new_images = args.num_class_images - cur_class_images
647
+ logger.info(f"Number of class images to sample: {num_new_images}.")
648
+
649
+ sample_dataset = PromptDataset(args.class_prompt, num_new_images)
650
+ sample_dataloader = torch.utils.data.DataLoader(sample_dataset, batch_size=args.sample_batch_size)
651
+
652
+ sample_dataloader = accelerator.prepare(sample_dataloader)
653
+ pipeline.to(accelerator.device)
654
+
655
+ for example in tqdm(
656
+ sample_dataloader, desc="Generating class images", disable=not accelerator.is_local_main_process
657
+ ):
658
+ images = pipeline(example["prompt"]).images
659
+
660
+ for i, image in enumerate(images):
661
+ hash_image = hashlib.sha1(image.tobytes()).hexdigest()
662
+ image_filename = class_images_dir / f"{example['index'][i] + cur_class_images}-{hash_image}.jpg"
663
+ image.save(image_filename)
664
+
665
+ del pipeline
666
+ if torch.cuda.is_available():
667
+ torch.cuda.empty_cache()
668
+ elif torch.xpu.is_available():
669
+ torch.xpu.empty_cache()
670
+
671
+ # Handle the repository creation
672
+ if accelerator.is_main_process:
673
+ if args.push_to_hub:
674
+ api = HfApi(token=args.hub_token)
675
+
676
+ # Create repo (repo_name from args or inferred)
677
+ repo_name = args.hub_model_id
678
+ if repo_name is None:
679
+ repo_name = Path(args.output_dir).absolute().name
680
+ repo_id = api.create_repo(repo_name, exist_ok=True).repo_id
681
+
682
+ with open(os.path.join(args.output_dir, ".gitignore"), "w+") as gitignore:
683
+ if "step_*" not in gitignore:
684
+ gitignore.write("step_*\n")
685
+ if "epoch_*" not in gitignore:
686
+ gitignore.write("epoch_*\n")
687
+ elif args.output_dir is not None:
688
+ os.makedirs(args.output_dir, exist_ok=True)
689
+
690
+ # Load the tokenizer
691
+ if args.tokenizer_name:
692
+ tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name, revision=args.revision, use_fast=False)
693
+ elif args.pretrained_model_name_or_path:
694
+ tokenizer = AutoTokenizer.from_pretrained(
695
+ args.pretrained_model_name_or_path,
696
+ subfolder="tokenizer",
697
+ revision=args.revision,
698
+ use_fast=False,
699
+ )
700
+
701
+ # import correct text encoder class
702
+ text_encoder_cls = import_model_class_from_model_name_or_path(args.pretrained_model_name_or_path, args.revision)
703
+
704
+ # Load scheduler and models
705
+ noise_scheduler = DDPMScheduler(
706
+ beta_start=0.00085,
707
+ beta_end=0.012,
708
+ beta_schedule="scaled_linear",
709
+ num_train_timesteps=1000,
710
+ ) # DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
711
+ text_encoder = text_encoder_cls.from_pretrained(
712
+ args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision
713
+ )
714
+ vae = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae", revision=args.revision)
715
+ unet = UNet2DConditionModel.from_pretrained(
716
+ args.pretrained_model_name_or_path, subfolder="unet", revision=args.revision
717
+ )
718
+
719
+ if args.use_lora:
720
+ config = LoraConfig(
721
+ r=args.lora_r,
722
+ lora_alpha=args.lora_alpha,
723
+ target_modules=UNET_TARGET_MODULES,
724
+ lora_dropout=args.lora_dropout,
725
+ bias=args.lora_bias,
726
+ )
727
+ unet = get_peft_model(unet, config)
728
+ unet.print_trainable_parameters()
729
+ print(unet)
730
+
731
+ vae.requires_grad_(False)
732
+ if not args.train_text_encoder:
733
+ text_encoder.requires_grad_(False)
734
+ elif args.train_text_encoder and args.use_lora:
735
+ config = LoraConfig(
736
+ r=args.lora_text_encoder_r,
737
+ lora_alpha=args.lora_text_encoder_alpha,
738
+ target_modules=TEXT_ENCODER_TARGET_MODULES,
739
+ lora_dropout=args.lora_text_encoder_dropout,
740
+ bias=args.lora_text_encoder_bias,
741
+ )
742
+ text_encoder = get_peft_model(text_encoder, config)
743
+ text_encoder.print_trainable_parameters()
744
+ print(text_encoder)
745
+
746
+ if args.enable_xformers_memory_efficient_attention:
747
+ if accelerator.device.type == "xpu":
748
+ logger.warning("XPU hasn't support xformers yet, ignore it.")
749
+ elif is_xformers_available():
750
+ unet.enable_xformers_memory_efficient_attention()
751
+ else:
752
+ raise ValueError("xformers is not available. Make sure it is installed correctly")
753
+
754
+ if args.gradient_checkpointing:
755
+ unet.enable_gradient_checkpointing()
756
+ # below fails when using lora so commenting it out
757
+ if args.train_text_encoder and not args.use_lora:
758
+ text_encoder.gradient_checkpointing_enable()
759
+
760
+ # Enable TF32 for faster training on Ampere GPUs,
761
+ # cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
762
+ if args.allow_tf32 and torch.cuda.is_available():
763
+ torch.backends.cuda.matmul.allow_tf32 = True
764
+
765
+ if args.scale_lr:
766
+ args.learning_rate = (
767
+ args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
768
+ )
769
+
770
+ # Use 8-bit Adam for lower memory usage or to fine-tune the model in 16GB accelerators
771
+ if args.use_8bit_adam:
772
+ try:
773
+ import bitsandbytes as bnb
774
+ except ImportError:
775
+ raise ImportError(
776
+ "To use 8-bit Adam, please install the bitsandbytes library: `pip install bitsandbytes`."
777
+ )
778
+
779
+ optimizer_class = bnb.optim.AdamW8bit
780
+ else:
781
+ optimizer_class = torch.optim.AdamW
782
+
783
+ # Optimizer creation
784
+ params_to_optimize = (
785
+ itertools.chain(unet.parameters(), text_encoder.parameters()) if args.train_text_encoder else unet.parameters()
786
+ )
787
+ optimizer = optimizer_class(
788
+ params_to_optimize,
789
+ lr=args.learning_rate,
790
+ betas=(args.adam_beta1, args.adam_beta2),
791
+ weight_decay=args.adam_weight_decay,
792
+ eps=args.adam_epsilon,
793
+ )
794
+
795
+ # Dataset and DataLoaders creation:
796
+ train_dataset = DreamBoothDataset(
797
+ instance_data_root=args.instance_data_dir,
798
+ instance_prompt=args.instance_prompt,
799
+ class_data_root=args.class_data_dir if args.with_prior_preservation else None,
800
+ class_prompt=args.class_prompt,
801
+ tokenizer=tokenizer,
802
+ size=args.resolution,
803
+ center_crop=args.center_crop,
804
+ )
805
+
806
+ train_dataloader = torch.utils.data.DataLoader(
807
+ train_dataset,
808
+ batch_size=args.train_batch_size,
809
+ shuffle=True,
810
+ collate_fn=lambda examples: collate_fn(examples, args.with_prior_preservation),
811
+ num_workers=args.num_dataloader_workers,
812
+ )
813
+
814
+ # Scheduler and math around the number of training steps.
815
+ overrode_max_train_steps = False
816
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
817
+ if args.max_train_steps is None:
818
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
819
+ overrode_max_train_steps = True
820
+
821
+ lr_scheduler = get_scheduler(
822
+ args.lr_scheduler,
823
+ optimizer=optimizer,
824
+ num_warmup_steps=args.lr_warmup_steps * args.gradient_accumulation_steps,
825
+ num_training_steps=args.max_train_steps * args.gradient_accumulation_steps,
826
+ num_cycles=args.lr_num_cycles,
827
+ power=args.lr_power,
828
+ )
829
+
830
+ # Prepare everything with our `accelerator`.
831
+ if args.train_text_encoder:
832
+ unet, text_encoder, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
833
+ unet, text_encoder, optimizer, train_dataloader, lr_scheduler
834
+ )
835
+ else:
836
+ unet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
837
+ unet, optimizer, train_dataloader, lr_scheduler
838
+ )
839
+
840
+ # For mixed precision training we cast the text_encoder and vae weights to half-precision
841
+ # as these models are only used for inference, keeping weights in full precision is not required.
842
+ weight_dtype = torch.float32
843
+ if accelerator.mixed_precision == "fp16":
844
+ weight_dtype = torch.float16
845
+ elif accelerator.mixed_precision == "bf16":
846
+ weight_dtype = torch.bfloat16
847
+
848
+ # Move vae and text_encoder to device and cast to weight_dtype
849
+ vae.to(accelerator.device, dtype=weight_dtype)
850
+ if not args.train_text_encoder:
851
+ text_encoder.to(accelerator.device, dtype=weight_dtype)
852
+
853
+ # We need to recalculate our total training steps as the size of the training dataloader may have changed.
854
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
855
+ if overrode_max_train_steps:
856
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
857
+ # Afterwards we recalculate our number of training epochs
858
+ args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
859
+
860
+ # We need to initialize the trackers we use, and also store our configuration.
861
+ # The trackers initializes automatically on the main process.
862
+ if accelerator.is_main_process:
863
+ accelerator.init_trackers("dreambooth", config=vars(args))
864
+
865
+ # Train!
866
+ total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
867
+
868
+ logger.info("***** Running training *****")
869
+ logger.info(f" Num examples = {len(train_dataset)}")
870
+ logger.info(f" Num batches each epoch = {len(train_dataloader)}")
871
+ logger.info(f" Num Epochs = {args.num_train_epochs}")
872
+ logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
873
+ logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
874
+ logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
875
+ logger.info(f" Total optimization steps = {args.max_train_steps}")
876
+ global_step = 0
877
+ first_epoch = 0
878
+
879
+ # Potentially load in the weights and states from a previous save
880
+ if args.resume_from_checkpoint:
881
+ if args.resume_from_checkpoint != "latest":
882
+ path = os.path.basename(args.resume_from_checkpoint)
883
+ else:
884
+ # Get the mos recent checkpoint
885
+ dirs = os.listdir(args.output_dir)
886
+ dirs = [d for d in dirs if d.startswith("checkpoint")]
887
+ dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
888
+ path = dirs[-1]
889
+ accelerator.print(f"Resuming from checkpoint {path}")
890
+ accelerator.load_state(os.path.join(args.output_dir, path))
891
+ global_step = int(path.split("-")[1])
892
+
893
+ resume_global_step = global_step * args.gradient_accumulation_steps
894
+ first_epoch = resume_global_step // num_update_steps_per_epoch
895
+ resume_step = resume_global_step % num_update_steps_per_epoch
896
+
897
+ # Only show the progress bar once on each machine.
898
+ progress_bar = tqdm(range(global_step, args.max_train_steps), disable=not accelerator.is_local_main_process)
899
+ progress_bar.set_description("Steps")
900
+
901
+ for epoch in range(first_epoch, args.num_train_epochs):
902
+ unet.train()
903
+ if args.train_text_encoder:
904
+ text_encoder.train()
905
+ with TorchTracemalloc() if not args.no_tracemalloc else nullcontext() as tracemalloc:
906
+ for step, batch in enumerate(train_dataloader):
907
+ # Skip steps until we reach the resumed step
908
+ if args.resume_from_checkpoint and epoch == first_epoch and step < resume_step:
909
+ if step % args.gradient_accumulation_steps == 0:
910
+ progress_bar.update(1)
911
+ if args.report_to == "wandb":
912
+ accelerator.print(progress_bar)
913
+ continue
914
+
915
+ with accelerator.accumulate(unet):
916
+ # Convert images to latent space
917
+ latents = vae.encode(batch["pixel_values"].to(dtype=weight_dtype)).latent_dist.sample()
918
+ latents = latents * 0.18215
919
+
920
+ # Sample noise that we'll add to the latents
921
+ noise = torch.randn_like(latents)
922
+ bsz = latents.shape[0]
923
+ # Sample a random timestep for each image
924
+ timesteps = torch.randint(
925
+ 0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device
926
+ )
927
+ timesteps = timesteps.long()
928
+
929
+ # Add noise to the latents according to the noise magnitude at each timestep
930
+ # (this is the forward diffusion process)
931
+ noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
932
+
933
+ # Get the text embedding for conditioning
934
+ encoder_hidden_states = text_encoder(batch["input_ids"])[0]
935
+
936
+ # Predict the noise residual
937
+ model_pred = unet(noisy_latents, timesteps, encoder_hidden_states).sample
938
+
939
+ # Get the target for loss depending on the prediction type
940
+ if noise_scheduler.config.prediction_type == "epsilon":
941
+ target = noise
942
+ elif noise_scheduler.config.prediction_type == "v_prediction":
943
+ target = noise_scheduler.get_velocity(latents, noise, timesteps)
944
+ else:
945
+ raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
946
+
947
+ if args.with_prior_preservation:
948
+ # Chunk the noise and model_pred into two parts and compute the loss on each part separately.
949
+ model_pred, model_pred_prior = torch.chunk(model_pred, 2, dim=0)
950
+ target, target_prior = torch.chunk(target, 2, dim=0)
951
+
952
+ # Compute instance loss
953
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
954
+
955
+ # Compute prior loss
956
+ prior_loss = F.mse_loss(model_pred_prior.float(), target_prior.float(), reduction="mean")
957
+
958
+ # Add the prior loss to the instance loss.
959
+ loss = loss + args.prior_loss_weight * prior_loss
960
+ else:
961
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
962
+
963
+ accelerator.backward(loss)
964
+ if accelerator.sync_gradients:
965
+ params_to_clip = (
966
+ itertools.chain(unet.parameters(), text_encoder.parameters())
967
+ if args.train_text_encoder
968
+ else unet.parameters()
969
+ )
970
+ accelerator.clip_grad_norm_(params_to_clip, args.max_grad_norm)
971
+ optimizer.step()
972
+ lr_scheduler.step()
973
+ optimizer.zero_grad()
974
+
975
+ # Checks if the accelerator has performed an optimization step behind the scenes
976
+ if accelerator.sync_gradients:
977
+ progress_bar.update(1)
978
+ if args.report_to == "wandb":
979
+ accelerator.print(progress_bar)
980
+ global_step += 1
981
+
982
+ # if global_step % args.checkpointing_steps == 0:
983
+ # if accelerator.is_main_process:
984
+ # save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
985
+ # accelerator.save_state(save_path)
986
+ # logger.info(f"Saved state to {save_path}")
987
+
988
+ logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
989
+ progress_bar.set_postfix(**logs)
990
+ accelerator.log(logs, step=global_step)
991
+
992
+ if (
993
+ args.validation_prompt is not None
994
+ and (step + num_update_steps_per_epoch * epoch) % args.validation_steps == 0
995
+ ):
996
+ logger.info(
997
+ f"Running validation... \n Generating {args.num_validation_images} images with prompt:"
998
+ f" {args.validation_prompt}."
999
+ )
1000
+ # create pipeline
1001
+ pipeline = DiffusionPipeline.from_pretrained(
1002
+ args.pretrained_model_name_or_path,
1003
+ safety_checker=None,
1004
+ revision=args.revision,
1005
+ )
1006
+ # set `keep_fp32_wrapper` to True because we do not want to remove
1007
+ # mixed precision hooks while we are still training
1008
+ pipeline.unet = accelerator.unwrap_model(unet, keep_fp32_wrapper=True)
1009
+ pipeline.text_encoder = accelerator.unwrap_model(text_encoder, keep_fp32_wrapper=True)
1010
+ pipeline.scheduler = DPMSolverMultistepScheduler.from_config(pipeline.scheduler.config)
1011
+ pipeline = pipeline.to(accelerator.device)
1012
+ pipeline.set_progress_bar_config(disable=True)
1013
+
1014
+ # run inference
1015
+ if args.seed is not None:
1016
+ generator = torch.Generator(device=accelerator.device).manual_seed(args.seed)
1017
+ else:
1018
+ generator = None
1019
+ images = []
1020
+ for _ in range(args.num_validation_images):
1021
+ image = pipeline(args.validation_prompt, num_inference_steps=25, generator=generator).images[0]
1022
+ images.append(image)
1023
+
1024
+ for tracker in accelerator.trackers:
1025
+ if tracker.name == "tensorboard":
1026
+ np_images = np.stack([np.asarray(img) for img in images])
1027
+ tracker.writer.add_images("validation", np_images, epoch, dataformats="NHWC")
1028
+ if tracker.name == "wandb":
1029
+ import wandb
1030
+
1031
+ tracker.log(
1032
+ {
1033
+ "validation": [
1034
+ wandb.Image(image, caption=f"{i}: {args.validation_prompt}")
1035
+ for i, image in enumerate(images)
1036
+ ]
1037
+ }
1038
+ )
1039
+
1040
+ del pipeline
1041
+ if torch.cuda.is_available():
1042
+ torch.cuda.empty_cache()
1043
+ elif torch.xpu.is_available():
1044
+ torch.xpu.empty_cache()
1045
+
1046
+ if global_step >= args.max_train_steps:
1047
+ break
1048
+
1049
+ # Printing the accelerator memory usage details such as allocated memory, peak memory, and total memory usage
1050
+ if not args.no_tracemalloc:
1051
+ accelerator.print(
1052
+ f"{accelerator.device.type.upper()} Memory before entering the train : {b2mb(tracemalloc.begin)}"
1053
+ )
1054
+ accelerator.print(
1055
+ f"{accelerator.device.type.upper()} Memory consumed at the end of the train (end-begin): {tracemalloc.used}"
1056
+ )
1057
+ accelerator.print(
1058
+ f"{accelerator.device.type.upper()} Peak Memory consumed during the train (max-begin): {tracemalloc.peaked}"
1059
+ )
1060
+ accelerator.print(
1061
+ f"{accelerator.device.type.upper()} Total Peak Memory consumed during the train (max): {tracemalloc.peaked + b2mb(tracemalloc.begin)}"
1062
+ )
1063
+
1064
+ accelerator.print(f"CPU Memory before entering the train : {b2mb(tracemalloc.cpu_begin)}")
1065
+ accelerator.print(f"CPU Memory consumed at the end of the train (end-begin): {tracemalloc.cpu_used}")
1066
+ accelerator.print(f"CPU Peak Memory consumed during the train (max-begin): {tracemalloc.cpu_peaked}")
1067
+ accelerator.print(
1068
+ f"CPU Total Peak Memory consumed during the train (max): {tracemalloc.cpu_peaked + b2mb(tracemalloc.cpu_begin)}"
1069
+ )
1070
+
1071
+ # Create the pipeline using using the trained modules and save it.
1072
+ accelerator.wait_for_everyone()
1073
+ if accelerator.is_main_process:
1074
+ if args.use_lora:
1075
+ unwarpped_unet = accelerator.unwrap_model(unet)
1076
+ unwarpped_unet.save_pretrained(
1077
+ os.path.join(args.output_dir, "unet"), state_dict=accelerator.get_state_dict(unet)
1078
+ )
1079
+ if args.train_text_encoder:
1080
+ unwarpped_text_encoder = accelerator.unwrap_model(text_encoder)
1081
+ unwarpped_text_encoder.save_pretrained(
1082
+ os.path.join(args.output_dir, "text_encoder"),
1083
+ state_dict=accelerator.get_state_dict(text_encoder),
1084
+ )
1085
+ else:
1086
+ pipeline = DiffusionPipeline.from_pretrained(
1087
+ args.pretrained_model_name_or_path,
1088
+ unet=accelerator.unwrap_model(unet),
1089
+ text_encoder=accelerator.unwrap_model(text_encoder),
1090
+ revision=args.revision,
1091
+ )
1092
+ pipeline.save_pretrained(args.output_dir)
1093
+
1094
+ if args.push_to_hub:
1095
+ api.upload_folder(
1096
+ repo_id=repo_id,
1097
+ folder_path=args.output_dir,
1098
+ commit_message="End of training",
1099
+ run_as_future=True,
1100
+ )
1101
+
1102
+ accelerator.end_training()
1103
+
1104
+
1105
+ if __name__ == "__main__":
1106
+ args = parse_args()
1107
+ main(args)
tasks/tasksmith-c488fc138ba1/tests/source/examples/lora_finetuning_transformer_engine/Dockerfile ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ FROM nvcr.io/nvidia/pytorch:26.01-py3
2
+
3
+ WORKDIR /workspace/lora_finetuning
4
+
5
+ COPY requirements.txt .
6
+ RUN pip install --no-cache-dir -r requirements.txt
7
+
8
+ COPY lora_finetuning_te.py .
tasks/tasksmith-c488fc138ba1/tests/source/examples/lora_finetuning_transformer_engine/README.md ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Transformer Engine ESM2 LoRA Fine-Tuning
2
+
3
+ This example demonstrates LoRA fine-tuning for Transformer Engine ESM2 token classification.
4
+
5
+ ## Setup
6
+
7
+ Choose one of the two options below.
8
+
9
+ ### Option A: Docker (recommended)
10
+
11
+ Build a self-contained image based on the publicly available NVIDIA PyTorch container
12
+ (`nvcr.io/nvidia/pytorch:26.01-py3`), which already ships CUDA, cuDNN, and Transformer Engine:
13
+
14
+ ```bash
15
+ docker build -t lora-te examples/lora_finetuning_transformer_engine
16
+ ```
17
+
18
+ Run the training inside the container:
19
+
20
+ ```bash
21
+ docker run --gpus all --rm lora-te \
22
+ python lora_finetuning_te.py \
23
+ --base_model nvidia/esm2_t6_8M_UR50D \
24
+ --output_dir ./esm2_lora_output \
25
+ --num_train_samples 256 \
26
+ --num_eval_samples 64 \
27
+ --num_epochs 1
28
+ ```
29
+
30
+ Or start an interactive session to experiment:
31
+
32
+ ```bash
33
+ docker run --gpus all --rm -it lora-te bash
34
+ ```
35
+
36
+ ### Option B: Virtual environment
37
+
38
+ Create and activate a virtual environment, then install the Python dependencies:
39
+
40
+ ```bash
41
+ python -m venv .venv
42
+ source .venv/bin/activate
43
+ pip install -r examples/lora_finetuning_transformer_engine/requirements.txt
44
+ ```
45
+
46
+ **Transformer Engine** must be installed separately and must match the system CUDA toolkit version.
47
+ See the [TE installation guide](https://docs.nvidia.com/deeplearning/transformer-engine/user-guide/installation.html)
48
+ for details.
49
+
50
+ ## What this example does
51
+
52
+ - Loads a Transformer Engine ESM2 model for token classification
53
+ - Applies LoRA adapters via PEFT
54
+ - Generates random protein-like sequences
55
+ - Assigns randomly generated secondary structure labels (`H`, `E`, `C`)
56
+ - Trains/evaluates with `Trainer`
57
+
58
+ ## Run
59
+
60
+ ```bash
61
+ python examples/lora_finetuning_transformer_engine/lora_finetuning_te.py \
62
+ --base_model nvidia/esm2_t6_8M_UR50D \
63
+ --output_dir ./esm2_lora_output \
64
+ --num_train_samples 256 \
65
+ --num_eval_samples 64 \
66
+ --num_epochs 1
67
+ ```
68
+
69
+ > **Note:** The default ESM2 models on Hugging Face Hub ship custom modeling code.
70
+ > You must pass `--trust_remote_code` to allow loading that code.
71
+
72
+ ## Customize
73
+
74
+ ```bash
75
+ python examples/lora_finetuning_transformer_engine/lora_finetuning_te.py \
76
+ --base_model nvidia/esm2_t6_8M_UR50D \
77
+ --trust_remote_code \
78
+ --output_dir ./esm2_lora_output \
79
+ --max_length 256 \
80
+ --batch_size 4 \
81
+ --learning_rate 3e-4 \
82
+ --lora_r 16 \
83
+ --lora_alpha 32 \
84
+ --lora_dropout 0.1
85
+ ```
86
+
87
+ ## Dataset
88
+
89
+ By default the script generates a **synthetic dataset** at runtime — random protein-like sequences
90
+ with randomly generated secondary structure labels (`H`, `E`, `C`). This is useful for quick sanity checks and testing.
91
+
92
+ For a more realistic evaluation, you can use the **Porter6** secondary-structure dataset.
93
+ A download-and-convert script is available in the BioNeMo repository:
94
+
95
+ [prepare_porter6_dataset.py](https://github.com/NVIDIA/bionemo-framework/blob/bd72d882bca458d9438e05661c41163949713d1f/bionemo-recipes/recipes/esm2_peft_te/data/prepare_porter6_dataset.py)
96
+
97
+ Run it to produce train and validation parquet files, then pass them to the training script
98
+ with `--train_parquet` and `--val_parquet`:
99
+
100
+ ```bash
101
+ python examples/lora_finetuning_transformer_engine/lora_finetuning_te.py \
102
+ --base_model nvidia/esm2_t6_8M_UR50D \
103
+ --train_parquet porter6_train_dataset_55k.parquet \
104
+ --val_parquet porter6_val_dataset_2024_692.parquet \
105
+ --output_dir ./esm2_lora_output \
106
+ --num_epochs 3
107
+ ```
108
+
109
+ ## Outputs
110
+
111
+ After training, the script saves:
112
+
113
+ - PEFT adapter weights/config in `--output_dir`
114
+ - Tokenizer files in `--output_dir`
115
+
116
+ ## More examples
117
+
118
+ For additional examples of TransformerEngine-accelerated transformers, visit
119
+ `https://github.com/NVIDIA/bionemo-framework/bionemo-recipes`.
tasks/tasksmith-c488fc138ba1/tests/source/examples/lora_finetuning_transformer_engine/lora_finetuning_te.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Transformer Engine ESM2 LoRA fine-tuning example using Hugging Face Trainer.
3
+
4
+ This script demonstrates:
5
+ 1. Loading a Transformer Engine-based ESM2 token classification model
6
+ 2. Applying LoRA adapters with PEFT
7
+ 3. Building a synthetic protein token-classification dataset in code
8
+ 4. Training with the Hugging Face Trainer (no DDP setup required)
9
+ """
10
+
11
+ import os
12
+
13
+
14
+ # TE-backed models are incompatible with Trainer's DataParallel wrapping.
15
+ # Pin to a single GPU before torch is imported so torch.cuda.device_count() == 1.
16
+ os.environ.setdefault("CUDA_VISIBLE_DEVICES", "0")
17
+
18
+ import argparse
19
+ import random
20
+
21
+ import numpy as np
22
+ import pandas as pd
23
+ import torch
24
+ from datasets import Dataset
25
+ from transformers import (
26
+ AutoConfig,
27
+ AutoModelForTokenClassification,
28
+ AutoTokenizer,
29
+ DataCollatorForTokenClassification,
30
+ Trainer,
31
+ TrainingArguments,
32
+ )
33
+
34
+ from peft import LoraConfig, TaskType, get_peft_model
35
+
36
+
37
+ SS3_ID2LABEL = {0: "H", 1: "E", 2: "C"}
38
+ SS3_LABEL2ID = {label: idx for idx, label in SS3_ID2LABEL.items()}
39
+
40
+ AMINO_ACIDS = "ACDEFGHIKLMNPQRSTVWY"
41
+ HELIX_AA = set("AELMQKRH")
42
+ BETA_AA = set("VIFYWT")
43
+
44
+
45
+ def parse_args():
46
+ """Parse command-line arguments."""
47
+ parser = argparse.ArgumentParser(description="Transformer Engine ESM2 LoRA fine-tuning with Hugging Face Trainer")
48
+
49
+ parser.add_argument(
50
+ "--base_model",
51
+ type=str,
52
+ default="nvidia/esm2_t6_8M_UR50D",
53
+ help="Transformer Engine ESM2 model name or path",
54
+ )
55
+ parser.add_argument("--output_dir", type=str, default="./esm2_lora_output", help="Output directory")
56
+ parser.add_argument("--max_length", type=int, default=128, help="Maximum sequence length")
57
+ parser.add_argument("--num_train_samples", type=int, default=256, help="Number of synthetic training samples")
58
+ parser.add_argument("--num_eval_samples", type=int, default=64, help="Number of synthetic evaluation samples")
59
+ parser.add_argument("--min_seq_len", type=int, default=32, help="Minimum sequence length")
60
+ parser.add_argument("--max_seq_len", type=int, default=96, help="Maximum sequence length")
61
+ parser.add_argument("--batch_size", type=int, default=8, help="Per-device batch size")
62
+ parser.add_argument("--num_epochs", type=int, default=1, help="Number of training epochs")
63
+ parser.add_argument("--learning_rate", type=float, default=5e-4, help="Learning rate")
64
+ parser.add_argument("--weight_decay", type=float, default=0.01, help="Weight decay")
65
+ parser.add_argument("--logging_steps", type=int, default=10, help="Logging frequency (steps)")
66
+ parser.add_argument("--eval_steps", type=int, default=25, help="Evaluation frequency (steps)")
67
+ parser.add_argument("--save_steps", type=int, default=25, help="Save frequency (steps)")
68
+ parser.add_argument("--seed", type=int, default=42, help="Random seed")
69
+ parser.add_argument("--lora_r", type=int, default=8, help="LoRA rank")
70
+ parser.add_argument("--lora_alpha", type=int, default=16, help="LoRA alpha")
71
+ parser.add_argument("--lora_dropout", type=float, default=0.05, help="LoRA dropout")
72
+ parser.add_argument(
73
+ "--trust_remote_code",
74
+ action="store_true",
75
+ default=False,
76
+ help="Allow loading model code from the Hub. Required for models like nvidia/esm2_*.",
77
+ )
78
+ parser.add_argument(
79
+ "--train_parquet",
80
+ type=str,
81
+ default=None,
82
+ help="Path to a training parquet file with Sequence and Secondary_structure columns. "
83
+ "When provided, the synthetic dataset is not generated.",
84
+ )
85
+ parser.add_argument(
86
+ "--val_parquet",
87
+ type=str,
88
+ default=None,
89
+ help="Path to a validation parquet file with the same schema as --train_parquet.",
90
+ )
91
+
92
+ args = parser.parse_args()
93
+
94
+ if bool(args.train_parquet) != bool(args.val_parquet):
95
+ parser.error("--train_parquet and --val_parquet must both be provided or both omitted.")
96
+
97
+ return args
98
+
99
+
100
+ def set_seed(seed: int):
101
+ """Set random seeds for reproducibility."""
102
+ random.seed(seed)
103
+ np.random.seed(seed)
104
+ torch.manual_seed(seed)
105
+ if torch.cuda.is_available():
106
+ torch.cuda.manual_seed_all(seed)
107
+
108
+
109
+ def build_synthetic_sequences(num_samples: int, min_len: int, max_len: int):
110
+ """Generate random amino-acid sequences."""
111
+ sequences = []
112
+ for _ in range(num_samples):
113
+ length = random.randint(min_len, max_len)
114
+ sequences.append("".join(random.choices(AMINO_ACIDS, k=length)))
115
+ return sequences
116
+
117
+
118
+ def ss_char_to_label(char: str) -> int:
119
+ """Map a single secondary structure character to a label id (H/E/C)."""
120
+ return SS3_LABEL2ID.get(char, SS3_LABEL2ID["C"])
121
+
122
+
123
+ def tokenize_and_align_labels(sequences, label_strings, tokenizer, max_length: int):
124
+ """Tokenize protein sequences and align per-residue label strings to token positions."""
125
+ batch_input_ids = []
126
+ batch_attention_mask = []
127
+ batch_labels = []
128
+
129
+ for sequence, label_str in zip(sequences, label_strings):
130
+ encoded = tokenizer(
131
+ sequence,
132
+ truncation=True,
133
+ max_length=max_length,
134
+ add_special_tokens=True,
135
+ )
136
+ input_ids = encoded["input_ids"]
137
+ attention_mask = encoded["attention_mask"]
138
+
139
+ labels = [-100] * len(input_ids)
140
+ usable_len = min(len(sequence), len(label_str), len(input_ids) - 2)
141
+ for idx in range(usable_len):
142
+ labels[idx + 1] = ss_char_to_label(label_str[idx])
143
+
144
+ batch_input_ids.append(input_ids)
145
+ batch_attention_mask.append(attention_mask)
146
+ batch_labels.append(labels)
147
+
148
+ return {
149
+ "input_ids": batch_input_ids,
150
+ "attention_mask": batch_attention_mask,
151
+ "labels": batch_labels,
152
+ }
153
+
154
+
155
+ def load_parquet_dataset(train_path: str, val_path: str, tokenizer, max_length: int):
156
+ """Load train/val parquet files and return tokenized Datasets."""
157
+ train_df = pd.read_parquet(train_path)
158
+ val_df = pd.read_parquet(val_path)
159
+
160
+ train_dataset = Dataset.from_pandas(train_df).map(
161
+ lambda ex: tokenize_and_align_labels(ex["Sequence"], ex["Secondary_structure"], tokenizer, max_length),
162
+ batched=True,
163
+ remove_columns=train_df.columns.tolist(),
164
+ )
165
+ val_dataset = Dataset.from_pandas(val_df).map(
166
+ lambda ex: tokenize_and_align_labels(ex["Sequence"], ex["Secondary_structure"], tokenizer, max_length),
167
+ batched=True,
168
+ remove_columns=val_df.columns.tolist(),
169
+ )
170
+ return train_dataset, val_dataset
171
+
172
+
173
+ def compute_metrics(eval_pred):
174
+ """Compute token accuracy while ignoring -100 labels."""
175
+ logits, labels = eval_pred
176
+ predictions = np.argmax(logits, axis=-1)
177
+ mask = labels != -100
178
+ correct = (predictions == labels) & mask
179
+ total_tokens = mask.sum()
180
+ accuracy = float(correct.sum() / total_tokens) if total_tokens > 0 else 0.0
181
+ return {"token_accuracy": accuracy}
182
+
183
+
184
+ def residue_to_ss_char(aa: str) -> str:
185
+ """Map an amino acid to a synthetic secondary structure character (H/E/C)."""
186
+ if aa in HELIX_AA:
187
+ return "H"
188
+ if aa in BETA_AA:
189
+ return "E"
190
+ return "C"
191
+
192
+
193
+ def sequence_to_synthetic_labels(sequence: str) -> str:
194
+ """Derive a synthetic per-residue label string from an amino acid sequence."""
195
+ return "".join(residue_to_ss_char(aa) for aa in sequence)
196
+
197
+
198
+ def make_synthetic_dataset(
199
+ tokenizer,
200
+ num_train_samples: int,
201
+ num_eval_samples: int,
202
+ min_seq_len: int,
203
+ max_seq_len: int,
204
+ max_length: int,
205
+ ):
206
+ """Create a synthetic train/eval dataset for token classification."""
207
+ train_sequences = build_synthetic_sequences(num_train_samples, min_seq_len, max_seq_len)
208
+ eval_sequences = build_synthetic_sequences(num_eval_samples, min_seq_len, max_seq_len)
209
+
210
+ train_labels = [sequence_to_synthetic_labels(s) for s in train_sequences]
211
+ eval_labels = [sequence_to_synthetic_labels(s) for s in eval_sequences]
212
+
213
+ train_dataset = Dataset.from_dict({"sequence": train_sequences, "labels_str": train_labels}).map(
214
+ lambda ex: tokenize_and_align_labels(ex["sequence"], ex["labels_str"], tokenizer, max_length),
215
+ batched=True,
216
+ remove_columns=["sequence", "labels_str"],
217
+ )
218
+ eval_dataset = Dataset.from_dict({"sequence": eval_sequences, "labels_str": eval_labels}).map(
219
+ lambda ex: tokenize_and_align_labels(ex["sequence"], ex["labels_str"], tokenizer, max_length),
220
+ batched=True,
221
+ remove_columns=["sequence", "labels_str"],
222
+ )
223
+ return train_dataset, eval_dataset
224
+
225
+
226
+ def main():
227
+ args = parse_args()
228
+ set_seed(args.seed)
229
+
230
+ if not args.trust_remote_code and "esm2" in args.base_model.lower():
231
+ raise ValueError(
232
+ f"Model '{args.base_model}' requires remote code execution. "
233
+ "Re-run with --trust_remote_code to confirm you trust this model's code."
234
+ )
235
+
236
+ os.makedirs(args.output_dir, exist_ok=True)
237
+ use_bf16 = torch.cuda.is_available() and torch.cuda.is_bf16_supported()
238
+ model_dtype = torch.bfloat16 if use_bf16 else torch.float32
239
+
240
+ print(f"Loading tokenizer and model from: {args.base_model}")
241
+ tokenizer = AutoTokenizer.from_pretrained(args.base_model, trust_remote_code=args.trust_remote_code)
242
+
243
+ config = AutoConfig.from_pretrained(args.base_model, trust_remote_code=args.trust_remote_code)
244
+ config.num_labels = 3
245
+ config.id2label = SS3_ID2LABEL
246
+ config.label2id = SS3_LABEL2ID
247
+
248
+ model = AutoModelForTokenClassification.from_pretrained(
249
+ args.base_model,
250
+ config=config,
251
+ trust_remote_code=args.trust_remote_code,
252
+ dtype=model_dtype,
253
+ )
254
+
255
+ lora_config = LoraConfig(
256
+ task_type=TaskType.TOKEN_CLS,
257
+ r=args.lora_r,
258
+ lora_alpha=args.lora_alpha,
259
+ lora_dropout=args.lora_dropout,
260
+ target_modules=["layernorm_qkv"],
261
+ bias="none",
262
+ inference_mode=False,
263
+ )
264
+ model = get_peft_model(model, lora_config)
265
+ model.print_trainable_parameters()
266
+
267
+ if args.train_parquet and args.val_parquet:
268
+ print(f"Loading parquet datasets: train={args.train_parquet}, val={args.val_parquet}")
269
+ train_dataset, eval_dataset = load_parquet_dataset(
270
+ train_path=args.train_parquet,
271
+ val_path=args.val_parquet,
272
+ tokenizer=tokenizer,
273
+ max_length=args.max_length,
274
+ )
275
+ else:
276
+ print("Building synthetic dataset...")
277
+ train_dataset, eval_dataset = make_synthetic_dataset(
278
+ tokenizer=tokenizer,
279
+ num_train_samples=args.num_train_samples,
280
+ num_eval_samples=args.num_eval_samples,
281
+ min_seq_len=args.min_seq_len,
282
+ max_seq_len=args.max_seq_len,
283
+ max_length=args.max_length,
284
+ )
285
+
286
+ data_collator = DataCollatorForTokenClassification(tokenizer=tokenizer)
287
+
288
+ training_args = TrainingArguments(
289
+ output_dir=args.output_dir,
290
+ num_train_epochs=args.num_epochs,
291
+ per_device_train_batch_size=args.batch_size,
292
+ per_device_eval_batch_size=args.batch_size,
293
+ learning_rate=args.learning_rate,
294
+ weight_decay=args.weight_decay,
295
+ logging_steps=args.logging_steps,
296
+ eval_steps=args.eval_steps,
297
+ save_steps=args.save_steps,
298
+ eval_strategy="steps",
299
+ save_strategy="steps",
300
+ save_total_limit=2,
301
+ load_best_model_at_end=True,
302
+ metric_for_best_model="token_accuracy",
303
+ greater_is_better=True,
304
+ report_to="none",
305
+ remove_unused_columns=False,
306
+ bf16=use_bf16,
307
+ seed=args.seed,
308
+ )
309
+
310
+ trainer = Trainer(
311
+ model=model,
312
+ args=training_args,
313
+ train_dataset=train_dataset,
314
+ eval_dataset=eval_dataset,
315
+ data_collator=data_collator,
316
+ compute_metrics=compute_metrics,
317
+ )
318
+
319
+ trainer.train()
320
+ final_metrics = trainer.evaluate()
321
+ print(f"Final evaluation metrics: {final_metrics}")
322
+
323
+ model.save_pretrained(args.output_dir)
324
+ tokenizer.save_pretrained(args.output_dir)
325
+ print(f"Saved LoRA adapter and tokenizer to: {args.output_dir}")
326
+
327
+
328
+ if __name__ == "__main__":
329
+ main()
tasks/tasksmith-c488fc138ba1/tests/source/examples/lora_finetuning_transformer_engine/requirements.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ torch
2
+ transformers
3
+ datasets
4
+ peft
5
+ accelerate
6
+ numpy
7
+ pandas
8
+ pyarrow
9
+ safetensors
10
+ # transformer-engine must match the system CUDA toolkit version.
11
+ # Install it separately or use the system-provided package.
12
+ # See: https://docs.nvidia.com/deeplearning/transformer-engine/user-guide/installation.html
tasks/tasksmith-c488fc138ba1/tests/source/examples/lora_ga_finetuning/README.md ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LoRA-GA: Low-Rank Adaptation with Gradient Approximation
2
+
3
+ ## Introduction
4
+
5
+ [LoRA-GA](https://huggingface.co/papers/2407.05000) improves upon standard LoRA by using gradient information during initialization instead of random initialization. By performing SVD on estimated gradients, LoRA-GA initializes adapter weights in a direction that aligns with full fine-tuning, achieving 2-4x faster convergence while maintaining the same final performance. The method is orthogonal to existing LoRA variants and can be easily integrated with techniques like DoRA and LoRA+.
6
+
7
+ ## Quick start
8
+
9
+ This example script demonstrates how to fine-tune a language model using LoRA-GA on the WikiText-2 dataset. The script performs gradient estimation on a small number of batches, uses those gradients to initialize LoRA adapters, and then trains the model with the Hugging Face Trainer.
10
+
11
+ ```python
12
+ import torch
13
+ from datasets import load_dataset
14
+ from transformers import AutoTokenizer, AutoModelForCausalLM, Trainer, TrainingArguments
15
+ from torch.utils.data import DataLoader
16
+ from peft import LoraConfig, get_peft_model
17
+ from peft.tuners.lora import LoraGAConfig, preprocess_loraga
18
+
19
+ # Load model and tokenizer
20
+ model = AutoModelForCausalLM.from_pretrained("gpt2")
21
+ tokenizer = AutoTokenizer.from_pretrained("gpt2")
22
+ dataset = load_dataset("wikitext", "wikitext-2-raw-v1")
23
+
24
+ # Prepare dataloader for gradient estimation
25
+ train_dataloader = DataLoader(dataset["train"], batch_size=2, shuffle=True)
26
+
27
+ # Define train_step callback for gradient estimation
28
+ def train_step():
29
+ """Run forward and backward passes for gradient estimation."""
30
+ data_iter = iter(train_dataloader)
31
+ for _ in range(64): # 64 iterations
32
+ batch = next(data_iter)
33
+
34
+ outputs = model(**batch)
35
+ loss = outputs.loss
36
+ loss.backward()
37
+
38
+ # Step 1: Create LoRA-GA config
39
+ lora_ga_config = LoraGAConfig(
40
+ direction="ArB2r",
41
+ scale="stable",
42
+ stable_gamma=16,
43
+ )
44
+
45
+ lora_config = LoraConfig(
46
+ r=8,
47
+ lora_alpha=16,
48
+ target_modules=["c_attn"],
49
+ init_lora_weights="lora_ga",
50
+ lora_ga_config=lora_ga_config,
51
+ task_type="CAUSAL_LM",
52
+ )
53
+
54
+ # Step 2: Preprocess with LoRA-GA to estimate gradients
55
+ preprocess_loraga(model, lora_config, train_step)
56
+
57
+ # Step 3: Create PEFT model with LoRA-GA initialization
58
+ peft_model = get_peft_model(model, lora_config)
59
+
60
+ # Step 4: Train normally
61
+ trainer = Trainer(
62
+ model=peft_model,
63
+ train_dataset=dataset["train"],
64
+ args=TrainingArguments(output_dir="./output", num_train_epochs=3),
65
+ )
66
+ trainer.train()
67
+
68
+ # Step 5: Save the trained adapter
69
+ peft_model.save_pretrained("./output")
70
+ ```
71
+
72
+ ## Saving with Modified Base Weights
73
+
74
+ **Important**: LoRA-GA modifies the base model weights during initialization (unlike standard LoRA). This means you need to handle saving carefully if you want to restore the original base weights.
75
+
76
+ ### Option 1: Save adapter only (default)
77
+
78
+ The standard `save_pretrained()` saves the adapter with the modified base weights embedded:
79
+
80
+ ```python
81
+ # This saves the adapter - base weights remain modified
82
+ peft_model.save_pretrained("./output")
83
+ ```
84
+
85
+ ### Option 2: Restore original base weights
86
+
87
+ If you need to restore the original base weights (e.g., for model merging or sharing), use `path_initial_model_for_weight_conversion`:
88
+
89
+ ```python
90
+ # Save the original model BEFORE LoRA-GA preprocessing
91
+ model.save_pretrained("./original_model")
92
+
93
+ # ... do preprocessing and training ...
94
+
95
+ # Save adapter and convert back to original base weights
96
+ peft_model.save_pretrained(
97
+ "./output",
98
+ path_initial_model_for_weight_conversion="./original_model"
99
+ )
100
+ ```
101
+
102
+ This is useful when:
103
+ - You want to merge the adapter with the original base weights later
104
+ - You're sharing the adapter and want users to apply it to the unmodified base model
105
+ - You need the base model weights in their original state for other purposes
106
+
107
+ ## Run the finetuning script
108
+
109
+ Simply run:
110
+
111
+ ```bash
112
+ python examples/lora_ga_finetuning/lora_ga_finetuning.py \
113
+ --base_model gpt2 \
114
+ --dataset_name wikitext \
115
+ --dataset_config wikitext-2-raw-v1 \
116
+ --output_dir ./lora_ga_output
117
+ ```
118
+
119
+ ### Customize LoRA-GA parameters
120
+
121
+ You can customize the direction and scaling strategies:
122
+
123
+ ```bash
124
+ python examples/lora_ga_finetuning/lora_ga_finetuning.py \
125
+ --base_model gpt2 \
126
+ --direction ArB2r \
127
+ --scale stable \
128
+ --stable_gamma 16 \
129
+ --grad_estimate_iters 64
130
+ ```
131
+
132
+ ### Full example with all parameters
133
+
134
+ ```bash
135
+ python lora_ga_finetuning.py \
136
+ --base_model "gpt2" \
137
+ --dataset_name "wikitext" \
138
+ --dataset_config "wikitext-2-raw-v1" \
139
+ --output_dir "./lora_ga_output" \
140
+ --r 8 \
141
+ --lora_alpha 16 \
142
+ --lora_dropout 0.1 \
143
+ --direction "ArB2r" \
144
+ --scale "stable" \
145
+ --stable_gamma 16 \
146
+ --grad_estimate_iters 64 \
147
+ --grad_estimate_batch_size 2 \
148
+ --num_epochs 3 \
149
+ --batch_size 8 \
150
+ --learning_rate 3e-5
151
+ ```
152
+
153
+ ## Configuration Options
154
+
155
+ ### Direction Strategies
156
+
157
+ Controls how SVD components are distributed to lora_A and lora_B:
158
+
159
+ - `ArBr`: Alternating distribution - A takes odd indices, B takes even indices
160
+ - `A2rBr`: A takes second half, B takes first half
161
+ - `ArB2r` (default): A takes first half, B takes second half - typically performs best
162
+ - `random`: Random selection of singular vectors
163
+
164
+ ### Scaling Strategies
165
+
166
+ Controls initialization magnitude:
167
+
168
+ - `stable` (default): Conservative scaling using stable_gamma parameter for stable training
169
+ - `weight_svd`: Scales based on SVD of original weights for better alignment
170
+ - `gd_scale`: Scales based on gradient descent step size
171
+ - `unit`: Unit scaling (no adjustment)
172
+
173
+ ## Use the model on 🤗
174
+
175
+ You can load and use the model as any other 🤗 models:
176
+
177
+ ```python
178
+ from transformers import AutoModelForCausalLM
179
+ from peft import PeftModel
180
+
181
+ model = AutoModelForCausalLM.from_pretrained("gpt2")
182
+ model = PeftModel.from_pretrained(model, "path/to/lora_ga_output")
183
+ ```
184
+
185
+ ## LoRA-GA vs. LoRA
186
+
187
+ Key differences and advantages:
188
+
189
+ 1. **Faster Convergence**: LoRA-GA achieves 2-4x faster convergence compared to standard LoRA due to gradient-aligned initialization.
190
+
191
+ 2. **Same Final Performance**: LoRA-GA maintains the same or better final performance as standard LoRA.
192
+
193
+ 3. **Initialization Overhead**: LoRA-GA requires a gradient estimation phase (typically 1-2 minutes for 64 iterations), but this is quickly amortized during training.
194
+
195
+ 4. **Orthogonal to Other Methods**: LoRA-GA can be combined with DoRA, LoRA+, quantization, and other LoRA enhancements.
196
+
197
+ ## API Design
198
+
199
+ LoRA-GA follows the same pattern as PiSSA, OLoRA, and CorDA:
200
+
201
+ 1. **Preprocessing**: Use `preprocess_loraga(model, lora_config, train_step)` to estimate gradients and attach them to model layers
202
+ 2. **Configuration**: Use `LoraGAConfig` as a sub-config within `LoraConfig` with `init_lora_weights="lora_ga"`
203
+ 3. **Initialization**: Call `get_peft_model()` after preprocessing to create the PEFT model with LoRA-GA initialization
204
+ 4. **Training**: Train normally using Hugging Face Trainer or your own training loop
205
+ 5. **Saving**: Use standard `save_pretrained()` to save the trained adapter
206
+
207
+ ## Using LoRA-GA with Quantized Models
208
+
209
+ LoRA-GA requires full-precision gradients during preprocessing. For quantized models (e.g., BitsAndBytes 4-bit/8-bit), use a two-stage workflow:
210
+
211
+ ### Step 1: Estimate gradients with full-precision model
212
+
213
+ ```python
214
+ import torch
215
+ from transformers import AutoModelForCausalLM, BitsAndBytesConfig
216
+ from peft import LoraConfig, get_peft_model
217
+ from peft.tuners.lora import LoraGAConfig, preprocess_loraga
218
+
219
+ # Load model in full precision for gradient estimation
220
+ model = AutoModelForCausalLM.from_pretrained(
221
+ "meta-llama/Llama-2-7b-hf",
222
+ torch_dtype=torch.bfloat16,
223
+ device_map="auto"
224
+ )
225
+
226
+ # Configure LoRA-GA
227
+ lora_config = LoraConfig(
228
+ r=8,
229
+ target_modules=["q_proj", "v_proj"],
230
+ init_lora_weights="lora_ga",
231
+ lora_ga_config=LoraGAConfig(direction="ArB2r", scale="stable"),
232
+ )
233
+
234
+ # Define your train_step (same as before)
235
+ def train_step():
236
+ for _ in range(64):
237
+ # Your training logic here
238
+ outputs = model(**batch)
239
+ loss = outputs.loss
240
+ loss.backward()
241
+
242
+ # Estimate and cache gradients
243
+ preprocess_loraga(model, lora_config, train_step, cache_file="loraga_gradients.pt")
244
+
245
+ # Clean up full-precision model
246
+ del model
247
+ torch.cuda.empty_cache()
248
+ ```
249
+
250
+ ### Step 2: Load quantized model and apply LoRA-GA
251
+
252
+ ```python
253
+ # Load model with quantization
254
+ quantization_config = BitsAndBytesConfig(load_in_4bit=True)
255
+ model = AutoModelForCausalLM.from_pretrained(
256
+ "meta-llama/Llama-2-7b-hf",
257
+ quantization_config=quantization_config,
258
+ device_map="auto"
259
+ )
260
+
261
+ # Apply LoRA-GA - gradients will be loaded from cache automatically
262
+ peft_model = get_peft_model(model, lora_config)
263
+
264
+ # Train normally
265
+ trainer.train()
266
+ ```
267
+
268
+ **Key points:**
269
+ - Gradient estimation must use a non-quantized model (full precision or bfloat16/float16)
270
+ - Cache gradients with `cache_file` parameter to avoid re-computation
271
+ - Cached gradients are automatically loaded when applying LoRA to the quantized model
272
+ - This workflow allows memory-efficient training with quantized models while benefiting from LoRA-GA's faster convergence
273
+
274
+ ## Tips
275
+
276
+ - **Gradient Estimation**: 64-128 iterations is typically sufficient. More iterations provide more accurate estimation but increase initialization time.
277
+
278
+ - **Batch Size**: Use smaller batch sizes (2-4) for gradient estimation to maximize gradient diversity.
279
+
280
+ - **Direction and Scale**: The default `direction="ArB2r"` and `scale="stable"` work well in most cases.
281
+
282
+ - **User-Defined Callback**: The `train_step` callback gives you full control over the gradient estimation process. You can customize batching, loss functions, and more.
283
+
284
+ - **Gradient Accumulation**: Do NOT call `model.zero_grad()` or `optimizer.zero_grad()` inside your `train_step` callback. LoRA-GA relies on PyTorch's natural gradient accumulation across iterations.
285
+
286
+ ## Citation
287
+
288
+ ```bibtex
289
+ @article{wang2024loraga,
290
+ title={LoRA-GA: Low-Rank Adaptation with Gradient Approximation},
291
+ author={Wang, Shaowen and Zhu, Linxi and Ding, Hengyuan and Liu, Jiaqi and Chen, Jiaming and Zhu, Kaikai and Pang, Wei and Zhu, Jun and You, Yang},
292
+ journal={arXiv preprint arXiv:2407.05000},
293
+ year={2024}
294
+ }
295
+ ```
tasks/tasksmith-c488fc138ba1/tests/source/examples/lora_ga_finetuning/lora_ga_finetuning.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Example script demonstrating LoRA-GA (Low-Rank Adaptation with Gradient Approximation) fine-tuning.
4
+
5
+ LoRA-GA improves upon standard LoRA by using gradient information during initialization,
6
+ achieving 2-4x faster convergence while maintaining the same final performance.
7
+
8
+ This example shows:
9
+ 1. How to define a train_step callback for gradient estimation
10
+ 2. How to use preprocess_loraga for LoRA-GA initialization
11
+ 3. Training with standard Hugging Face Trainer
12
+ 4. Saving the trained adapter
13
+ """
14
+
15
+ import argparse
16
+ import os
17
+
18
+ import torch
19
+ from datasets import load_dataset
20
+ from torch.utils.data import DataLoader
21
+ from transformers import (
22
+ AutoModelForCausalLM,
23
+ AutoTokenizer,
24
+ DataCollatorForLanguageModeling,
25
+ Trainer,
26
+ TrainingArguments,
27
+ default_data_collator,
28
+ )
29
+
30
+ from peft import LoraConfig, get_peft_model
31
+ from peft.tuners.lora import LoraGAConfig, preprocess_loraga
32
+
33
+
34
+ def parse_args():
35
+ parser = argparse.ArgumentParser(description="LoRA-GA fine-tuning example")
36
+
37
+ # Model arguments
38
+ parser.add_argument("--base_model", type=str, default="gpt2", help="Base model name or path")
39
+ parser.add_argument("--output_dir", type=str, default="./lora_ga_output", help="Output directory")
40
+
41
+ # Dataset arguments
42
+ parser.add_argument("--dataset_name", type=str, default="wikitext", help="Dataset name")
43
+ parser.add_argument("--dataset_config", type=str, default="wikitext-2-raw-v1", help="Dataset configuration")
44
+ parser.add_argument("--max_length", type=int, default=512, help="Maximum sequence length")
45
+
46
+ # LoRA-GA configuration
47
+ parser.add_argument("--r", type=int, default=8, help="LoRA rank")
48
+ parser.add_argument("--lora_alpha", type=int, default=16, help="LoRA alpha")
49
+ parser.add_argument("--lora_dropout", type=float, default=0.1, help="LoRA dropout")
50
+ parser.add_argument(
51
+ "--target_modules",
52
+ type=str,
53
+ nargs="+",
54
+ default=["c_attn"],
55
+ help="Target modules for LoRA (e.g., c_attn for GPT-2)",
56
+ )
57
+ parser.add_argument(
58
+ "--direction",
59
+ type=str,
60
+ default="ArB2r",
61
+ choices=["ArBr", "A2rBr", "ArB2r", "random"],
62
+ help="Direction strategy for LoRA-GA initialization",
63
+ )
64
+ parser.add_argument(
65
+ "--scale",
66
+ type=str,
67
+ default="stable",
68
+ choices=["stable", "weight_svd", "gd_scale", "unit"],
69
+ help="Scaling strategy for LoRA-GA initialization",
70
+ )
71
+ parser.add_argument("--stable_gamma", type=int, default=16, help="Gamma for stable scaling")
72
+
73
+ # Gradient estimation arguments
74
+ parser.add_argument(
75
+ "--grad_estimate_iters", type=int, default=64, help="Number of iterations for gradient estimation"
76
+ )
77
+ parser.add_argument("--grad_estimate_batch_size", type=int, default=2, help="Batch size for gradient estimation")
78
+
79
+ # Training arguments
80
+ parser.add_argument("--num_epochs", type=int, default=3, help="Number of training epochs")
81
+ parser.add_argument("--batch_size", type=int, default=8, help="Training batch size")
82
+ parser.add_argument("--learning_rate", type=float, default=3e-5, help="Learning rate")
83
+ parser.add_argument("--warmup_steps", type=int, default=100, help="Warmup steps")
84
+ parser.add_argument("--logging_steps", type=int, default=10, help="Logging steps")
85
+ parser.add_argument("--save_steps", type=int, default=500, help="Save checkpoint steps")
86
+ parser.add_argument("--eval_steps", type=int, default=500, help="Evaluation steps")
87
+
88
+ # Other arguments
89
+ parser.add_argument("--seed", type=int, default=42, help="Random seed")
90
+
91
+ return parser.parse_args()
92
+
93
+
94
+ def prepare_dataset(dataset_name, dataset_config, tokenizer, max_length):
95
+ """Load and prepare the dataset."""
96
+ print(f"\nLoading dataset: {dataset_name}/{dataset_config}")
97
+ dataset = load_dataset(dataset_name, dataset_config)
98
+
99
+ def tokenize_function(examples):
100
+ # For causal language modeling, we tokenize and set labels = input_ids
101
+ result = tokenizer(
102
+ examples["text"], padding="max_length", truncation=True, max_length=max_length, return_tensors="pt"
103
+ )
104
+ result["labels"] = result["input_ids"].clone()
105
+ return result
106
+
107
+ # Tokenize the dataset
108
+ print("Tokenizing dataset...")
109
+ tokenized_datasets = dataset.map(
110
+ tokenize_function, batched=True, remove_columns=dataset["train"].column_names, desc="Tokenizing"
111
+ )
112
+
113
+ return tokenized_datasets
114
+
115
+
116
+ def main():
117
+ args = parse_args()
118
+
119
+ # Set random seed
120
+ torch.manual_seed(args.seed)
121
+
122
+ # Create output directory
123
+ os.makedirs(args.output_dir, exist_ok=True)
124
+
125
+ # Load tokenizer and model
126
+ print(f"\nLoading model: {args.base_model}")
127
+ tokenizer = AutoTokenizer.from_pretrained(args.base_model)
128
+ tokenizer.pad_token = tokenizer.eos_token
129
+
130
+ model = AutoModelForCausalLM.from_pretrained(args.base_model)
131
+
132
+ # Prepare dataset
133
+ tokenized_datasets = prepare_dataset(args.dataset_name, args.dataset_config, tokenizer, args.max_length)
134
+
135
+ # Create LoRA-GA configuration
136
+ print("\nCreating LoRA-GA configuration...")
137
+ lora_ga_config = LoraGAConfig(
138
+ direction=args.direction,
139
+ scale=args.scale,
140
+ stable_gamma=args.stable_gamma,
141
+ )
142
+
143
+ lora_config = LoraConfig(
144
+ r=args.r,
145
+ lora_alpha=args.lora_alpha,
146
+ lora_dropout=args.lora_dropout,
147
+ target_modules=args.target_modules,
148
+ bias="none",
149
+ task_type="CAUSAL_LM",
150
+ init_lora_weights="lora_ga",
151
+ lora_ga_config=lora_ga_config,
152
+ )
153
+ print(f" Direction: {args.direction}")
154
+ print(f" Scale: {args.scale}")
155
+ print(f" Rank: {args.r}, Alpha: {args.lora_alpha}")
156
+
157
+ # ===== GRADIENT ESTIMATION PHASE =====
158
+ print("\n" + "=" * 70)
159
+ print("GRADIENT ESTIMATION PHASE")
160
+ print("=" * 70)
161
+ print(f"Estimating gradients over {args.grad_estimate_iters} iterations...")
162
+ print("This allows LoRA-GA to initialize adapters aligned with full fine-tuning.")
163
+
164
+ # Prepare gradient estimation dataloader
165
+ train_dataset = tokenized_datasets["train"]
166
+
167
+ # Create a simple DataLoader for gradient estimation
168
+ grad_dataloader = DataLoader(
169
+ train_dataset,
170
+ batch_size=args.grad_estimate_batch_size,
171
+ shuffle=True,
172
+ collate_fn=default_data_collator,
173
+ )
174
+
175
+ # Move model to GPU if available
176
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
177
+ model = model.to(device)
178
+ model.train()
179
+
180
+ # Define train_step callback
181
+ def train_step():
182
+ """Run forward and backward passes for gradient estimation."""
183
+ grad_iter = iter(grad_dataloader)
184
+ for _ in range(args.grad_estimate_iters):
185
+ batch = next(grad_iter)
186
+
187
+ # Move batch to device
188
+ batch = {k: v.to(device) for k, v in batch.items()}
189
+
190
+ # Forward pass
191
+ outputs = model(**batch)
192
+ loss = outputs.loss
193
+
194
+ # Backward pass
195
+ loss.backward()
196
+
197
+ # Preprocess with LoRA-GA
198
+ print("Running gradient estimation...")
199
+ preprocess_loraga(model, lora_config, train_step)
200
+ print("✓ Gradient estimation complete!")
201
+
202
+ # ===== MODEL INITIALIZATION PHASE =====
203
+ print("\n" + "=" * 70)
204
+ print("LORA-GA INITIALIZATION PHASE")
205
+ print("=" * 70)
206
+ print("Initializing LoRA adapters with gradient information...")
207
+
208
+ # Create PEFT model with LoRA-GA initialization
209
+ peft_model = get_peft_model(model, lora_config)
210
+
211
+ # Print trainable parameters
212
+ peft_model.print_trainable_parameters()
213
+
214
+ # ===== TRAINING PHASE =====
215
+ print("\n" + "=" * 70)
216
+ print("TRAINING PHASE")
217
+ print("=" * 70)
218
+ print("Starting training with LoRA-GA initialized adapters...")
219
+ print("LoRA-GA achieves 2-4x faster convergence compared to random initialization!\n")
220
+
221
+ # Setup training arguments
222
+ training_args = TrainingArguments(
223
+ output_dir=args.output_dir,
224
+ num_train_epochs=args.num_epochs,
225
+ per_device_train_batch_size=args.batch_size,
226
+ per_device_eval_batch_size=args.batch_size,
227
+ learning_rate=args.learning_rate,
228
+ warmup_steps=args.warmup_steps,
229
+ logging_steps=args.logging_steps,
230
+ save_steps=args.save_steps,
231
+ eval_steps=args.eval_steps,
232
+ eval_strategy="steps",
233
+ save_total_limit=2,
234
+ load_best_model_at_end=True,
235
+ report_to="none",
236
+ seed=args.seed,
237
+ )
238
+
239
+ # Data collator
240
+ data_collator = DataCollatorForLanguageModeling(tokenizer, mlm=False)
241
+
242
+ # Create Trainer
243
+ trainer = Trainer(
244
+ model=peft_model,
245
+ args=training_args,
246
+ train_dataset=tokenized_datasets["train"],
247
+ eval_dataset=tokenized_datasets["validation"],
248
+ data_collator=data_collator,
249
+ )
250
+
251
+ # Train the model
252
+ trainer.train()
253
+
254
+ # ===== SAVING PHASE =====
255
+ print("\n" + "=" * 70)
256
+ print("SAVING PHASE")
257
+ print("=" * 70)
258
+ print("Saving trained adapter...")
259
+
260
+ # Save the trained adapter
261
+ peft_model.save_pretrained(args.output_dir)
262
+
263
+ print(f"\n✓ Training complete! Model saved to: {args.output_dir}")
264
+ print("\nSaved files:")
265
+ print(" - adapter_model.safetensors: Trained adapter weights")
266
+ print(" - adapter_config.json: Configuration file")
267
+
268
+ print("\n" + "=" * 70)
269
+ print("DONE!")
270
+ print("=" * 70)
271
+ print("\nYou can now use the trained adapter with:")
272
+ print(" from peft import PeftModel")
273
+ print(" from transformers import AutoModelForCausalLM")
274
+ print(f" model = AutoModelForCausalLM.from_pretrained('{args.base_model}')")
275
+ print(f" model = PeftModel.from_pretrained(model, '{args.output_dir}')")
276
+
277
+
278
+ if __name__ == "__main__":
279
+ main()
tasks/tasksmith-c488fc138ba1/tests/source/examples/lorafa_finetune/README.md ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LoRA-FA: Memory-efficient Low-rank Adaptation for Large Language Models Fine-tuning
2
+
3
+ ## Introduction
4
+
5
+ [LoRA-FA](https://huggingface.co/papers/2308.03303) is a noval Parameter-efficient Fine-tuning method, which freezes the projection down layer (matrix A) during LoRA training process and thus lead to less accelerator memory consumption by eliminating the need for storing the activations of input tensors (X). Furthermore, LoRA-FA narrows the gap between the update amount of pre-trained weights when using the low-rank fine-tuning method and the full fine-tuning method. In conclusion, LoRA-FA reduces the memory consumption and leads to superior performance compared to vanilla LoRA.
6
+
7
+ ## Quick start
8
+
9
+ ```python
10
+ import torch
11
+ from peft import LoraConfig, get_peft_model
12
+ from peft.optimizers import create_lorafa_optimizer
13
+ from transformers import AutoTokenizer, AutoModelForCausalLM, Trainer
14
+ from datasets import load_dataset
15
+
16
+ model = AutoModelForCausalLM.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct")
17
+ tokenizer = AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct")
18
+ dataset = load_dataset("timdettmers/openassistant-guanaco", split="train")
19
+
20
+ lora_rank = 16
21
+ lora_alpha = 32
22
+
23
+ lora_config = LoraConfig(
24
+ r=lora_rank,
25
+ lora_alpha=lora_alpha,
26
+ bias="none",
27
+ )
28
+ peft_model = get_peft_model(model, lora_config)
29
+ optimizer = create_lorafa_optimizer(
30
+ model=peft_model,
31
+ r=lora_rank,
32
+ lora_alpha=lora_alpha,
33
+ lr=7e-5,
34
+ )
35
+ # you can also use scheduler, we recommend get_cosine_schedule_with_warmup from transformers
36
+ # for better model performance
37
+ scheduler = None
38
+
39
+ trainer = transformers.Trainer(
40
+ model=peft_model,
41
+ train_dataset=dataset,
42
+ dataset_text_field="text",
43
+ max_length=2048,
44
+ processing_class=tokenizer,
45
+ optimizers=(optimizer, None),
46
+ )
47
+ trainer.train()
48
+ peft_model.save_pretrained("lorafa-llama-3-8b-inst")
49
+ ```
50
+
51
+ The only change in your code is to pass the LoRA-FA optimizer to the trainer (if training with trainer). Do not forget `from peft.optimizers import create_lorafa_optimizer`!
52
+
53
+ ## Example
54
+
55
+ In this dir, we also provide you a simple example for fine-tuning with LoRA-FA optimizer.
56
+
57
+ ### Run on CPU, single-accelerator or multi-accelerator
58
+
59
+ This 👇 by default will load the model in peft set up with LoRA config, and train the model with LoRA-FA optimizer.
60
+
61
+ 0. CPU
62
+
63
+ You can simply run LoRA-FA as below:
64
+
65
+ ```bash
66
+ python lorafa_finetuning.py --base_model_name_or_path meta-llama/Meta-Llama-3-8B --dataset_name_or_path meta-math/MetaMathQA-40K --output_dir path/to/output --lorafa
67
+ ```
68
+
69
+ 1. Single-accelerator
70
+
71
+ Run the finetuning script on 1 accelerator:
72
+
73
+ ```bash
74
+ export CUDA_VISIBLE_DEVICES=0 # force to use CUDA GPU 0
75
+ export ZE_AFFINITY_MASK=0 # force to use Intel XPU 0
76
+
77
+ python lorafa_finetuning.py --base_model_name_or_path meta-llama/Meta-Llama-3-8B --dataset_name_or_path meta-math/MetaMathQA-40K --output_dir path/to/output --lorafa
78
+ ```
79
+
80
+ 2. Multi-accelerator
81
+
82
+ LoRA-FA can also be run on multi-accelerator, with 🤗 Accelerate:
83
+
84
+ ```bash
85
+ export CUDA_VISIBLE_DEVICES=0,1,2,3 # force to use CUDA GPU 0,1,2,3
86
+ export ZE_AFFINITY_MASK=0,1,2,3 # force to use Intel XPU 0,1,2,3
87
+
88
+ accelerate launch lorafa_finetuning.py --base_model_name_or_path meta-llama/Meta-Llama-3-8B --dataset_name_or_path meta-math/MetaMathQA-40K --output_dir path/to/output --lorafa
89
+ ```
90
+
91
+ The `accelerate launch` will automatically configure multi-accelerator for you. You can also utilize `accelerate launch` in single-accelerator scenario.
92
+
93
+ ### Use the model from 🤗
94
+ You can load and use the model as any other 🤗 models.
95
+ ```python
96
+ from transformers import AutoModel
97
+ model = AutoModel.from_pretrained("meta-llama/Llama-2-7b-chat-hf")
98
+ ```
99
+
100
+ ## Best practice in fine-tuning Llama using LoRA-FA: the hyper-params
101
+
102
+ Sometimes, achieving optimal LoRA fine-tuning can be challenging due to the larger number of hyperparameters to consider compared to full fine-tuning. For instance, not only do we need to adjust the commonly used learning rate, but the ideal LoRA rank may also vary depending on the specific model and task. Additionally, there are other factors to consider, such as LoRA alpha and sequence length. To assist with this, we have created a repository of reproducible best practices in the [LoRA-FA examples](https://github.com/AaronZLT/lorafa) for reference. This resource showcases the optimal LoRA-FA fine-tuning hyperparameters for different models across various datasets. By doing so, we significantly reduce the time and effort spent on hyperparameter tuning, and it may also provide insights for tuning other training hyperparameters. We encourage you to experiment and fine-tune on your own downstream tasks as well.
103
+
104
+ ## LoRA-FA's advantages and limitations
105
+
106
+ By eliminating the activation of adapter A, LoRA-FA uses less memory for fine-tuning compared to LoRA. For instance, when fine-tuning Llama-2-7b-chat-hf with a batch size of 8 and a sequence length of 1024, LoRA-FA requires 36GB of memory to store activations. This allows it to run successfully on an 80GB accelerator. In contrast, LoRA requires at least 60GB of memory for activations, leading to an Out of Memory (OOM) error. Additionally, the memory consumption of LoRA-FA is not sensitive to the rank, allowing for performance improvements by increasing the LoRA rank without additional memory usage. LoRA-FA further narrows the performance gap with Full-FT by minimizing the discrepancy between the low-rank gradient and the full gradient, enabling it to achieve performance that is on par with or even superior to vanilla LoRA.
107
+
108
+ Despite its advantages, LoRA-FA is inherently limited by its low-rank approximation nature and potential issues with catastrophic forgetting. The gradient approximation can impact training throughput. Addressing these limitations, especially in terms of approximation accuracy and forgetting phenomena, presents a promising direction for future research.
109
+
110
+ ## Citation
111
+ ```
112
+ @misc{zhang2023lorafamemoryefficientlowrankadaptation,
113
+ title={LoRA-FA: Memory-efficient Low-rank Adaptation for Large Language Models Fine-tuning},
114
+ author={Longteng Zhang and Lin Zhang and Shaohuai Shi and Xiaowen Chu and Bo Li},
115
+ year={2023},
116
+ eprint={2308.03303},
117
+ archivePrefix={arXiv},
118
+ primaryClass={cs.CL},
119
+ url={https://huggingface.co/papers/2308.03303},
120
+ }
121
+ ```
tasks/tasksmith-c488fc138ba1/tests/source/examples/lorafa_finetune/lorafa_finetuning.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import os
16
+ from typing import Optional
17
+
18
+ import torch
19
+ from datasets import load_dataset
20
+ from transformers import (
21
+ AutoModelForCausalLM,
22
+ AutoTokenizer,
23
+ BitsAndBytesConfig,
24
+ DataCollatorForLanguageModeling,
25
+ Trainer,
26
+ TrainingArguments,
27
+ )
28
+
29
+ from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
30
+ from peft.optimizers import create_lorafa_optimizer
31
+
32
+
33
+ def train_model(
34
+ base_model_name_or_path: str,
35
+ dataset_name_or_path: str,
36
+ output_dir: str,
37
+ batch_size: int,
38
+ num_epochs: int,
39
+ lr: float,
40
+ cutoff_len: int,
41
+ quantize: bool,
42
+ eval_step: int,
43
+ save_step: int,
44
+ lora_rank: int,
45
+ lora_alpha: int,
46
+ lora_dropout: float,
47
+ lora_target_modules: Optional[str],
48
+ lorafa: bool,
49
+ ):
50
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
51
+
52
+ is_bf16_supported = False
53
+ device_map = "cpu"
54
+ if torch.cuda.is_available():
55
+ is_bf16_supported = torch.cuda.is_bf16_supported()
56
+ device_map = "cuda"
57
+ elif torch.xpu.is_available():
58
+ is_bf16_supported = torch.xpu.is_bf16_supported()
59
+ device_map = "xpu"
60
+ compute_dtype = torch.bfloat16 if is_bf16_supported else torch.float16
61
+
62
+ # load tokenizer
63
+ tokenizer = AutoTokenizer.from_pretrained(base_model_name_or_path)
64
+
65
+ # load model
66
+ if quantize:
67
+ model = AutoModelForCausalLM.from_pretrained(
68
+ base_model_name_or_path,
69
+ quantization_config=BitsAndBytesConfig(
70
+ load_in_4bit=True,
71
+ bnb_4bit_compute_dtype=compute_dtype,
72
+ bnb_4bit_use_double_quant=False,
73
+ bnb_4bit_quant_type="nf4",
74
+ ),
75
+ dtype=compute_dtype,
76
+ device_map=device_map,
77
+ )
78
+ # setup for quantized training
79
+ model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=True)
80
+ else:
81
+ model = AutoModelForCausalLM.from_pretrained(
82
+ base_model_name_or_path, dtype=compute_dtype, device_map=device_map
83
+ )
84
+
85
+ # LoRA config for the PEFT model
86
+ if lora_target_modules is not None:
87
+ if lora_target_modules == "all-linear":
88
+ target_modules = "all-linear"
89
+ else:
90
+ target_modules = lora_target_modules.split(",")
91
+ else:
92
+ target_modules = ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
93
+
94
+ lora_config = LoraConfig(
95
+ r=lora_rank,
96
+ lora_alpha=lora_alpha,
97
+ target_modules=target_modules,
98
+ lora_dropout=lora_dropout,
99
+ bias="none",
100
+ )
101
+
102
+ # get the peft model with LoRA config
103
+ model = get_peft_model(model, lora_config)
104
+
105
+ tokenizer.pad_token = tokenizer.eos_token
106
+
107
+ # Load the dataset
108
+ dataset = load_dataset(dataset_name_or_path)
109
+
110
+ def tokenize_function(examples):
111
+ inputs = tokenizer(examples["query"], padding="max_length", truncation=True, max_length=cutoff_len)
112
+ outputs = tokenizer(examples["response"], padding="max_length", truncation=True, max_length=cutoff_len)
113
+ inputs["labels"] = outputs["input_ids"].copy()
114
+ return inputs
115
+
116
+ # Tokenize the dataset and prepare for training
117
+ tokenized_datasets = dataset.map(tokenize_function, batched=True, remove_columns=dataset["train"].column_names)
118
+ dataset = tokenized_datasets["train"].train_test_split(test_size=0.1, shuffle=True, seed=42)
119
+ train_dataset = dataset["train"]
120
+ eval_dataset = dataset["test"]
121
+
122
+ # Data collator to dynamically pad the batched examples
123
+ data_collator = DataCollatorForLanguageModeling(tokenizer, mlm=False)
124
+
125
+ # Define training arguments
126
+ training_args = TrainingArguments(
127
+ output_dir=output_dir,
128
+ num_train_epochs=num_epochs,
129
+ per_device_train_batch_size=batch_size,
130
+ per_device_eval_batch_size=batch_size,
131
+ warmup_steps=100,
132
+ weight_decay=0.01,
133
+ logging_dir="./logs",
134
+ logging_steps=eval_step,
135
+ save_steps=save_step,
136
+ save_total_limit=2,
137
+ gradient_accumulation_steps=1,
138
+ bf16=compute_dtype == torch.bfloat16,
139
+ fp16=compute_dtype == torch.float16,
140
+ learning_rate=lr,
141
+ )
142
+
143
+ # Here we initialize the LoRA-FA Optimizer
144
+ # After this, all adapter A will be fixed, only adapter B will be trainable
145
+ if lorafa:
146
+ optimizer = create_lorafa_optimizer(
147
+ model=model, r=lora_rank, lora_alpha=lora_alpha, lr=lr, weight_decay=training_args.weight_decay
148
+ )
149
+ trainer = Trainer(
150
+ model=model,
151
+ args=training_args,
152
+ train_dataset=train_dataset,
153
+ eval_dataset=eval_dataset,
154
+ data_collator=data_collator,
155
+ optimizers=(optimizer, None),
156
+ )
157
+ else:
158
+ trainer = Trainer(
159
+ model=model,
160
+ args=training_args,
161
+ train_dataset=train_dataset,
162
+ eval_dataset=eval_dataset,
163
+ data_collator=data_collator,
164
+ )
165
+
166
+ # Start model training
167
+ trainer.train()
168
+
169
+ # Save the model and tokenizer locally
170
+ model.save_pretrained(output_dir)
171
+ tokenizer.save_pretrained(output_dir)
172
+
173
+
174
+ if __name__ == "__main__":
175
+ import argparse
176
+
177
+ parser = argparse.ArgumentParser(description="Fine-tune Meta-Llama-3-8B-Instruct with LoRA-FA and PEFT")
178
+ parser.add_argument(
179
+ "--base_model_name_or_path",
180
+ type=str,
181
+ default="meta-llama/Meta-Llama-3-8B-Instruct",
182
+ help="Base model name or path",
183
+ )
184
+ parser.add_argument(
185
+ "--dataset_name_or_path", type=str, default="meta-math/MetaMathQA-40K", help="Dataset name or path"
186
+ )
187
+ parser.add_argument("--output_dir", type=str, help="Output directory for the fine-tuned model")
188
+ parser.add_argument("--batch_size", type=int, default=1, help="Batch size")
189
+ parser.add_argument("--num_epochs", type=int, default=3, help="Number of training epochs")
190
+ parser.add_argument("--lr", type=float, default=7e-5, help="Learning rate")
191
+ parser.add_argument("--cutoff_len", type=int, default=1024, help="Cutoff length for tokenization")
192
+ parser.add_argument("--quantize", action="store_true", help="Use quantization")
193
+ parser.add_argument("--eval_step", type=int, default=10, help="Evaluation step interval")
194
+ parser.add_argument("--save_step", type=int, default=100, help="Save step interval")
195
+ parser.add_argument("--lora_rank", type=int, default=16, help="LoRA rank")
196
+ parser.add_argument("--lora_alpha", type=int, default=32, help="LoRA alpha")
197
+ parser.add_argument("--lora_dropout", type=float, default=0.05, help="LoRA dropout rate")
198
+ parser.add_argument(
199
+ "--lora_target_modules", type=str, default=None, help="Comma-separated list of target modules for LoRA"
200
+ )
201
+ parser.add_argument("--lorafa", action="store_true", help="Use LoRA-FA Optimizer")
202
+
203
+ args = parser.parse_args()
204
+
205
+ train_model(
206
+ base_model_name_or_path=args.base_model_name_or_path,
207
+ dataset_name_or_path=args.dataset_name_or_path,
208
+ output_dir=args.output_dir,
209
+ batch_size=args.batch_size,
210
+ num_epochs=args.num_epochs,
211
+ lr=args.lr,
212
+ cutoff_len=args.cutoff_len,
213
+ quantize=args.quantize,
214
+ eval_step=args.eval_step,
215
+ save_step=args.save_step,
216
+ lora_rank=args.lora_rank,
217
+ lora_alpha=args.lora_alpha,
218
+ lora_dropout=args.lora_dropout,
219
+ lora_target_modules=args.lora_target_modules,
220
+ lorafa=args.lorafa,
221
+ )
tasks/tasksmith-c488fc138ba1/tests/source/examples/miss_finetuning/README.md ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MiSS: Balancing LoRA Performance and Efficiency with Simple Shard Sharing
2
+ ## Introduction ([Paper](https://huggingface.co/papers/2409.15371), [code](https://github.com/JL-er/MiSS))
3
+ MiSS (Matrix Shard Sharing) is a novel PEFT method that adopts a low-rank structure, requires only a single trainable matrix, and introduces a new update mechanism distinct from LoRA, achieving an excellent balance between performance and efficiency.
4
+
5
+
6
+ ## Quick Start
7
+ ```python
8
+ import torch
9
+ from peft import MissConfig, get_peft_model
10
+ from transformers import AutoTokenizer, AutoModelForCausalLM
11
+ from trl import SFTConfig, SFTTrainer
12
+ from datasets import load_dataset
13
+
14
+ model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf", dtype=torch.bfloat16, device_map="auto")
15
+ tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
16
+ tokenizer.pad_token_id = tokenizer.eos_token_id
17
+
18
+ miss_config = MissConfig(
19
+ r = 64,
20
+ miss_dropout = 0.01
21
+ )
22
+ #bat: In this mode, you can enable nonlinear updates across different shards.
23
+ # miss_config = MissConfig(
24
+ # r = 64,
25
+ # init_weights="bat"
26
+ # )
27
+
28
+ # mini: In this mode, you can set a smaller rank to use fewer trainable parameters, but it is recommended to keep `out_features % mini_r == 0`.
29
+ # miss_config = MissConfig(
30
+ # r = 64,
31
+ # init_weights="mini",
32
+ # mini_r = 8
33
+ # )
34
+ peft_model = get_peft_model(model, miss_config)
35
+
36
+ peft_model.print_trainable_parameters()
37
+
38
+ dataset = load_dataset("imdb", split="train[:1%]")
39
+
40
+ training_args = SFTConfig(dataset_text_field="text", max_length=128)
41
+ trainer = SFTTrainer(
42
+ model=peft_model,
43
+ args=training_args,
44
+ train_dataset=dataset,
45
+ processing_class=tokenizer,
46
+ )
47
+ trainer.train()
48
+ peft_model.save_pretrained("miss-llama-2-7b")
49
+ ```
50
+
51
+
52
+ To utilize the fine-tuned MiSS modules, simply run the following command:
53
+ ```python
54
+ import torch
55
+ from peft import PeftModel
56
+ from transformers import AutoModelForCausalLM
57
+
58
+ model = AutoModelForCausalLM.from_pretrained(
59
+ "meta-llama/Llama-2-7b-hf", dtype=torch.bfloat16, device_map="auto"
60
+ )
61
+ peft_model = PeftModel.from_pretrained(model, "miss-llama-2-7b")
62
+ ```
63
+
64
+ ## Advanced Usage
65
+
66
+ ### Fine-tune
67
+ ```shell
68
+ #Bat performs better than MiSS, but it uses more memory and is twice as slow. If you want to use the Bat method, you only need to add the parameter init_weights="bat".
69
+ python miss_finetuning.py \
70
+ --base_model_name_or_path meta-llama/Llama-2-7b-hf \
71
+ --output_dir output/miss-llama-2-7b-metamath-10k \
72
+ --miss_r 64 \
73
+ --miss_dropout 0.01 \
74
+ --init_weights True \
75
+ --bits bf16 \
76
+ --data_path meta-math/MetaMathQA \
77
+ --dataset_split train[:100000] \
78
+ --dataset_field query response \
79
+ --bf16 True \
80
+ --num_train_epochs 1 \
81
+ --per_device_train_batch_size 2 \
82
+ --gradient_accumulation_steps 8 \
83
+ --save_strategy "steps" \
84
+ --save_steps 1000 \
85
+ --save_total_limit 1 \
86
+ --logging_steps 1 \
87
+ --learning_rate 2e-5 \
88
+ --weight_decay 0. \
89
+ --warmup_steps 0.03 \
90
+ --tf32 True \
91
+ --report_to none
92
+ ```
93
+
94
+
95
+
96
+ # Citation
97
+ ```bib
98
+ @misc{kang2025missrevisitingtradeofflora,
99
+ title={MiSS: Revisiting the Trade-off in LoRA with an Efficient Shard-Sharing Structure},
100
+ author={Jiale Kang and Qingyu Yin},
101
+ year={2025},
102
+ eprint={2409.15371},
103
+ archivePrefix={arXiv},
104
+ primaryClass={cs.CL},
105
+ url={https://arxiv.org/abs/2409.15371},
106
+ }
tasks/tasksmith-c488fc138ba1/tests/source/examples/miss_finetuning/miss_finetuning.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025-present the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import os
16
+ from dataclasses import dataclass, field
17
+ from typing import Literal, Optional
18
+
19
+ import torch
20
+ from datasets import load_dataset
21
+ from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser
22
+ from trl import SFTConfig, SFTTrainer
23
+
24
+ from peft import MissConfig, get_peft_model
25
+
26
+
27
+ @dataclass
28
+ class ScriptArguments(SFTConfig):
29
+ # model configs
30
+ base_model_name_or_path: Optional[str] = field(
31
+ default=None, metadata={"help": "The name or path of the fp32/16 base model."}
32
+ )
33
+ bits: str = field(default="bf16", metadata={"help": "(`['bf16', 'fp16', fp32]`)"})
34
+ init_weights: Literal[True, "bat"] = field(
35
+ default=True,
36
+ metadata={
37
+ "help": (
38
+ "True -> MiSS efficience and balance; `bat` -> Bat, `mini` -> smaller MiSS efficience and balance"
39
+ ),
40
+ },
41
+ )
42
+ miss_r: int = field(default=16)
43
+ miss_dropout: float = field(default=0.0)
44
+ merge_and_save: bool = field(default=False)
45
+ # dataset configs
46
+ data_path: str = field(default="imdb", metadata={"help": "Path to the training data."})
47
+ dataset_split: str = field(default="train[:1%]", metadata={"help": "(`['train', 'test', 'eval']`):"})
48
+ dataset_field: list[str] = field(default=None, metadata={"help": "Fields of dataset input and output."})
49
+
50
+
51
+ parser = HfArgumentParser(ScriptArguments)
52
+ script_args = parser.parse_args_into_dataclasses()[0]
53
+ print(script_args)
54
+
55
+ print(f"Load pre-processed residual model in {script_args.bits} bits.")
56
+ if script_args.bits in ["nf4", "fp4", "int8"]:
57
+ print("MiSS currently does not support quantization.")
58
+
59
+ elif script_args.base_model_name_or_path is not None:
60
+ print(f"No available pre-processed model, manually initialize a MiSS using {script_args.base_model_name_or_path}.")
61
+ model = AutoModelForCausalLM.from_pretrained(
62
+ script_args.base_model_name_or_path,
63
+ dtype=(
64
+ torch.float16
65
+ if script_args.bits == "fp16"
66
+ else (torch.bfloat16 if script_args.bits == "bf16" else torch.float32)
67
+ ),
68
+ device_map="auto",
69
+ )
70
+ tokenizer = AutoTokenizer.from_pretrained(script_args.base_model_name_or_path)
71
+ tokenizer.pad_token_id = tokenizer.eos_token_id
72
+ miss_config = MissConfig(
73
+ r=script_args.miss_r,
74
+ miss_dropout=script_args.miss_dropout,
75
+ target_modules=["q_proj", "o_proj", "k_proj", "v_proj", "gate_proj", "up_proj", "down_proj"],
76
+ bias="none",
77
+ task_type="CAUSAL_LM",
78
+ init_weights=script_args.init_weights,
79
+ )
80
+ peft_model = get_peft_model(model, miss_config)
81
+
82
+ print(peft_model)
83
+ peft_model.print_trainable_parameters()
84
+
85
+ print(f"Training MiSS with trl on the {script_args.data_path}[{script_args.dataset_split}] dataset.")
86
+ dataset = load_dataset(script_args.data_path, split=script_args.dataset_split)
87
+ dataset = dataset.map(
88
+ lambda example: {
89
+ "text": f"### USER: {example[script_args.dataset_field[0]]}\n### ASSISTANT: {example[script_args.dataset_field[1]]}"
90
+ }
91
+ )
92
+
93
+ trainer = SFTTrainer(
94
+ model=peft_model,
95
+ args=script_args,
96
+ train_dataset=dataset,
97
+ processing_class=tokenizer,
98
+ )
99
+ trainer.train()
100
+ trainer.save_state()
101
+
102
+ peft_model.save_pretrained(
103
+ os.path.join(script_args.output_dir, "miss_ft"),
104
+ )
105
+
106
+ if script_args.merge_and_save:
107
+ model = peft_model.merge_and_unload()
108
+ model.save_pretrained(os.path.join(script_args.output_dir, "miss_merged"))
109
+ tokenizer.save_pretrained(os.path.join(script_args.output_dir, "miss_merged"))
tasks/tasksmith-c488fc138ba1/tests/source/examples/monteclora_finetuning/sequence_classification_finetune_monteclora.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+
4
+ import evaluate
5
+ import numpy as np
6
+ from datasets import load_dataset
7
+ from transformers import (
8
+ AutoModelForSequenceClassification,
9
+ AutoTokenizer,
10
+ DataCollatorWithPadding,
11
+ Trainer,
12
+ TrainingArguments,
13
+ )
14
+
15
+ # Assuming MonteCLoRA is available in your local installed PEFT version
16
+ from peft import LoraConfig, MontecloraConfig, TaskType, get_peft_model
17
+ from peft.helpers import MontecloraTrainerMixin as MonteCLoRATrainerMixin
18
+ from peft.utils import infer_device
19
+
20
+
21
+ # ----------------------------------------------------------------------------
22
+ # 1. Trainer Definition
23
+ # ----------------------------------------------------------------------------
24
+ # Reuse the helper mixin so variational loss handling stays centralized.
25
+ class MonteCLoRATrainer(MonteCLoRATrainerMixin, Trainer):
26
+ pass
27
+
28
+
29
+ # ----------------------------------------------------------------------------
30
+ # 2. Metrics Helper
31
+ # ----------------------------------------------------------------------------
32
+ # GLUE/MRPC uses Accuracy and F1 score
33
+ metric = evaluate.load("glue", "mrpc")
34
+
35
+
36
+ def compute_metrics(eval_pred):
37
+ predictions, labels = eval_pred
38
+ predictions = np.argmax(predictions, axis=1)
39
+ return metric.compute(predictions=predictions, references=labels)
40
+
41
+
42
+ # ----------------------------------------------------------------------------
43
+ # 3. Main Training Function
44
+ # ----------------------------------------------------------------------------
45
+ def train_model(
46
+ base_model: str,
47
+ output_dir: str,
48
+ batch_size: int,
49
+ num_epochs: int,
50
+ learning_rate: float,
51
+ max_length: int,
52
+ device: str,
53
+ rank: int,
54
+ lora_alpha: int,
55
+ target_modules: str,
56
+ n_samples: int,
57
+ push_to_hub: bool,
58
+ hub_model_id: str,
59
+ ):
60
+ hf_token = os.getenv("HF_TOKEN") or None
61
+
62
+ # --- Device Setup ---
63
+ device = infer_device()
64
+ print(f"Using device: {device}")
65
+
66
+ # --- Load Tokenizer ---
67
+ tokenizer = AutoTokenizer.from_pretrained(base_model, token=hf_token)
68
+
69
+ # --- Load Dataset (GLUE MRPC) ---
70
+ # MRPC is a classification task (Is sentence B a paraphrase of sentence A?)
71
+ dataset = load_dataset("glue", "mrpc")
72
+
73
+ def tokenize_function(examples):
74
+ return tokenizer(
75
+ examples["sentence1"], examples["sentence2"], padding="max_length", truncation=True, max_length=max_length
76
+ )
77
+
78
+ tokenized_datasets = dataset.map(tokenize_function, batched=True)
79
+
80
+ # Remove raw text columns to avoid Trainer warnings
81
+ tokenized_datasets = tokenized_datasets.remove_columns(["sentence1", "sentence2", "idx"])
82
+ tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
83
+ tokenized_datasets.set_format("torch")
84
+
85
+ # --- Load Base Model ---
86
+ # num_labels=2 because MRPC is binary classification
87
+ model = AutoModelForSequenceClassification.from_pretrained(base_model, num_labels=2, token=hf_token)
88
+
89
+ # --- PEFT Configuration (MonteCLoRA) ---
90
+ # Note: Using n_samples to control Monte Carlo iterations
91
+ monte_clora_config = MontecloraConfig(num_samples=n_samples)
92
+ peft_config = LoraConfig(
93
+ task_type=TaskType.SEQ_CLS,
94
+ inference_mode=False,
95
+ r=rank,
96
+ lora_alpha=lora_alpha,
97
+ target_modules=target_modules.split(",") if target_modules else ["query", "value"],
98
+ bias="none",
99
+ monteclora_config=monte_clora_config,
100
+ )
101
+
102
+ # {'loss': 0.6984, 'grad_norm': 1.1652556657791138, 'learning_rate': 0.00019843478260869567, 'epoch': 0.04}
103
+ # {'loss': 0.6794, 'grad_norm': 1.619783878326416, 'learning_rate': 0.00019669565217391306, 'epoch': 0.09}
104
+ # {'loss': 0.7077, 'grad_norm': 0.7201359272003174, 'learning_rate': 0.00019495652173913045, 'epoch': 0.13}
105
+ # {'loss': 0.6822, 'grad_norm': 2.9292023181915283, 'learning_rate': 0.00019321739130434784, 'epoch': 0.17}
106
+ # {'loss': 0.6673, 'grad_norm': 0.6151084899902344, 'learning_rate': 0.0001914782608695652, 'epoch': 0.22}
107
+ # {'loss': 0.6674, 'grad_norm': 0.7056446671485901, 'learning_rate': 0.00018973913043478262, 'epoch': 0.26}
108
+ # Wrap model with PEFT
109
+ model = get_peft_model(model, peft_config)
110
+ model.print_trainable_parameters()
111
+ print(model)
112
+ model.to(device)
113
+
114
+ # --- Training Setup ---
115
+ data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
116
+
117
+ training_args = TrainingArguments(
118
+ output_dir=output_dir,
119
+ num_train_epochs=num_epochs,
120
+ per_device_train_batch_size=batch_size,
121
+ per_device_eval_batch_size=batch_size,
122
+ learning_rate=learning_rate,
123
+ weight_decay=0.01,
124
+ eval_strategy="epoch", # Evaluate at end of every epoch
125
+ save_strategy="epoch",
126
+ load_best_model_at_end=True,
127
+ metric_for_best_model="f1", # Optimize for F1 score
128
+ logging_steps=10,
129
+ push_to_hub=push_to_hub,
130
+ hub_model_id=hub_model_id,
131
+ hub_token=hf_token,
132
+ remove_unused_columns=False, # Important for PEFT sometimes
133
+ )
134
+
135
+ # Trainer mixes in MonteCLoRA variational regularization support.
136
+ trainer = MonteCLoRATrainer(
137
+ model=model,
138
+ args=training_args,
139
+ train_dataset=tokenized_datasets["train"],
140
+ eval_dataset=tokenized_datasets["validation"], # MRPC standard validation split
141
+ tokenizer=tokenizer,
142
+ data_collator=data_collator,
143
+ compute_metrics=compute_metrics,
144
+ )
145
+
146
+ print("Starting Training...")
147
+ trainer.train()
148
+
149
+ # --- Evaluation ---
150
+ print("Evaluating...")
151
+ eval_results = trainer.evaluate()
152
+ print(f"Evaluation Results: {eval_results}")
153
+
154
+ # --- Save & Push ---
155
+ if push_to_hub:
156
+ trainer.push_to_hub()
157
+
158
+ trainer.save_model(output_dir)
159
+ print(f"Model saved to {output_dir}")
160
+
161
+
162
+ # ----------------------------------------------------------------------------
163
+ # 4. Entry Point
164
+ # ----------------------------------------------------------------------------
165
+ if __name__ == "__main__":
166
+ parser = argparse.ArgumentParser(description="Fine-tune RoBERTa on MRPC with MonteCLoRA")
167
+
168
+ parser.add_argument("--base_model", type=str, default="roberta-base", help="Base model name")
169
+ parser.add_argument("--output_dir", type=str, default="./monteclora-roberta-mrpc", help="Output directory")
170
+ parser.add_argument("--batch_size", type=int, default=16, help="Batch size (per device)")
171
+ parser.add_argument("--num_epochs", type=int, default=5, help="Training epochs")
172
+ parser.add_argument(
173
+ "--learning_rate", type=float, default=2e-4, help="Learning rate"
174
+ ) # Higher LR for PEFT is common
175
+ parser.add_argument("--max_length", type=int, default=128, help="Max sequence length")
176
+ parser.add_argument("--device", type=str, default="auto", help="Device (cuda/cpu/auto)")
177
+
178
+ # MonteCLoRA specific args
179
+ parser.add_argument("--rank", type=int, default=8, help="LoRA Rank")
180
+ parser.add_argument("--lora_alpha", type=int, default=16, help="LoRA Alpha")
181
+ parser.add_argument("--target_modules", type=str, default="query,value", help="Modules to apply adapter to")
182
+ parser.add_argument("--n_samples", type=int, default=10, help="Number of MC samples")
183
+
184
+ parser.add_argument("--push_to_hub", action="store_true", help="Push to HF Hub")
185
+ parser.add_argument("--hub_model_id", type=str, default=None, help="Hub Repo ID")
186
+
187
+ args = parser.parse_args()
188
+
189
+ train_model(
190
+ base_model=args.base_model,
191
+ output_dir=args.output_dir,
192
+ batch_size=args.batch_size,
193
+ num_epochs=args.num_epochs,
194
+ learning_rate=args.learning_rate,
195
+ max_length=args.max_length,
196
+ device=args.device,
197
+ rank=args.rank,
198
+ lora_alpha=args.lora_alpha,
199
+ target_modules=args.target_modules,
200
+ n_samples=args.n_samples,
201
+ push_to_hub=args.push_to_hub,
202
+ hub_model_id=args.hub_model_id,
203
+ )
tasks/tasksmith-c488fc138ba1/tests/source/examples/multi_adapter_examples/Lora_Merging.ipynb ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 5,
6
+ "id": "db4208b9-5da4-46df-b77a-0f1836c9e4ec",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "import os\n",
11
+ "\n",
12
+ "os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\" # force using CUDA device 1\n",
13
+ "os.environ[\"ZE_AFFINITY_MASK\"] = \"1\" # force using Intel XPU device 1\n",
14
+ "from peft import PeftConfig, PeftModel\n",
15
+ "from peft import PeftModel, PeftConfig\n",
16
+ "from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig\n",
17
+ "from datasets import load_dataset\n",
18
+ "import torch\n",
19
+ "import random\n",
20
+ "\n",
21
+ "peft_model_id = \"smangrul/tinyllama_lora_norobots\"\n",
22
+ "device = torch.accelerator.current_accelerator().type if hasattr(torch, \"accelerator\") else \"cuda\"\n",
23
+ "config = PeftConfig.from_pretrained(peft_model_id)\n",
24
+ "model_kwargs = {\"device_map\": \"auto\"}\n",
25
+ "model_kwargs[\"quantization_config\"] = BitsAndBytesConfig(load_in_4bit=True)\n",
26
+ "model = AutoModelForCausalLM.from_pretrained(config.base_model_name_or_path, **model_kwargs)\n",
27
+ "tokenizer = AutoTokenizer.from_pretrained(peft_model_id)\n",
28
+ "model.resize_token_embeddings(len(tokenizer))\n",
29
+ "model = PeftModel.from_pretrained(model, peft_model_id, adapter_name=\"norobots\")\n",
30
+ "_ = model.load_adapter(\"smangrul/tinyllama_lora_sql\", adapter_name=\"sql\")\n",
31
+ "_ = model.load_adapter(\"smangrul/tinyllama_lora_adcopy\", adapter_name=\"adcopy\")"
32
+ ]
33
+ },
34
+ {
35
+ "cell_type": "code",
36
+ "execution_count": 6,
37
+ "id": "541dab43-9675-42a2-8d90-7437df9f0fa0",
38
+ "metadata": {},
39
+ "outputs": [
40
+ {
41
+ "name": "stdout",
42
+ "output_type": "stream",
43
+ "text": [
44
+ "CPU times: user 17.1 s, sys: 458 ms, total: 17.5 s\n",
45
+ "Wall time: 1.94 s\n"
46
+ ]
47
+ }
48
+ ],
49
+ "source": [
50
+ "%%time\n",
51
+ "# [0.8, 0.1, 0.1] linear #[1.0, 0.2] 0.7 density dare_linear #[1.5, 0.3] 0.5 density ties #[0.8, 0.5] cat\n",
52
+ "adapters = [\"norobots\", \"adcopy\", \"sql\"]\n",
53
+ "weights = [2.0, 0.3, 0.7]\n",
54
+ "adapter_name = \"merge\"\n",
55
+ "density = 0.2\n",
56
+ "combination_type = \"ties\"\n",
57
+ "if adapter_name in model.peft_config:\n",
58
+ " model.delete_adapter(adapter_name)\n",
59
+ "model.add_weighted_adapter(adapters, weights, adapter_name, combination_type=combination_type, density=density)"
60
+ ]
61
+ },
62
+ {
63
+ "cell_type": "code",
64
+ "execution_count": 7,
65
+ "id": "76596671-3677-47f0-9d66-81f40bc4d726",
66
+ "metadata": {},
67
+ "outputs": [],
68
+ "source": [
69
+ "model.eval()\n",
70
+ "model.set_adapter(\"merge\")"
71
+ ]
72
+ },
73
+ {
74
+ "cell_type": "code",
75
+ "execution_count": null,
76
+ "id": "9d59f9f3-6313-43d8-be36-4ca2bbb105b2",
77
+ "metadata": {},
78
+ "outputs": [],
79
+ "source": [
80
+ "messages = [\n",
81
+ " {\"role\": \"user\", \"content\": \"Write an essay about Generative AI.\"},\n",
82
+ "]\n",
83
+ "text = tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)\n",
84
+ "inputs = tokenizer(text, return_tensors=\"pt\") # , add_special_tokens=False)\n",
85
+ "inputs = {k: v.to(device) for k, v in inputs.items()}\n",
86
+ "outputs = model.generate(\n",
87
+ " **inputs,\n",
88
+ " max_new_tokens=256,\n",
89
+ " do_sample=True,\n",
90
+ " top_p=0.95,\n",
91
+ " temperature=0.2,\n",
92
+ " repetition_penalty=1.2,\n",
93
+ " eos_token_id=tokenizer.eos_token_id,\n",
94
+ ")\n",
95
+ "print(tokenizer.decode(outputs[0]))"
96
+ ]
97
+ },
98
+ {
99
+ "cell_type": "code",
100
+ "execution_count": null,
101
+ "id": "e5c1daeb-59c8-41d7-bebb-7abd052ab917",
102
+ "metadata": {},
103
+ "outputs": [
104
+ {
105
+ "name": "stdout",
106
+ "output_type": "stream",
107
+ "text": [
108
+ "<s><|im_start|>system \n",
109
+ "Create a text ad given the following product and description.<|im_end|> \n",
110
+ "<|im_start|>user \n",
111
+ "Product: Sony PS5 PlayStation Console\n",
112
+ "Description: The PS5™ console unleashes new gaming possibilities that you never anticipated.<|im_end|> \n",
113
+ "<|im_start|>assistant \n",
114
+ "Ad Text: Experience the next-gen power of the all-new Sony PS5 with its stunning visuals, innovative gameplay features, and more! Get ready to play in style as you experience the future of gaming on your own terms.<|im_end|>\n"
115
+ ]
116
+ }
117
+ ],
118
+ "source": [
119
+ "messages = [\n",
120
+ " {\"role\": \"system\", \"content\": \"Create a text ad given the following product and description.\"},\n",
121
+ " {\n",
122
+ " \"role\": \"user\",\n",
123
+ " \"content\": \"Product: Sony PS5 PlayStation Console\\nDescription: The PS5™ console unleashes new gaming possibilities that you never anticipated.\",\n",
124
+ " },\n",
125
+ "]\n",
126
+ "text = tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)\n",
127
+ "inputs = tokenizer(text, return_tensors=\"pt\") # , add_special_tokens=False)\n",
128
+ "inputs = {k: v.to(device) for k, v in inputs.items()}\n",
129
+ "outputs = model.generate(\n",
130
+ " **inputs,\n",
131
+ " max_new_tokens=128,\n",
132
+ " do_sample=True,\n",
133
+ " top_p=0.95,\n",
134
+ " temperature=0.2,\n",
135
+ " repetition_penalty=1.2,\n",
136
+ " eos_token_id=tokenizer.eos_token_id,\n",
137
+ ")\n",
138
+ "print(tokenizer.decode(outputs[0]))"
139
+ ]
140
+ },
141
+ {
142
+ "cell_type": "code",
143
+ "execution_count": null,
144
+ "id": "5bb08b46-90ae-48a8-8783-ca74b3e26e42",
145
+ "metadata": {},
146
+ "outputs": [
147
+ {
148
+ "name": "stdout",
149
+ "output_type": "stream",
150
+ "text": [
151
+ "<s> Table: 2-11365528-2\n",
152
+ "Columns: ['Team', 'Head Coach', 'President', 'Home Ground', 'Location']\n",
153
+ "Natural Query: Who is the Head Coach of the team whose President is Mario Volarevic?\n",
154
+ "SQL Query: SELECT Head Coach FROM 2-11365528-2 WHERE President = Mario Volarevic</s>\n"
155
+ ]
156
+ }
157
+ ],
158
+ "source": [
159
+ "text = \"\"\"Table: 2-11365528-2\n",
160
+ "Columns: ['Team', 'Head Coach', 'President', 'Home Ground', 'Location']\n",
161
+ "Natural Query: Who is the Head Coach of the team whose President is Mario Volarevic?\n",
162
+ "SQL Query:\"\"\"\n",
163
+ "\n",
164
+ "inputs = tokenizer(text, return_tensors=\"pt\") # , add_special_tokens=False)\n",
165
+ "inputs = {k: v.to(device) for k, v in inputs.items()}\n",
166
+ "outputs = model.generate(\n",
167
+ " **inputs, max_new_tokens=64, repetition_penalty=1.1, eos_token_id=tokenizer(\"</s>\").input_ids[-1]\n",
168
+ ")\n",
169
+ "print(tokenizer.decode(outputs[0]))"
170
+ ]
171
+ }
172
+ ],
173
+ "metadata": {
174
+ "kernelspec": {
175
+ "display_name": "Python 3",
176
+ "language": "python",
177
+ "name": "python3"
178
+ },
179
+ "language_info": {
180
+ "codemirror_mode": {
181
+ "name": "ipython",
182
+ "version": 3
183
+ },
184
+ "file_extension": ".py",
185
+ "mimetype": "text/x-python",
186
+ "name": "python",
187
+ "nbconvert_exporter": "python",
188
+ "pygments_lexer": "ipython3",
189
+ "version": "3.11.13"
190
+ }
191
+ },
192
+ "nbformat": 4,
193
+ "nbformat_minor": 5
194
+ }
tasks/tasksmith-c488fc138ba1/tests/source/examples/multi_adapter_examples/PEFT_Multi_LoRA_Inference.ipynb ADDED
@@ -0,0 +1,367 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "id": "jONLwzXgLg-I",
7
+ "metadata": {
8
+ "id": "jONLwzXgLg-I"
9
+ },
10
+ "outputs": [],
11
+ "source": [
12
+ "!pip install -q git+https://github.com/huggingface/transformers.git\n",
13
+ "!pip install -q git+https://github.com/huggingface/peft.git\n",
14
+ "!pip install -q git+https://github.com/huggingface/accelerate.git@main\n",
15
+ "!pip install huggingface_hub\n",
16
+ "!pip install bitsandbytes\n",
17
+ "!pip install SentencePiece"
18
+ ]
19
+ },
20
+ {
21
+ "cell_type": "code",
22
+ "execution_count": null,
23
+ "id": "36460935",
24
+ "metadata": {
25
+ "id": "36460935"
26
+ },
27
+ "outputs": [],
28
+ "source": [
29
+ "import os\n",
30
+ "import torch\n",
31
+ "\n",
32
+ "os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\" # force using CUDA device 0\n",
33
+ "os.environ[\"ZE_AFFINITY_MASK\"] = \"0\" # force using Intel XPU device 0"
34
+ ]
35
+ },
36
+ {
37
+ "cell_type": "code",
38
+ "execution_count": null,
39
+ "id": "1351e04c",
40
+ "metadata": {
41
+ "id": "1351e04c"
42
+ },
43
+ "outputs": [],
44
+ "source": [
45
+ "from huggingface_hub import notebook_login\n",
46
+ "\n",
47
+ "\n",
48
+ "notebook_login()"
49
+ ]
50
+ },
51
+ {
52
+ "cell_type": "code",
53
+ "execution_count": null,
54
+ "id": "d85af699",
55
+ "metadata": {
56
+ "id": "d85af699"
57
+ },
58
+ "outputs": [],
59
+ "source": [
60
+ "from peft import PeftModel\n",
61
+ "from transformers import LlamaTokenizer, LlamaForCausalLM, GenerationConfig, BitsAndBytesConfig\n",
62
+ "\n",
63
+ "model_name = \"meta-llama/Llama-2-7b-hf\"\n",
64
+ "tokenizer = LlamaTokenizer.from_pretrained(model_name)\n",
65
+ "model = LlamaForCausalLM.from_pretrained(model_name, quantization_config=BitsAndBytesConfig(load_in_8bit=True), device_map=\"auto\", use_auth_token=True)"
66
+ ]
67
+ },
68
+ {
69
+ "cell_type": "code",
70
+ "execution_count": null,
71
+ "id": "f0f515ed",
72
+ "metadata": {
73
+ "colab": {
74
+ "base_uri": "https://localhost:8080/"
75
+ },
76
+ "id": "f0f515ed",
77
+ "outputId": "312488a5-f4f8-48a4-8c63-7b4a59e80418"
78
+ },
79
+ "outputs": [],
80
+ "source": [
81
+ "%%time\n",
82
+ "model = PeftModel.from_pretrained(model, \"tloen/alpaca-lora-7b\", adapter_name=\"eng_alpaca\")"
83
+ ]
84
+ },
85
+ {
86
+ "cell_type": "code",
87
+ "execution_count": null,
88
+ "id": "67a0c121",
89
+ "metadata": {
90
+ "id": "67a0c121"
91
+ },
92
+ "outputs": [],
93
+ "source": [
94
+ "%%time\n",
95
+ "model.load_adapter(\"22h/cabrita-lora-v0-1\", adapter_name=\"portuguese_alpaca\")"
96
+ ]
97
+ },
98
+ {
99
+ "cell_type": "code",
100
+ "execution_count": null,
101
+ "id": "4b655fca",
102
+ "metadata": {
103
+ "id": "4b655fca"
104
+ },
105
+ "outputs": [],
106
+ "source": [
107
+ "model"
108
+ ]
109
+ },
110
+ {
111
+ "cell_type": "code",
112
+ "execution_count": null,
113
+ "id": "e9ebd572",
114
+ "metadata": {
115
+ "id": "e9ebd572"
116
+ },
117
+ "outputs": [],
118
+ "source": [
119
+ "device = torch.accelerator.current_accelerator().type if hasattr(torch, \"accelerator\") else \"cuda\"\n",
120
+ "\n",
121
+ "model.to(device)"
122
+ ]
123
+ },
124
+ {
125
+ "cell_type": "code",
126
+ "execution_count": 8,
127
+ "id": "138805b3",
128
+ "metadata": {
129
+ "id": "138805b3"
130
+ },
131
+ "outputs": [],
132
+ "source": [
133
+ "def generate_prompt(instruction, input=None):\n",
134
+ " if input:\n",
135
+ " return f\"\"\"Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.\n",
136
+ "### Instruction:\n",
137
+ "{instruction}\n",
138
+ "### Input:\n",
139
+ "{input}\n",
140
+ "### Response:\"\"\"\n",
141
+ " else:\n",
142
+ " return f\"\"\"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n",
143
+ "### Instruction:\n",
144
+ "{instruction}\n",
145
+ "### Response:\"\"\"\n",
146
+ "\n",
147
+ "\n",
148
+ "def evaluate(\n",
149
+ " instruction,\n",
150
+ " input=None,\n",
151
+ " temperature=0.1,\n",
152
+ " top_p=0.75,\n",
153
+ " top_k=40,\n",
154
+ " num_beams=4,\n",
155
+ " max_new_tokens=256,\n",
156
+ " **kwargs,\n",
157
+ "):\n",
158
+ " prompt = generate_prompt(instruction, input)\n",
159
+ " inputs = tokenizer(prompt, return_tensors=\"pt\")\n",
160
+ " input_ids = inputs[\"input_ids\"].to(device)\n",
161
+ " generation_config = GenerationConfig(\n",
162
+ " temperature=temperature,\n",
163
+ " top_p=top_p,\n",
164
+ " top_k=top_k,\n",
165
+ " num_beams=num_beams,\n",
166
+ " no_repeat_ngram_size=3,\n",
167
+ " **kwargs,\n",
168
+ " )\n",
169
+ "\n",
170
+ " with torch.no_grad():\n",
171
+ " generation_output = model.generate(\n",
172
+ " input_ids=input_ids,\n",
173
+ " generation_config=generation_config,\n",
174
+ " return_dict_in_generate=True,\n",
175
+ " output_scores=True,\n",
176
+ " max_new_tokens=max_new_tokens,\n",
177
+ " )\n",
178
+ " s = generation_output.sequences[0]\n",
179
+ " output = tokenizer.decode(s)\n",
180
+ " return output.split(\"### Response:\")[1].strip()"
181
+ ]
182
+ },
183
+ {
184
+ "cell_type": "code",
185
+ "execution_count": 9,
186
+ "id": "fd5e6b3b",
187
+ "metadata": {
188
+ "colab": {
189
+ "base_uri": "https://localhost:8080/"
190
+ },
191
+ "id": "fd5e6b3b",
192
+ "outputId": "ec72241b-c427-4258-b02f-2101df0d171a"
193
+ },
194
+ "outputs": [
195
+ {
196
+ "name": "stdout",
197
+ "output_type": "stream",
198
+ "text": [
199
+ "CPU times: user 5.16 ms, sys: 443 μs, total: 5.6 ms\n",
200
+ "Wall time: 5.58 ms\n"
201
+ ]
202
+ }
203
+ ],
204
+ "source": [
205
+ "%%time\n",
206
+ "model.set_adapter(\"eng_alpaca\")"
207
+ ]
208
+ },
209
+ {
210
+ "cell_type": "code",
211
+ "execution_count": 10,
212
+ "id": "33650851",
213
+ "metadata": {
214
+ "colab": {
215
+ "base_uri": "https://localhost:8080/"
216
+ },
217
+ "id": "33650851",
218
+ "outputId": "aae24052-0f09-4812-88c3-6fb53dec656c"
219
+ },
220
+ "outputs": [
221
+ {
222
+ "name": "stderr",
223
+ "output_type": "stream",
224
+ "text": [
225
+ "The following generation flags are not valid and may be ignored: ['temperature', 'top_p', 'top_k']. Set `TRANSFORMERS_VERBOSITY=info` for more details.\n",
226
+ "The following generation flags are not valid and may be ignored: ['temperature', 'top_p', 'top_k']. Set `TRANSFORMERS_VERBOSITY=info` for more details.\n"
227
+ ]
228
+ },
229
+ {
230
+ "name": "stdout",
231
+ "output_type": "stream",
232
+ "text": [
233
+ "The alpaca (Vicugna pacos) is a domesticated species of South American camelid. It resembles a small llama in appearance. It is kept in herds that graze on the level heights of the Andes of southern Peru, southern Bolivia, Ecuador, and northern Chile, at an altitude of about 3,800 m (12,500 ft) to 5,000 meters (16,404 ft). It is bred for its fiber, which is similar to sheep's wool but finer, silkier, and more durable. Alpaca fiber is used for making knitted and woven items, such as sweaters, hats, gloves, scarves, a variety of textiles, rugs, and blankets. The wool can be dyed, and is used to make ponchos, blankets, and sweaters in Peru and other Andean countries. The animals are also raised for meat and as a source of dairy products, including milk, butter, and cheese.\n",
234
+ "Alpaca fleece comes in 22 natural colors, the most\n"
235
+ ]
236
+ }
237
+ ],
238
+ "source": [
239
+ "instruction = \"Tell me about alpacas.\"\n",
240
+ "\n",
241
+ "print(evaluate(instruction))"
242
+ ]
243
+ },
244
+ {
245
+ "cell_type": "code",
246
+ "execution_count": 13,
247
+ "id": "fdc7196e",
248
+ "metadata": {
249
+ "colab": {
250
+ "base_uri": "https://localhost:8080/"
251
+ },
252
+ "id": "fdc7196e",
253
+ "outputId": "44cb6742-066b-470e-f507-cbf21e5ae030"
254
+ },
255
+ "outputs": [
256
+ {
257
+ "name": "stdout",
258
+ "output_type": "stream",
259
+ "text": [
260
+ "CPU times: user 6 ms, sys: 0 ns, total: 6 ms\n",
261
+ "Wall time: 5.86 ms\n"
262
+ ]
263
+ }
264
+ ],
265
+ "source": [
266
+ "%%time\n",
267
+ "model.set_adapter(\"portuguese_alpaca\")"
268
+ ]
269
+ },
270
+ {
271
+ "cell_type": "code",
272
+ "execution_count": 14,
273
+ "id": "31997da3",
274
+ "metadata": {
275
+ "colab": {
276
+ "base_uri": "https://localhost:8080/"
277
+ },
278
+ "id": "31997da3",
279
+ "outputId": "8071de75-dc9d-4e89-e85f-674f1de22658"
280
+ },
281
+ "outputs": [
282
+ {
283
+ "name": "stderr",
284
+ "output_type": "stream",
285
+ "text": [
286
+ "The following generation flags are not valid and may be ignored: ['temperature', 'top_p', 'top_k']. Set `TRANSFORMERS_VERBOSITY=info` for more details.\n",
287
+ "The following generation flags are not valid and may be ignored: ['temperature', 'top_p', 'top_k']. Set `TRANSFORMERS_VERBOSITY=info` for more details.\n"
288
+ ]
289
+ },
290
+ {
291
+ "name": "stdout",
292
+ "output_type": "stream",
293
+ "text": [
294
+ "I'm sorry, but I can't make it to the party. I'm not feeling well. I have a headache and I don't think it's a good idea for me to go out tonight. I hope you understand and that you have a great time at the party!</s>\n"
295
+ ]
296
+ }
297
+ ],
298
+ "source": [
299
+ "instruction = \"Invente uma desculpa criativa pra dizer que não preciso ir à festa.\"\n",
300
+ "\n",
301
+ "print(evaluate(instruction))"
302
+ ]
303
+ },
304
+ {
305
+ "cell_type": "code",
306
+ "execution_count": 15,
307
+ "id": "8b8e4e9a",
308
+ "metadata": {
309
+ "colab": {
310
+ "base_uri": "https://localhost:8080/"
311
+ },
312
+ "id": "8b8e4e9a",
313
+ "outputId": "84226223-e018-4feb-e189-969c344fd940"
314
+ },
315
+ "outputs": [
316
+ {
317
+ "name": "stderr",
318
+ "output_type": "stream",
319
+ "text": [
320
+ "The following generation flags are not valid and may be ignored: ['temperature', 'top_p', 'top_k']. Set `TRANSFORMERS_VERBOSITY=info` for more details.\n",
321
+ "The following generation flags are not valid and may be ignored: ['temperature', 'top_p', 'top_k']. Set `TRANSFORMERS_VERBOSITY=info` for more details.\n"
322
+ ]
323
+ },
324
+ {
325
+ "name": "stdout",
326
+ "output_type": "stream",
327
+ "text": [
328
+ "Eu não posso ir porque tenho que fazer uma tarefa para o meu professor.\n",
329
+ "</s>\n"
330
+ ]
331
+ }
332
+ ],
333
+ "source": [
334
+ "with model.disable_adapter():\n",
335
+ " instruction = \"Invente uma desculpa criativa pra dizer que não preciso ir à festa.\"\n",
336
+ "\n",
337
+ " print(evaluate(instruction))"
338
+ ]
339
+ }
340
+ ],
341
+ "metadata": {
342
+ "accelerator": "GPU",
343
+ "colab": {
344
+ "provenance": []
345
+ },
346
+ "gpuClass": "standard",
347
+ "kernelspec": {
348
+ "display_name": "Python 3",
349
+ "language": "python",
350
+ "name": "python3"
351
+ },
352
+ "language_info": {
353
+ "codemirror_mode": {
354
+ "name": "ipython",
355
+ "version": 3
356
+ },
357
+ "file_extension": ".py",
358
+ "mimetype": "text/x-python",
359
+ "name": "python",
360
+ "nbconvert_exporter": "python",
361
+ "pygments_lexer": "ipython3",
362
+ "version": "3.11.13"
363
+ }
364
+ },
365
+ "nbformat": 4,
366
+ "nbformat_minor": 5
367
+ }
tasks/tasksmith-c488fc138ba1/tests/source/examples/multi_adapter_examples/multi_adapter_weighted_inference_diffusers.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
tasks/tasksmith-c488fc138ba1/tests/source/examples/multilayer_perceptron/README.md ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Fine-tuning a multilayer perceptron using LoRA and 🤗 PEFT
2
+
3
+ [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/peft/blob/main/examples/multilayer_perceptron/multilayer_perceptron_lora.ipynb)
4
+
5
+ PEFT supports fine-tuning any type of model as long as the layers being used are supported. The model does not have to be a transformers model, for instance. To demonstrate this, the accompanying notebook `multilayer_perceptron_lora.ipynb` shows how to apply LoRA to a simple multilayer perceptron and use it to train a model to perform a classification task.
tasks/tasksmith-c488fc138ba1/tests/source/examples/multilayer_perceptron/multilayer_perceptron_lora.ipynb ADDED
@@ -0,0 +1,752 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "8e8743c8",
6
+ "metadata": {},
7
+ "source": [
8
+ "# Using PEFT with custom models"
9
+ ]
10
+ },
11
+ {
12
+ "cell_type": "markdown",
13
+ "id": "c42c67e1",
14
+ "metadata": {},
15
+ "source": [
16
+ "`peft` allows us to fine-tune models efficiently with LoRA. In this short notebook, we will demonstrate how to train a simple multilayer perceptron (MLP) using `peft`."
17
+ ]
18
+ },
19
+ {
20
+ "cell_type": "markdown",
21
+ "id": "ce314af5",
22
+ "metadata": {},
23
+ "source": [
24
+ "## Imports"
25
+ ]
26
+ },
27
+ {
28
+ "cell_type": "markdown",
29
+ "id": "b28b214d",
30
+ "metadata": {},
31
+ "source": [
32
+ "Make sure that you have the latest version of `peft` installed. To ensure that, run this in your Python environment:\n",
33
+ " \n",
34
+ " python -m pip install --upgrade peft"
35
+ ]
36
+ },
37
+ {
38
+ "cell_type": "code",
39
+ "execution_count": 1,
40
+ "id": "4d9da3d9",
41
+ "metadata": {},
42
+ "outputs": [],
43
+ "source": [
44
+ "import copy\n",
45
+ "import os\n",
46
+ "\n",
47
+ "# ignore bnb warnings\n",
48
+ "os.environ[\"BITSANDBYTES_NOWELCOME\"] = \"1\""
49
+ ]
50
+ },
51
+ {
52
+ "cell_type": "code",
53
+ "execution_count": 2,
54
+ "id": "44075f54",
55
+ "metadata": {},
56
+ "outputs": [
57
+ {
58
+ "name": "stderr",
59
+ "output_type": "stream",
60
+ "text": [
61
+ "/usr/local/lib/python3.11/dist-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
62
+ " from .autonotebook import tqdm as notebook_tqdm\n"
63
+ ]
64
+ }
65
+ ],
66
+ "source": [
67
+ "import peft\n",
68
+ "import torch\n",
69
+ "from torch import nn\n",
70
+ "import torch.nn.functional as F"
71
+ ]
72
+ },
73
+ {
74
+ "cell_type": "code",
75
+ "execution_count": 3,
76
+ "id": "f72acdfb",
77
+ "metadata": {},
78
+ "outputs": [
79
+ {
80
+ "data": {
81
+ "text/plain": [
82
+ "<torch._C.Generator at 0x7f6d9259a5d0>"
83
+ ]
84
+ },
85
+ "execution_count": 3,
86
+ "metadata": {},
87
+ "output_type": "execute_result"
88
+ }
89
+ ],
90
+ "source": [
91
+ "torch.manual_seed(0)"
92
+ ]
93
+ },
94
+ {
95
+ "cell_type": "markdown",
96
+ "id": "2b127a78",
97
+ "metadata": {},
98
+ "source": [
99
+ "## Data"
100
+ ]
101
+ },
102
+ {
103
+ "cell_type": "markdown",
104
+ "id": "f265da76",
105
+ "metadata": {},
106
+ "source": [
107
+ "We will create a toy dataset consisting of random data for a classification task. There is a little bit of signal in the data, so we should expect that the loss of the model can improve during training."
108
+ ]
109
+ },
110
+ {
111
+ "cell_type": "code",
112
+ "execution_count": 4,
113
+ "id": "b355567e",
114
+ "metadata": {},
115
+ "outputs": [],
116
+ "source": [
117
+ "X = torch.rand((1000, 20))\n",
118
+ "y = (X.sum(1) > 10).long()"
119
+ ]
120
+ },
121
+ {
122
+ "cell_type": "code",
123
+ "execution_count": 5,
124
+ "id": "a60a869d",
125
+ "metadata": {},
126
+ "outputs": [],
127
+ "source": [
128
+ "n_train = 800\n",
129
+ "batch_size = 64"
130
+ ]
131
+ },
132
+ {
133
+ "cell_type": "code",
134
+ "execution_count": 6,
135
+ "id": "8859572e",
136
+ "metadata": {},
137
+ "outputs": [],
138
+ "source": [
139
+ "train_dataloader = torch.utils.data.DataLoader(\n",
140
+ " torch.utils.data.TensorDataset(X[:n_train], y[:n_train]),\n",
141
+ " batch_size=batch_size,\n",
142
+ " shuffle=True,\n",
143
+ ")\n",
144
+ "eval_dataloader = torch.utils.data.DataLoader(\n",
145
+ " torch.utils.data.TensorDataset(X[n_train:], y[n_train:]),\n",
146
+ " batch_size=batch_size,\n",
147
+ ")"
148
+ ]
149
+ },
150
+ {
151
+ "cell_type": "markdown",
152
+ "id": "97bddd2c",
153
+ "metadata": {},
154
+ "source": [
155
+ "## Model"
156
+ ]
157
+ },
158
+ {
159
+ "cell_type": "markdown",
160
+ "id": "db694a58",
161
+ "metadata": {},
162
+ "source": [
163
+ "As a model, we use a simple multilayer perceptron (MLP). For demonstration purposes, we use a very large number of hidden units. This is totally overkill for this task but it helps to demonstrate the advantages of `peft`. In more realistic settings, models will also be quite large on average, so this is not far-fetched."
164
+ ]
165
+ },
166
+ {
167
+ "cell_type": "code",
168
+ "execution_count": 7,
169
+ "id": "1b43cd8f",
170
+ "metadata": {},
171
+ "outputs": [],
172
+ "source": [
173
+ "class MLP(nn.Module):\n",
174
+ " def __init__(self, num_units_hidden=2000):\n",
175
+ " super().__init__()\n",
176
+ " self.seq = nn.Sequential(\n",
177
+ " nn.Linear(20, num_units_hidden),\n",
178
+ " nn.ReLU(),\n",
179
+ " nn.Linear(num_units_hidden, num_units_hidden),\n",
180
+ " nn.ReLU(),\n",
181
+ " nn.Linear(num_units_hidden, 2),\n",
182
+ " nn.LogSoftmax(dim=-1),\n",
183
+ " )\n",
184
+ "\n",
185
+ " def forward(self, X):\n",
186
+ " return self.seq(X)"
187
+ ]
188
+ },
189
+ {
190
+ "cell_type": "markdown",
191
+ "id": "1277bf00",
192
+ "metadata": {},
193
+ "source": [
194
+ "## Training"
195
+ ]
196
+ },
197
+ {
198
+ "cell_type": "markdown",
199
+ "id": "02caf26a",
200
+ "metadata": {},
201
+ "source": [
202
+ "Here are just a few training hyper-parameters and a simple function that performs the training and evaluation loop."
203
+ ]
204
+ },
205
+ {
206
+ "cell_type": "code",
207
+ "execution_count": 9,
208
+ "id": "5d14c0c4",
209
+ "metadata": {},
210
+ "outputs": [],
211
+ "source": [
212
+ "lr = 0.002\n",
213
+ "batch_size = 64\n",
214
+ "max_epochs = 30\n",
215
+ "device = torch.accelerator.current_accelerator().type if hasattr(torch, \"accelerator\") else \"cuda\""
216
+ ]
217
+ },
218
+ {
219
+ "cell_type": "code",
220
+ "execution_count": 10,
221
+ "id": "657d6b3e",
222
+ "metadata": {},
223
+ "outputs": [],
224
+ "source": [
225
+ "def train(model, optimizer, criterion, train_dataloader, eval_dataloader, epochs):\n",
226
+ " for epoch in range(epochs):\n",
227
+ " model.train()\n",
228
+ " train_loss = 0\n",
229
+ " for xb, yb in train_dataloader:\n",
230
+ " xb = xb.to(device)\n",
231
+ " yb = yb.to(device)\n",
232
+ " outputs = model(xb)\n",
233
+ " loss = criterion(outputs, yb)\n",
234
+ " train_loss += loss.detach().float()\n",
235
+ " loss.backward()\n",
236
+ " optimizer.step()\n",
237
+ " optimizer.zero_grad()\n",
238
+ "\n",
239
+ " model.eval()\n",
240
+ " eval_loss = 0\n",
241
+ " for xb, yb in eval_dataloader:\n",
242
+ " xb = xb.to(device)\n",
243
+ " yb = yb.to(device)\n",
244
+ " with torch.no_grad():\n",
245
+ " outputs = model(xb)\n",
246
+ " loss = criterion(outputs, yb)\n",
247
+ " eval_loss += loss.detach().float()\n",
248
+ "\n",
249
+ " eval_loss_total = (eval_loss / len(eval_dataloader)).item()\n",
250
+ " train_loss_total = (train_loss / len(train_dataloader)).item()\n",
251
+ " print(f\"{epoch=:<2} {train_loss_total=:.4f} {eval_loss_total=:.4f}\")"
252
+ ]
253
+ },
254
+ {
255
+ "cell_type": "markdown",
256
+ "id": "b382dcbe",
257
+ "metadata": {},
258
+ "source": [
259
+ "### Training without peft"
260
+ ]
261
+ },
262
+ {
263
+ "cell_type": "markdown",
264
+ "id": "b40d4873",
265
+ "metadata": {},
266
+ "source": [
267
+ "Let's start without using `peft` to see what we can expect from the model training."
268
+ ]
269
+ },
270
+ {
271
+ "cell_type": "code",
272
+ "execution_count": 11,
273
+ "id": "f059ced4",
274
+ "metadata": {},
275
+ "outputs": [],
276
+ "source": [
277
+ "module = MLP().to(device)\n",
278
+ "optimizer = torch.optim.Adam(module.parameters(), lr=lr)\n",
279
+ "criterion = nn.CrossEntropyLoss()"
280
+ ]
281
+ },
282
+ {
283
+ "cell_type": "code",
284
+ "execution_count": 12,
285
+ "id": "17698863",
286
+ "metadata": {},
287
+ "outputs": [
288
+ {
289
+ "name": "stdout",
290
+ "output_type": "stream",
291
+ "text": [
292
+ "epoch=0 train_loss_total=0.7970 eval_loss_total=0.6472\n",
293
+ "epoch=1 train_loss_total=0.5597 eval_loss_total=0.4898\n",
294
+ "epoch=2 train_loss_total=0.3696 eval_loss_total=0.3323\n",
295
+ "epoch=3 train_loss_total=0.2364 eval_loss_total=0.5454\n",
296
+ "epoch=4 train_loss_total=0.2428 eval_loss_total=0.2843\n",
297
+ "epoch=5 train_loss_total=0.1251 eval_loss_total=0.2514\n",
298
+ "epoch=6 train_loss_total=0.0952 eval_loss_total=0.2068\n",
299
+ "epoch=7 train_loss_total=0.0831 eval_loss_total=0.2395\n",
300
+ "epoch=8 train_loss_total=0.0655 eval_loss_total=0.2524\n",
301
+ "epoch=9 train_loss_total=0.0380 eval_loss_total=0.3650\n",
302
+ "epoch=10 train_loss_total=0.0363 eval_loss_total=0.3495\n",
303
+ "epoch=11 train_loss_total=0.0231 eval_loss_total=0.2360\n",
304
+ "epoch=12 train_loss_total=0.0162 eval_loss_total=0.2276\n",
305
+ "epoch=13 train_loss_total=0.0094 eval_loss_total=0.2716\n",
306
+ "epoch=14 train_loss_total=0.0065 eval_loss_total=0.2237\n",
307
+ "epoch=15 train_loss_total=0.0054 eval_loss_total=0.2366\n",
308
+ "epoch=16 train_loss_total=0.0035 eval_loss_total=0.2673\n",
309
+ "epoch=17 train_loss_total=0.0028 eval_loss_total=0.2630\n",
310
+ "epoch=18 train_loss_total=0.0023 eval_loss_total=0.2835\n",
311
+ "epoch=19 train_loss_total=0.0021 eval_loss_total=0.2727\n",
312
+ "epoch=20 train_loss_total=0.0018 eval_loss_total=0.2597\n",
313
+ "epoch=21 train_loss_total=0.0016 eval_loss_total=0.2553\n",
314
+ "epoch=22 train_loss_total=0.0014 eval_loss_total=0.2712\n",
315
+ "epoch=23 train_loss_total=0.0013 eval_loss_total=0.2637\n",
316
+ "epoch=24 train_loss_total=0.0012 eval_loss_total=0.2733\n",
317
+ "epoch=25 train_loss_total=0.0011 eval_loss_total=0.2738\n",
318
+ "epoch=26 train_loss_total=0.0010 eval_loss_total=0.2477\n",
319
+ "epoch=27 train_loss_total=0.0010 eval_loss_total=0.2584\n",
320
+ "epoch=28 train_loss_total=0.0009 eval_loss_total=0.2844\n",
321
+ "epoch=29 train_loss_total=0.0008 eval_loss_total=0.2633\n",
322
+ "CPU times: user 1.31 s, sys: 236 ms, total: 1.54 s\n",
323
+ "Wall time: 1.56 s\n"
324
+ ]
325
+ }
326
+ ],
327
+ "source": [
328
+ "%time train(module, optimizer, criterion, train_dataloader, eval_dataloader, epochs=max_epochs)"
329
+ ]
330
+ },
331
+ {
332
+ "cell_type": "markdown",
333
+ "id": "4cef0029",
334
+ "metadata": {},
335
+ "source": [
336
+ "Okay, so we got an eval loss of ~0.26, which is much better than random."
337
+ ]
338
+ },
339
+ {
340
+ "cell_type": "markdown",
341
+ "id": "4f106078",
342
+ "metadata": {},
343
+ "source": [
344
+ "### Training with peft"
345
+ ]
346
+ },
347
+ {
348
+ "cell_type": "markdown",
349
+ "id": "8dd47aa4",
350
+ "metadata": {},
351
+ "source": [
352
+ "Now let's train with `peft`. First we check the names of the modules, so that we can configure `peft` to fine-tune the right modules."
353
+ ]
354
+ },
355
+ {
356
+ "cell_type": "code",
357
+ "execution_count": 13,
358
+ "id": "922db29b",
359
+ "metadata": {
360
+ "scrolled": true
361
+ },
362
+ "outputs": [
363
+ {
364
+ "data": {
365
+ "text/plain": [
366
+ "[('', __main__.MLP),\n",
367
+ " ('seq', torch.nn.modules.container.Sequential),\n",
368
+ " ('seq.0', torch.nn.modules.linear.Linear),\n",
369
+ " ('seq.1', torch.nn.modules.activation.ReLU),\n",
370
+ " ('seq.2', torch.nn.modules.linear.Linear),\n",
371
+ " ('seq.3', torch.nn.modules.activation.ReLU),\n",
372
+ " ('seq.4', torch.nn.modules.linear.Linear),\n",
373
+ " ('seq.5', torch.nn.modules.activation.LogSoftmax)]"
374
+ ]
375
+ },
376
+ "execution_count": 13,
377
+ "metadata": {},
378
+ "output_type": "execute_result"
379
+ }
380
+ ],
381
+ "source": [
382
+ "[(n, type(m)) for n, m in MLP().named_modules()]"
383
+ ]
384
+ },
385
+ {
386
+ "cell_type": "markdown",
387
+ "id": "5efb275d",
388
+ "metadata": {},
389
+ "source": [
390
+ "Next we can define the LoRA config. There is nothing special going on here. We set the LoRA rank to 8 and select the layers `seq.0` and `seq.2` to be used for LoRA fine-tuning. As for `seq.4`, which is the output layer, we set it as `module_to_save`, which means it is also trained but no LoRA is applied."
391
+ ]
392
+ },
393
+ {
394
+ "cell_type": "markdown",
395
+ "id": "cf2c608d",
396
+ "metadata": {},
397
+ "source": [
398
+ "*Note: Not all layers types can be fine-tuned with LoRA. At the moment, linear layers, embeddings, `Conv2D` and `transformers.pytorch_utils.Conv1D` are supported."
399
+ ]
400
+ },
401
+ {
402
+ "cell_type": "code",
403
+ "execution_count": 14,
404
+ "id": "b342438f",
405
+ "metadata": {},
406
+ "outputs": [],
407
+ "source": [
408
+ "config = peft.LoraConfig(\n",
409
+ " r=8,\n",
410
+ " target_modules=[\"seq.0\", \"seq.2\"],\n",
411
+ " modules_to_save=[\"seq.4\"],\n",
412
+ ")"
413
+ ]
414
+ },
415
+ {
416
+ "cell_type": "markdown",
417
+ "id": "829b4e2d",
418
+ "metadata": {},
419
+ "source": [
420
+ "Now let's create the `peft` model by passing our initial MLP, as well as the config we just defined, to `get_peft_model`."
421
+ ]
422
+ },
423
+ {
424
+ "cell_type": "code",
425
+ "execution_count": null,
426
+ "id": "602b6658",
427
+ "metadata": {},
428
+ "outputs": [],
429
+ "source": [
430
+ "module = MLP().to(device)\n",
431
+ "module_copy = copy.deepcopy(module) # we keep a copy of the original model for later\n",
432
+ "peft_model = peft.get_peft_model(module, config)\n",
433
+ "optimizer = torch.optim.Adam(peft_model.parameters(), lr=lr)\n",
434
+ "criterion = nn.CrossEntropyLoss()\n",
435
+ "peft_model.print_trainable_parameters()"
436
+ ]
437
+ },
438
+ {
439
+ "cell_type": "markdown",
440
+ "id": "2103737d",
441
+ "metadata": {},
442
+ "source": [
443
+ "Checking the numbers, we see that only ~1% of parameters are actually trained, which is what we like to see.\n",
444
+ "\n",
445
+ "Now let's start the training:"
446
+ ]
447
+ },
448
+ {
449
+ "cell_type": "code",
450
+ "execution_count": 16,
451
+ "id": "9200cbc6",
452
+ "metadata": {},
453
+ "outputs": [
454
+ {
455
+ "name": "stdout",
456
+ "output_type": "stream",
457
+ "text": [
458
+ "epoch=0 train_loss_total=0.6695 eval_loss_total=0.6388\n",
459
+ "epoch=1 train_loss_total=0.5614 eval_loss_total=0.5456\n",
460
+ "epoch=2 train_loss_total=0.3897 eval_loss_total=0.3035\n",
461
+ "epoch=3 train_loss_total=0.2529 eval_loss_total=0.2510\n",
462
+ "epoch=4 train_loss_total=0.1914 eval_loss_total=0.2191\n",
463
+ "epoch=5 train_loss_total=0.1236 eval_loss_total=0.2586\n",
464
+ "epoch=6 train_loss_total=0.1076 eval_loss_total=0.3205\n",
465
+ "epoch=7 train_loss_total=0.1834 eval_loss_total=0.3951\n",
466
+ "epoch=8 train_loss_total=0.1037 eval_loss_total=0.1646\n",
467
+ "epoch=9 train_loss_total=0.0724 eval_loss_total=0.1409\n",
468
+ "epoch=10 train_loss_total=0.0691 eval_loss_total=0.1725\n",
469
+ "epoch=11 train_loss_total=0.0641 eval_loss_total=0.1423\n",
470
+ "epoch=12 train_loss_total=0.0382 eval_loss_total=0.1490\n",
471
+ "epoch=13 train_loss_total=0.0214 eval_loss_total=0.1517\n",
472
+ "epoch=14 train_loss_total=0.0119 eval_loss_total=0.1717\n",
473
+ "epoch=15 train_loss_total=0.0060 eval_loss_total=0.2366\n",
474
+ "epoch=16 train_loss_total=0.0029 eval_loss_total=0.2069\n",
475
+ "epoch=17 train_loss_total=0.0021 eval_loss_total=0.2082\n",
476
+ "epoch=18 train_loss_total=0.0016 eval_loss_total=0.2119\n",
477
+ "epoch=19 train_loss_total=0.0011 eval_loss_total=0.1984\n",
478
+ "epoch=20 train_loss_total=0.0010 eval_loss_total=0.1821\n",
479
+ "epoch=21 train_loss_total=0.0009 eval_loss_total=0.1892\n",
480
+ "epoch=22 train_loss_total=0.0007 eval_loss_total=0.2062\n",
481
+ "epoch=23 train_loss_total=0.0006 eval_loss_total=0.2408\n",
482
+ "epoch=24 train_loss_total=0.0006 eval_loss_total=0.2038\n",
483
+ "epoch=25 train_loss_total=0.0005 eval_loss_total=0.2374\n",
484
+ "epoch=26 train_loss_total=0.0004 eval_loss_total=0.2139\n",
485
+ "epoch=27 train_loss_total=0.0004 eval_loss_total=0.2085\n",
486
+ "epoch=28 train_loss_total=0.0004 eval_loss_total=0.2395\n",
487
+ "epoch=29 train_loss_total=0.0003 eval_loss_total=0.2100\n",
488
+ "CPU times: user 1.41 s, sys: 48.9 ms, total: 1.46 s\n",
489
+ "Wall time: 1.46 s\n"
490
+ ]
491
+ }
492
+ ],
493
+ "source": [
494
+ "%time train(peft_model, optimizer, criterion, train_dataloader, eval_dataloader, epochs=max_epochs)"
495
+ ]
496
+ },
497
+ {
498
+ "cell_type": "markdown",
499
+ "id": "20f6f452",
500
+ "metadata": {},
501
+ "source": [
502
+ "In the end, we see that the eval loss is very similar to the one we saw earlier when we trained without `peft`. This is quite nice to see, given that we are training a much smaller number of parameters."
503
+ ]
504
+ },
505
+ {
506
+ "cell_type": "markdown",
507
+ "id": "fa55d1d4",
508
+ "metadata": {},
509
+ "source": [
510
+ "#### Check which parameters were updated"
511
+ ]
512
+ },
513
+ {
514
+ "cell_type": "markdown",
515
+ "id": "a6e2146b",
516
+ "metadata": {},
517
+ "source": [
518
+ "Finally, just to check that LoRA was applied as expected, we check what original weights were updated what weights stayed the same."
519
+ ]
520
+ },
521
+ {
522
+ "cell_type": "code",
523
+ "execution_count": 17,
524
+ "id": "c7dcde21",
525
+ "metadata": {},
526
+ "outputs": [
527
+ {
528
+ "name": "stdout",
529
+ "output_type": "stream",
530
+ "text": [
531
+ "New parameter model.seq.0.lora_A.default.weight | 160 parameters | updated\n",
532
+ "New parameter model.seq.0.lora_B.default.weight | 16000 parameters | updated\n",
533
+ "New parameter model.seq.2.lora_A.default.weight | 16000 parameters | updated\n",
534
+ "New parameter model.seq.2.lora_B.default.weight | 16000 parameters | updated\n"
535
+ ]
536
+ }
537
+ ],
538
+ "source": [
539
+ "for name, param in peft_model.base_model.named_parameters():\n",
540
+ " if \"lora\" not in name:\n",
541
+ " continue\n",
542
+ "\n",
543
+ " print(f\"New parameter {name:<13} | {param.numel():>5} parameters | updated\")"
544
+ ]
545
+ },
546
+ {
547
+ "cell_type": "code",
548
+ "execution_count": 25,
549
+ "id": "022e6c41",
550
+ "metadata": {},
551
+ "outputs": [
552
+ {
553
+ "name": "stdout",
554
+ "output_type": "stream",
555
+ "text": [
556
+ "Parameter seq.0.weight | 40000 parameters | not updated\n",
557
+ "Parameter seq.0.bias | 2000 parameters | not updated\n",
558
+ "Parameter seq.2.weight | 4000000 parameters | not updated\n",
559
+ "Parameter seq.2.bias | 2000 parameters | not updated\n",
560
+ "Parameter seq.4.weight | 4000 parameters | not updated\n",
561
+ "Parameter seq.4.bias | 2 parameters | not updated\n",
562
+ "Parameter seq.4.weight | 4000 parameters | updated\n",
563
+ "Parameter seq.4.bias | 2 parameters | updated\n"
564
+ ]
565
+ }
566
+ ],
567
+ "source": [
568
+ "params_before = dict(module_copy.named_parameters())\n",
569
+ "for name, param in peft_model.base_model.named_parameters():\n",
570
+ " if \"lora\" in name:\n",
571
+ " continue\n",
572
+ "\n",
573
+ " name_before = (\n",
574
+ " name.partition(\".\")[-1].replace(\"base_layer.\", \"\").replace(\"original_\", \"\").replace(\"module.\", \"\").replace(\"modules_to_save.default.\", \"\")\n",
575
+ " )\n",
576
+ " param_before = params_before[name_before]\n",
577
+ " if torch.allclose(param, param_before):\n",
578
+ " print(f\"Parameter {name_before:<13} | {param.numel():>7} parameters | not updated\")\n",
579
+ " else:\n",
580
+ " print(f\"Parameter {name_before:<13} | {param.numel():>7} parameters | updated\")"
581
+ ]
582
+ },
583
+ {
584
+ "cell_type": "markdown",
585
+ "id": "4c09b43d",
586
+ "metadata": {},
587
+ "source": [
588
+ "So we can see that apart from the new LoRA weights that were added, only the last layer was updated. Since the LoRA weights and the last layer have comparitively few parameters, this gives us a big boost in efficiency."
589
+ ]
590
+ },
591
+ {
592
+ "cell_type": "markdown",
593
+ "id": "b46c6198",
594
+ "metadata": {},
595
+ "source": [
596
+ "## Sharing the model through Hugging Face Hub"
597
+ ]
598
+ },
599
+ {
600
+ "cell_type": "markdown",
601
+ "id": "6289e647",
602
+ "metadata": {},
603
+ "source": [
604
+ "### Pushing the model to HF Hub"
605
+ ]
606
+ },
607
+ {
608
+ "cell_type": "markdown",
609
+ "id": "06dcdfa0",
610
+ "metadata": {},
611
+ "source": [
612
+ "With the `peft` model, it is also very easy to push a model the Hugging Face Hub. Below, we demonstrate how it works. It is assumed that you have a valid Hugging Face account and are logged in:"
613
+ ]
614
+ },
615
+ {
616
+ "cell_type": "code",
617
+ "execution_count": 26,
618
+ "id": "1b91a0af",
619
+ "metadata": {},
620
+ "outputs": [],
621
+ "source": [
622
+ "user = \"BenjaminB\" # put your user name here\n",
623
+ "model_name = \"peft-lora-with-custom-model\"\n",
624
+ "model_id = f\"{user}/{model_name}\""
625
+ ]
626
+ },
627
+ {
628
+ "cell_type": "code",
629
+ "execution_count": null,
630
+ "id": "1430fffd",
631
+ "metadata": {},
632
+ "outputs": [],
633
+ "source": [
634
+ "peft_model.push_to_hub(model_id);"
635
+ ]
636
+ },
637
+ {
638
+ "cell_type": "markdown",
639
+ "id": "632bd799",
640
+ "metadata": {},
641
+ "source": [
642
+ "As we can see, the adapter size is only 211 kB."
643
+ ]
644
+ },
645
+ {
646
+ "cell_type": "markdown",
647
+ "id": "4ff78c0c",
648
+ "metadata": {},
649
+ "source": [
650
+ "### Loading the model from HF Hub"
651
+ ]
652
+ },
653
+ {
654
+ "cell_type": "markdown",
655
+ "id": "e5c7e87f",
656
+ "metadata": {},
657
+ "source": [
658
+ "Now, it only takes one step to load the model from HF Hub. To do this, we can use `PeftModel.from_pretrained`, passing our base model and the model ID:"
659
+ ]
660
+ },
661
+ {
662
+ "cell_type": "code",
663
+ "execution_count": null,
664
+ "id": "ce0fcced",
665
+ "metadata": {},
666
+ "outputs": [],
667
+ "source": [
668
+ "loaded = peft.PeftModel.from_pretrained(module_copy, model_id)\n",
669
+ "type(loaded)"
670
+ ]
671
+ },
672
+ {
673
+ "cell_type": "markdown",
674
+ "id": "cd4b4eac",
675
+ "metadata": {},
676
+ "source": [
677
+ "Let's check that the two models produce the same output:"
678
+ ]
679
+ },
680
+ {
681
+ "cell_type": "code",
682
+ "execution_count": null,
683
+ "id": "f2cf6ac4",
684
+ "metadata": {
685
+ "scrolled": true
686
+ },
687
+ "outputs": [],
688
+ "source": [
689
+ "y_peft = peft_model(X.to(device))\n",
690
+ "y_loaded = loaded(X.to(device))\n",
691
+ "torch.allclose(y_peft, y_loaded)"
692
+ ]
693
+ },
694
+ {
695
+ "cell_type": "markdown",
696
+ "id": "eeeb653f",
697
+ "metadata": {},
698
+ "source": [
699
+ "### Clean up"
700
+ ]
701
+ },
702
+ {
703
+ "cell_type": "markdown",
704
+ "id": "61c60355",
705
+ "metadata": {},
706
+ "source": [
707
+ "Finally, as a clean up step, you may want to delete the repo."
708
+ ]
709
+ },
710
+ {
711
+ "cell_type": "code",
712
+ "execution_count": 22,
713
+ "id": "b747038f",
714
+ "metadata": {},
715
+ "outputs": [],
716
+ "source": [
717
+ "from huggingface_hub import delete_repo"
718
+ ]
719
+ },
720
+ {
721
+ "cell_type": "code",
722
+ "execution_count": 23,
723
+ "id": "7e5ab237",
724
+ "metadata": {},
725
+ "outputs": [],
726
+ "source": [
727
+ "delete_repo(model_id)"
728
+ ]
729
+ }
730
+ ],
731
+ "metadata": {
732
+ "kernelspec": {
733
+ "display_name": "Python 3",
734
+ "language": "python",
735
+ "name": "python3"
736
+ },
737
+ "language_info": {
738
+ "codemirror_mode": {
739
+ "name": "ipython",
740
+ "version": 3
741
+ },
742
+ "file_extension": ".py",
743
+ "mimetype": "text/x-python",
744
+ "name": "python",
745
+ "nbconvert_exporter": "python",
746
+ "pygments_lexer": "ipython3",
747
+ "version": "3.11.13"
748
+ }
749
+ },
750
+ "nbformat": 4,
751
+ "nbformat_minor": 5
752
+ }
tasks/tasksmith-c488fc138ba1/tests/source/examples/oft_dreambooth/oft_dreambooth_inference.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
tasks/tasksmith-c488fc138ba1/tests/source/examples/oft_dreambooth/train_dreambooth.py ADDED
@@ -0,0 +1,1115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 contextlib import nullcontext
11
+ from pathlib import Path
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 get_peft_model
42
+ from peft.tuners.oft.config import OFTConfig
43
+
44
+
45
+ # Will error if the minimal version of diffusers is not installed. Remove at your own risks.
46
+ check_min_version("0.10.0.dev0")
47
+
48
+ logger = get_logger(__name__)
49
+
50
+ UNET_TARGET_MODULES = ["to_q", "to_v", "query", "value"] # , "ff.net.0.proj"]
51
+ TEXT_ENCODER_TARGET_MODULES = ["q_proj", "v_proj"]
52
+
53
+
54
+ def import_model_class_from_model_name_or_path(pretrained_model_name_or_path: str, revision: str):
55
+ text_encoder_config = PretrainedConfig.from_pretrained(
56
+ pretrained_model_name_or_path,
57
+ subfolder="text_encoder",
58
+ revision=revision,
59
+ )
60
+ model_class = text_encoder_config.architectures[0]
61
+
62
+ if model_class == "CLIPTextModel":
63
+ from transformers import CLIPTextModel
64
+
65
+ return CLIPTextModel
66
+ elif model_class == "RobertaSeriesModelWithTransformation":
67
+ from diffusers.pipelines.alt_diffusion.modeling_roberta_series import RobertaSeriesModelWithTransformation
68
+
69
+ return RobertaSeriesModelWithTransformation
70
+ else:
71
+ raise ValueError(f"{model_class} is not supported.")
72
+
73
+
74
+ def parse_args(input_args=None):
75
+ parser = argparse.ArgumentParser(description="Simple example of a training script.")
76
+ parser.add_argument(
77
+ "--pretrained_model_name_or_path",
78
+ type=str,
79
+ default=None,
80
+ required=True,
81
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
82
+ )
83
+ parser.add_argument(
84
+ "--revision",
85
+ type=str,
86
+ default=None,
87
+ required=False,
88
+ help="Revision of pretrained model identifier from huggingface.co/models.",
89
+ )
90
+ parser.add_argument(
91
+ "--tokenizer_name",
92
+ type=str,
93
+ default=None,
94
+ help="Pretrained tokenizer name or path if not the same as model_name",
95
+ )
96
+ parser.add_argument(
97
+ "--instance_data_dir",
98
+ type=str,
99
+ default=None,
100
+ required=True,
101
+ help="A folder containing the training data of instance images.",
102
+ )
103
+ parser.add_argument(
104
+ "--class_data_dir",
105
+ type=str,
106
+ default=None,
107
+ required=False,
108
+ help="A folder containing the training data of class images.",
109
+ )
110
+ parser.add_argument(
111
+ "--instance_prompt",
112
+ type=str,
113
+ default=None,
114
+ required=True,
115
+ help="The prompt with identifier specifying the instance",
116
+ )
117
+ parser.add_argument(
118
+ "--class_prompt",
119
+ type=str,
120
+ default=None,
121
+ help="The prompt to specify images in the same class as provided instance images.",
122
+ )
123
+ parser.add_argument(
124
+ "--with_prior_preservation",
125
+ default=False,
126
+ action="store_true",
127
+ help="Flag to add prior preservation loss.",
128
+ )
129
+ parser.add_argument("--prior_loss_weight", type=float, default=1.0, help="The weight of prior preservation loss.")
130
+ parser.add_argument(
131
+ "--num_class_images",
132
+ type=int,
133
+ default=100,
134
+ help=(
135
+ "Minimal class images for prior preservation loss. If there are not enough images already present in"
136
+ " class_data_dir, additional images will be sampled with class_prompt."
137
+ ),
138
+ )
139
+ parser.add_argument(
140
+ "--validation_prompt",
141
+ type=str,
142
+ default=None,
143
+ help="A prompt that is used during validation to verify that the model is learning.",
144
+ )
145
+ parser.add_argument(
146
+ "--num_validation_images",
147
+ type=int,
148
+ default=4,
149
+ help="Number of images that should be generated during validation with `validation_prompt`.",
150
+ )
151
+ parser.add_argument(
152
+ "--validation_steps",
153
+ type=int,
154
+ default=100,
155
+ help=(
156
+ "Run dreambooth validation every X steps. Dreambooth validation consists of running the prompt"
157
+ " `args.validation_prompt` multiple times: `args.num_validation_images`."
158
+ ),
159
+ )
160
+ parser.add_argument(
161
+ "--output_dir",
162
+ type=str,
163
+ default="text-inversion-model",
164
+ help="The output directory where the model predictions and checkpoints will be written.",
165
+ )
166
+ parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
167
+ parser.add_argument(
168
+ "--resolution",
169
+ type=int,
170
+ default=512,
171
+ help=(
172
+ "The resolution for input images, all the images in the train/validation dataset will be resized to this"
173
+ " resolution"
174
+ ),
175
+ )
176
+ parser.add_argument(
177
+ "--center_crop", action="store_true", help="Whether to center crop images before resizing to resolution"
178
+ )
179
+ parser.add_argument("--train_text_encoder", action="store_true", help="Whether to train the text encoder")
180
+
181
+ # oft args
182
+ parser.add_argument("--use_oft", action="store_true", help="Whether to use OFT for parameter efficient tuning")
183
+ parser.add_argument("--oft_r", type=int, default=0, help="OFT rank, only used if use_oft is True")
184
+ parser.add_argument("--oft_block_size", type=int, default=32, help="OFT block size, only used if use_oft is True")
185
+ parser.add_argument("--oft_dropout", type=float, default=0.0, help="OFT dropout, only used if use_oft is True")
186
+ parser.add_argument(
187
+ "--oft_use_coft", action="store_true", help="Using constrained OFT, only used if use_oft is True"
188
+ )
189
+ parser.add_argument(
190
+ "--oft_eps",
191
+ type=float,
192
+ default=0.0,
193
+ help="The control strength of COFT. Only has an effect if `oft_use_coft` is set to True.",
194
+ )
195
+
196
+ parser.add_argument(
197
+ "--oft_text_encoder_r",
198
+ type=int,
199
+ default=0,
200
+ help="OFT rank for text encoder, only used if `use_oft` and `train_text_encoder` are True",
201
+ )
202
+ parser.add_argument(
203
+ "--oft_text_encoder_block_size",
204
+ type=int,
205
+ default=32,
206
+ help="OFT block size for text encoder, only used if `use_oft` and `train_text_encoder` are True",
207
+ )
208
+ parser.add_argument(
209
+ "--oft_text_encoder_dropout",
210
+ type=float,
211
+ default=0.0,
212
+ help="OFT dropout for text encoder, only used if `use_oft` and `train_text_encoder` are True",
213
+ )
214
+ parser.add_argument(
215
+ "--oft_text_encoder_use_coft",
216
+ action="store_true",
217
+ help="Using constrained OFT on the text encoder, only used if use_oft is True",
218
+ )
219
+ parser.add_argument(
220
+ "--oft_text_encoder_eps",
221
+ type=float,
222
+ default=0.0,
223
+ help="The control strength of COFT on the text encoder. Only has an effect if `oft_text_encoder_use_coft` is set to True.",
224
+ )
225
+
226
+ parser.add_argument(
227
+ "--num_dataloader_workers", type=int, default=1, help="Num of workers for the training dataloader."
228
+ )
229
+
230
+ parser.add_argument(
231
+ "--no_tracemalloc",
232
+ default=False,
233
+ action="store_true",
234
+ help="Flag to stop memory allocation tracing during training. This could speed up training on Windows.",
235
+ )
236
+
237
+ parser.add_argument(
238
+ "--train_batch_size", type=int, default=4, help="Batch size (per device) for the training dataloader."
239
+ )
240
+ parser.add_argument(
241
+ "--sample_batch_size", type=int, default=4, help="Batch size (per device) for sampling images."
242
+ )
243
+ parser.add_argument("--num_train_epochs", type=int, default=1)
244
+ parser.add_argument(
245
+ "--max_train_steps",
246
+ type=int,
247
+ default=None,
248
+ help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
249
+ )
250
+ parser.add_argument(
251
+ "--checkpointing_steps",
252
+ type=int,
253
+ default=500,
254
+ help=(
255
+ "Save a checkpoint of the training state every X updates. These checkpoints can be used both as final"
256
+ " checkpoints in case they are better than the last checkpoint, and are also suitable for resuming"
257
+ " training using `--resume_from_checkpoint`."
258
+ ),
259
+ )
260
+ parser.add_argument(
261
+ "--resume_from_checkpoint",
262
+ type=str,
263
+ default=None,
264
+ help=(
265
+ "Whether training should be resumed from a previous checkpoint. Use a path saved by"
266
+ ' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
267
+ ),
268
+ )
269
+ parser.add_argument(
270
+ "--gradient_accumulation_steps",
271
+ type=int,
272
+ default=1,
273
+ help="Number of updates steps to accumulate before performing a backward/update pass.",
274
+ )
275
+ parser.add_argument(
276
+ "--gradient_checkpointing",
277
+ action="store_true",
278
+ help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
279
+ )
280
+ parser.add_argument(
281
+ "--learning_rate",
282
+ type=float,
283
+ default=5e-6,
284
+ help="Initial learning rate (after the potential warmup period) to use.",
285
+ )
286
+ parser.add_argument(
287
+ "--scale_lr",
288
+ action="store_true",
289
+ default=False,
290
+ help="Scale the learning rate by the number of accelerators, gradient accumulation steps, and batch size.",
291
+ )
292
+ parser.add_argument(
293
+ "--lr_scheduler",
294
+ type=str,
295
+ default="constant",
296
+ help=(
297
+ 'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
298
+ ' "constant", "constant_with_warmup"]'
299
+ ),
300
+ )
301
+ parser.add_argument(
302
+ "--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
303
+ )
304
+ parser.add_argument(
305
+ "--lr_num_cycles",
306
+ type=int,
307
+ default=1,
308
+ help="Number of hard resets of the lr in cosine_with_restarts scheduler.",
309
+ )
310
+ parser.add_argument("--lr_power", type=float, default=1.0, help="Power factor of the polynomial scheduler.")
311
+ parser.add_argument(
312
+ "--use_8bit_adam", action="store_true", help="Whether or not to use 8-bit Adam from bitsandbytes."
313
+ )
314
+ parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
315
+ parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
316
+ parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
317
+ parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
318
+ parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
319
+ parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
320
+ parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
321
+ parser.add_argument(
322
+ "--hub_model_id",
323
+ type=str,
324
+ default=None,
325
+ help="The name of the repository to keep in sync with the local `output_dir`.",
326
+ )
327
+ parser.add_argument(
328
+ "--logging_dir",
329
+ type=str,
330
+ default="logs",
331
+ help=(
332
+ "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
333
+ " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
334
+ ),
335
+ )
336
+ parser.add_argument(
337
+ "--allow_tf32",
338
+ action="store_true",
339
+ help=(
340
+ "Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
341
+ " https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
342
+ ),
343
+ )
344
+ parser.add_argument(
345
+ "--report_to",
346
+ type=str,
347
+ default="tensorboard",
348
+ help=(
349
+ 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
350
+ ' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
351
+ ),
352
+ )
353
+ parser.add_argument(
354
+ "--wandb_key",
355
+ type=str,
356
+ default=None,
357
+ help=("If report to option is set to wandb, api-key for wandb used for login to wandb "),
358
+ )
359
+ parser.add_argument(
360
+ "--wandb_project_name",
361
+ type=str,
362
+ default=None,
363
+ help=("If report to option is set to wandb, project name in wandb for log tracking "),
364
+ )
365
+ parser.add_argument(
366
+ "--mixed_precision",
367
+ type=str,
368
+ default=None,
369
+ choices=["no", "fp16", "bf16"],
370
+ help=(
371
+ "Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
372
+ " 1.10.and an Nvidia Ampere GPU or Intel XPU. Default to the value of accelerate config of the current system or the"
373
+ " flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
374
+ ),
375
+ )
376
+ parser.add_argument(
377
+ "--prior_generation_precision",
378
+ type=str,
379
+ default=None,
380
+ choices=["no", "fp32", "fp16", "bf16"],
381
+ help=(
382
+ "Choose prior generation precision between fp32, fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
383
+ " 1.10.and an Nvidia Ampere GPU or Intel XPU. Default to fp16 if a GPU/XPU is available else fp32."
384
+ ),
385
+ )
386
+ parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
387
+ parser.add_argument(
388
+ "--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
389
+ )
390
+
391
+ if input_args is not None:
392
+ args = parser.parse_args(input_args)
393
+ else:
394
+ args = parser.parse_args()
395
+
396
+ env_local_rank = int(os.environ.get("LOCAL_RANK", "-1"))
397
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
398
+ args.local_rank = env_local_rank
399
+
400
+ if args.with_prior_preservation:
401
+ if args.class_data_dir is None:
402
+ raise ValueError("You must specify a data directory for class images.")
403
+ if args.class_prompt is None:
404
+ raise ValueError("You must specify prompt for class images.")
405
+ else:
406
+ # logger is not available yet
407
+ if args.class_data_dir is not None:
408
+ warnings.warn("You need not use --class_data_dir without --with_prior_preservation.")
409
+ if args.class_prompt is not None:
410
+ warnings.warn("You need not use --class_prompt without --with_prior_preservation.")
411
+
412
+ return args
413
+
414
+
415
+ # Converting Bytes to Megabytes
416
+ def b2mb(x):
417
+ return int(x / 2**20)
418
+
419
+
420
+ # This context manager is used to track the peak memory usage of the process
421
+ class TorchTracemalloc:
422
+ def __enter__(self):
423
+ self.device_type = torch.accelerator.current_accelerator().type if hasattr(torch, "accelerator") else "cuda"
424
+ self.device_module = getattr(torch, self.device_type, torch.cuda)
425
+ gc.collect()
426
+ self.device_module.empty_cache()
427
+ self.device_module.reset_peak_memory_stats() # reset the peak gauge to zero
428
+ self.begin = self.device_module.memory_allocated()
429
+ self.process = psutil.Process()
430
+
431
+ self.cpu_begin = self.cpu_mem_used()
432
+ self.peak_monitoring = True
433
+ peak_monitor_thread = threading.Thread(target=self.peak_monitor_func)
434
+ peak_monitor_thread.daemon = True
435
+ peak_monitor_thread.start()
436
+ return self
437
+
438
+ def cpu_mem_used(self):
439
+ """get resident set size memory for the current process"""
440
+ return self.process.memory_info().rss
441
+
442
+ def peak_monitor_func(self):
443
+ self.cpu_peak = -1
444
+
445
+ while True:
446
+ self.cpu_peak = max(self.cpu_mem_used(), self.cpu_peak)
447
+
448
+ # can't sleep or will not catch the peak right (this comment is here on purpose)
449
+ # time.sleep(0.001) # 1msec
450
+
451
+ if not self.peak_monitoring:
452
+ break
453
+
454
+ def __exit__(self, *exc):
455
+ self.peak_monitoring = False
456
+
457
+ gc.collect()
458
+ self.device_module.empty_cache()
459
+ self.end = self.device_module.memory_allocated()
460
+ self.peak = self.device_module.max_memory_allocated()
461
+ self.used = b2mb(self.end - self.begin)
462
+ self.peaked = b2mb(self.peak - self.begin)
463
+
464
+ self.cpu_end = self.cpu_mem_used()
465
+ self.cpu_used = b2mb(self.cpu_end - self.cpu_begin)
466
+ self.cpu_peaked = b2mb(self.cpu_peak - self.cpu_begin)
467
+ # print(f"delta used/peak {self.used:4d}/{self.peaked:4d}")
468
+
469
+
470
+ class DreamBoothDataset(Dataset):
471
+ """
472
+ A dataset to prepare the instance and class images with the prompts for fine-tuning the model.
473
+ It pre-processes the images and the tokenizes prompts.
474
+ """
475
+
476
+ def __init__(
477
+ self,
478
+ instance_data_root,
479
+ instance_prompt,
480
+ tokenizer,
481
+ class_data_root=None,
482
+ class_prompt=None,
483
+ size=512,
484
+ center_crop=False,
485
+ ):
486
+ self.size = size
487
+ self.center_crop = center_crop
488
+ self.tokenizer = tokenizer
489
+
490
+ self.instance_data_root = Path(instance_data_root)
491
+ if not self.instance_data_root.exists():
492
+ raise ValueError("Instance images root doesn't exists.")
493
+
494
+ self.instance_images_path = list(Path(instance_data_root).iterdir())
495
+ self.num_instance_images = len(self.instance_images_path)
496
+ self.instance_prompt = instance_prompt
497
+ self._length = self.num_instance_images
498
+
499
+ if class_data_root is not None:
500
+ self.class_data_root = Path(class_data_root)
501
+ self.class_data_root.mkdir(parents=True, exist_ok=True)
502
+ self.class_images_path = list(self.class_data_root.iterdir())
503
+ self.num_class_images = len(self.class_images_path)
504
+ self._length = max(self.num_class_images, self.num_instance_images)
505
+ self.class_prompt = class_prompt
506
+ else:
507
+ self.class_data_root = None
508
+
509
+ self.image_transforms = transforms.Compose(
510
+ [
511
+ transforms.Resize(size, interpolation=transforms.InterpolationMode.BILINEAR),
512
+ transforms.CenterCrop(size) if center_crop else transforms.RandomCrop(size),
513
+ transforms.ToTensor(),
514
+ transforms.Normalize([0.5], [0.5]),
515
+ ]
516
+ )
517
+
518
+ def __len__(self):
519
+ return self._length
520
+
521
+ def __getitem__(self, index):
522
+ example = {}
523
+ instance_image = Image.open(self.instance_images_path[index % self.num_instance_images])
524
+ if instance_image.mode != "RGB":
525
+ instance_image = instance_image.convert("RGB")
526
+ example["instance_images"] = self.image_transforms(instance_image)
527
+ example["instance_prompt_ids"] = self.tokenizer(
528
+ self.instance_prompt,
529
+ truncation=True,
530
+ padding="max_length",
531
+ max_length=self.tokenizer.model_max_length,
532
+ return_tensors="pt",
533
+ ).input_ids
534
+
535
+ if self.class_data_root:
536
+ class_image = Image.open(self.class_images_path[index % self.num_class_images])
537
+ if class_image.mode != "RGB":
538
+ class_image = class_image.convert("RGB")
539
+ example["class_images"] = self.image_transforms(class_image)
540
+ example["class_prompt_ids"] = self.tokenizer(
541
+ self.class_prompt,
542
+ truncation=True,
543
+ padding="max_length",
544
+ max_length=self.tokenizer.model_max_length,
545
+ return_tensors="pt",
546
+ ).input_ids
547
+
548
+ return example
549
+
550
+
551
+ def collate_fn(examples, with_prior_preservation=False):
552
+ input_ids = [example["instance_prompt_ids"] for example in examples]
553
+ pixel_values = [example["instance_images"] for example in examples]
554
+
555
+ # Concat class and instance examples for prior preservation.
556
+ # We do this to avoid doing two forward passes.
557
+ if with_prior_preservation:
558
+ input_ids += [example["class_prompt_ids"] for example in examples]
559
+ pixel_values += [example["class_images"] for example in examples]
560
+
561
+ pixel_values = torch.stack(pixel_values)
562
+ pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float()
563
+
564
+ input_ids = torch.cat(input_ids, dim=0)
565
+
566
+ batch = {
567
+ "input_ids": input_ids,
568
+ "pixel_values": pixel_values,
569
+ }
570
+ return batch
571
+
572
+
573
+ class PromptDataset(Dataset):
574
+ "A simple dataset to prepare the prompts to generate class images on multiple accelerators."
575
+
576
+ def __init__(self, prompt, num_samples):
577
+ self.prompt = prompt
578
+ self.num_samples = num_samples
579
+
580
+ def __len__(self):
581
+ return self.num_samples
582
+
583
+ def __getitem__(self, index):
584
+ example = {}
585
+ example["prompt"] = self.prompt
586
+ example["index"] = index
587
+ return example
588
+
589
+
590
+ def main(args):
591
+ logging_dir = Path(args.output_dir, args.logging_dir)
592
+
593
+ accelerator = Accelerator(
594
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
595
+ mixed_precision=args.mixed_precision,
596
+ log_with=args.report_to,
597
+ project_dir=logging_dir,
598
+ )
599
+ if args.report_to == "wandb":
600
+ import wandb
601
+
602
+ wandb.login(key=args.wandb_key)
603
+ wandb.init(project=args.wandb_project_name)
604
+ # Currently, it's not possible to do gradient accumulation when training two models with accelerate.accumulate
605
+ # This will be enabled soon in accelerate. For now, we don't allow gradient accumulation when training two models.
606
+ # TODO (patil-suraj): Remove this check when gradient accumulation with two models is enabled in accelerate.
607
+ if args.train_text_encoder and args.gradient_accumulation_steps > 1 and accelerator.num_processes > 1:
608
+ raise ValueError(
609
+ "Gradient accumulation is not supported when training the text encoder in distributed training. "
610
+ "Please set gradient_accumulation_steps to 1. This feature will be supported in the future."
611
+ )
612
+
613
+ # Make one log on every process with the configuration for debugging.
614
+ logging.basicConfig(
615
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
616
+ datefmt="%m/%d/%Y %H:%M:%S",
617
+ level=logging.INFO,
618
+ )
619
+ logger.info(accelerator.state, main_process_only=False)
620
+ if accelerator.is_local_main_process:
621
+ datasets.utils.logging.set_verbosity_warning()
622
+ transformers.utils.logging.set_verbosity_warning()
623
+ diffusers.utils.logging.set_verbosity_info()
624
+ else:
625
+ datasets.utils.logging.set_verbosity_error()
626
+ transformers.utils.logging.set_verbosity_error()
627
+ diffusers.utils.logging.set_verbosity_error()
628
+
629
+ # If passed along, set the training seed now.
630
+ if args.seed is not None:
631
+ set_seed(args.seed)
632
+
633
+ # Generate class images if prior preservation is enabled.
634
+ if args.with_prior_preservation:
635
+ class_images_dir = Path(args.class_data_dir)
636
+ if not class_images_dir.exists():
637
+ class_images_dir.mkdir(parents=True)
638
+ cur_class_images = len(list(class_images_dir.iterdir()))
639
+
640
+ if cur_class_images < args.num_class_images:
641
+ dtype = torch.float16 if accelerator.device.type in ["cuda", "xpu"] else torch.float32
642
+ if args.prior_generation_precision == "fp32":
643
+ dtype = torch.float32
644
+ elif args.prior_generation_precision == "fp16":
645
+ dtype = torch.float16
646
+ elif args.prior_generation_precision == "bf16":
647
+ dtype = torch.bfloat16
648
+ pipeline = DiffusionPipeline.from_pretrained(
649
+ args.pretrained_model_name_or_path,
650
+ dtype=dtype,
651
+ safety_checker=None,
652
+ revision=args.revision,
653
+ )
654
+ pipeline.set_progress_bar_config(disable=True)
655
+
656
+ num_new_images = args.num_class_images - cur_class_images
657
+ logger.info(f"Number of class images to sample: {num_new_images}.")
658
+
659
+ sample_dataset = PromptDataset(args.class_prompt, num_new_images)
660
+ sample_dataloader = torch.utils.data.DataLoader(sample_dataset, batch_size=args.sample_batch_size)
661
+
662
+ sample_dataloader = accelerator.prepare(sample_dataloader)
663
+ pipeline.to(accelerator.device)
664
+
665
+ for example in tqdm(
666
+ sample_dataloader, desc="Generating class images", disable=not accelerator.is_local_main_process
667
+ ):
668
+ images = pipeline(example["prompt"]).images
669
+
670
+ for i, image in enumerate(images):
671
+ hash_image = hashlib.sha1(image.tobytes()).hexdigest()
672
+ image_filename = class_images_dir / f"{example['index'][i] + cur_class_images}-{hash_image}.jpg"
673
+ image.save(image_filename)
674
+
675
+ del pipeline
676
+ if torch.cuda.is_available():
677
+ torch.cuda.empty_cache()
678
+ elif torch.xpu.is_available():
679
+ torch.xpu.empty_cache()
680
+
681
+ # Handle the repository creation
682
+ if accelerator.is_main_process:
683
+ if args.push_to_hub:
684
+ api = HfApi(token=args.hub_token)
685
+
686
+ # Create repo (repo_name from args or inferred)
687
+ repo_name = args.hub_model_id
688
+ if repo_name is None:
689
+ repo_name = Path(args.output_dir).absolute().name
690
+ repo_id = api.create_repo(repo_name, exist_ok=True).repo_id
691
+
692
+ with open(os.path.join(args.output_dir, ".gitignore"), "w+") as gitignore:
693
+ if "step_*" not in gitignore:
694
+ gitignore.write("step_*\n")
695
+ if "epoch_*" not in gitignore:
696
+ gitignore.write("epoch_*\n")
697
+ elif args.output_dir is not None:
698
+ os.makedirs(args.output_dir, exist_ok=True)
699
+
700
+ # Load the tokenizer
701
+ if args.tokenizer_name:
702
+ tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name, revision=args.revision, use_fast=False)
703
+ elif args.pretrained_model_name_or_path:
704
+ tokenizer = AutoTokenizer.from_pretrained(
705
+ args.pretrained_model_name_or_path,
706
+ subfolder="tokenizer",
707
+ revision=args.revision,
708
+ use_fast=False,
709
+ )
710
+
711
+ # import correct text encoder class
712
+ text_encoder_cls = import_model_class_from_model_name_or_path(args.pretrained_model_name_or_path, args.revision)
713
+
714
+ # Load scheduler and models
715
+ noise_scheduler = DDPMScheduler(
716
+ beta_start=0.00085,
717
+ beta_end=0.012,
718
+ beta_schedule="scaled_linear",
719
+ num_train_timesteps=1000,
720
+ ) # DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
721
+ text_encoder = text_encoder_cls.from_pretrained(
722
+ args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision
723
+ )
724
+ vae = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae", revision=args.revision)
725
+ unet = UNet2DConditionModel.from_pretrained(
726
+ args.pretrained_model_name_or_path, subfolder="unet", revision=args.revision
727
+ )
728
+
729
+ if args.use_oft:
730
+ config = OFTConfig(
731
+ r=args.oft_r,
732
+ oft_block_size=args.oft_block_size,
733
+ target_modules=UNET_TARGET_MODULES,
734
+ module_dropout=args.oft_dropout,
735
+ init_weights=True,
736
+ coft=args.oft_use_coft,
737
+ eps=args.oft_eps,
738
+ )
739
+ unet = get_peft_model(unet, config)
740
+ unet.print_trainable_parameters()
741
+ print(unet)
742
+
743
+ vae.requires_grad_(False)
744
+ if not args.train_text_encoder:
745
+ text_encoder.requires_grad_(False)
746
+ elif args.train_text_encoder and args.use_oft:
747
+ config = OFTConfig(
748
+ r=args.oft_text_encoder_r,
749
+ oft_block_size=args.oft_text_encoder_block_size,
750
+ target_modules=TEXT_ENCODER_TARGET_MODULES,
751
+ module_dropout=args.oft_text_encoder_dropout,
752
+ init_weights=True,
753
+ coft=args.oft_text_encoder_use_coft,
754
+ eps=args.oft_text_encoder_eps,
755
+ )
756
+ text_encoder = get_peft_model(text_encoder, config)
757
+ text_encoder.print_trainable_parameters()
758
+ print(text_encoder)
759
+
760
+ if args.enable_xformers_memory_efficient_attention:
761
+ if accelerator.device.type == "xpu":
762
+ logger.warning("XPU hasn't support xformers yet, ignore it.")
763
+ elif is_xformers_available():
764
+ unet.enable_xformers_memory_efficient_attention()
765
+ else:
766
+ raise ValueError("xformers is not available. Make sure it is installed correctly")
767
+
768
+ if args.gradient_checkpointing:
769
+ unet.enable_gradient_checkpointing()
770
+ # below fails when using oft so commenting it out
771
+ if args.train_text_encoder and not args.use_oft:
772
+ text_encoder.gradient_checkpointing_enable()
773
+
774
+ # Enable TF32 for faster training on Ampere GPUs,
775
+ # cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
776
+ if args.allow_tf32 and torch.cuda.is_available():
777
+ torch.backends.cuda.matmul.allow_tf32 = True
778
+
779
+ if args.scale_lr:
780
+ args.learning_rate = (
781
+ args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
782
+ )
783
+
784
+ # Use 8-bit Adam for lower memory usage or to fine-tune the model in 16GB accelerators
785
+ if args.use_8bit_adam:
786
+ try:
787
+ import bitsandbytes as bnb
788
+ except ImportError:
789
+ raise ImportError(
790
+ "To use 8-bit Adam, please install the bitsandbytes library: `pip install bitsandbytes`."
791
+ )
792
+
793
+ optimizer_class = bnb.optim.AdamW8bit
794
+ else:
795
+ optimizer_class = torch.optim.AdamW
796
+
797
+ # Optimizer creation
798
+ params_to_optimize = (
799
+ itertools.chain(unet.parameters(), text_encoder.parameters()) if args.train_text_encoder else unet.parameters()
800
+ )
801
+ optimizer = optimizer_class(
802
+ params_to_optimize,
803
+ lr=args.learning_rate,
804
+ betas=(args.adam_beta1, args.adam_beta2),
805
+ weight_decay=args.adam_weight_decay,
806
+ eps=args.adam_epsilon,
807
+ )
808
+
809
+ # Dataset and DataLoaders creation:
810
+ train_dataset = DreamBoothDataset(
811
+ instance_data_root=args.instance_data_dir,
812
+ instance_prompt=args.instance_prompt,
813
+ class_data_root=args.class_data_dir if args.with_prior_preservation else None,
814
+ class_prompt=args.class_prompt,
815
+ tokenizer=tokenizer,
816
+ size=args.resolution,
817
+ center_crop=args.center_crop,
818
+ )
819
+
820
+ train_dataloader = torch.utils.data.DataLoader(
821
+ train_dataset,
822
+ batch_size=args.train_batch_size,
823
+ shuffle=True,
824
+ collate_fn=lambda examples: collate_fn(examples, args.with_prior_preservation),
825
+ num_workers=args.num_dataloader_workers,
826
+ )
827
+
828
+ # Scheduler and math around the number of training steps.
829
+ overrode_max_train_steps = False
830
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
831
+ if args.max_train_steps is None:
832
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
833
+ overrode_max_train_steps = True
834
+
835
+ lr_scheduler = get_scheduler(
836
+ args.lr_scheduler,
837
+ optimizer=optimizer,
838
+ num_warmup_steps=args.lr_warmup_steps * args.gradient_accumulation_steps,
839
+ num_training_steps=args.max_train_steps * args.gradient_accumulation_steps,
840
+ num_cycles=args.lr_num_cycles,
841
+ power=args.lr_power,
842
+ )
843
+
844
+ # Prepare everything with our `accelerator`.
845
+ if args.train_text_encoder:
846
+ unet, text_encoder, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
847
+ unet, text_encoder, optimizer, train_dataloader, lr_scheduler
848
+ )
849
+ else:
850
+ unet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
851
+ unet, optimizer, train_dataloader, lr_scheduler
852
+ )
853
+
854
+ # For mixed precision training we cast the text_encoder and vae weights to half-precision
855
+ # as these models are only used for inference, keeping weights in full precision is not required.
856
+ weight_dtype = torch.float32
857
+ if accelerator.mixed_precision == "fp16":
858
+ weight_dtype = torch.float16
859
+ elif accelerator.mixed_precision == "bf16":
860
+ weight_dtype = torch.bfloat16
861
+
862
+ # Move vae and text_encoder to device and cast to weight_dtype
863
+ vae.to(accelerator.device, dtype=weight_dtype)
864
+ if not args.train_text_encoder:
865
+ text_encoder.to(accelerator.device, dtype=weight_dtype)
866
+
867
+ # We need to recalculate our total training steps as the size of the training dataloader may have changed.
868
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
869
+ if overrode_max_train_steps:
870
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
871
+ # Afterwards we recalculate our number of training epochs
872
+ args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
873
+
874
+ # We need to initialize the trackers we use, and also store our configuration.
875
+ # The trackers initializes automatically on the main process.
876
+ if accelerator.is_main_process:
877
+ accelerator.init_trackers("dreambooth", config=vars(args))
878
+
879
+ # Train!
880
+ total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
881
+
882
+ logger.info("***** Running training *****")
883
+ logger.info(f" Num examples = {len(train_dataset)}")
884
+ logger.info(f" Num batches each epoch = {len(train_dataloader)}")
885
+ logger.info(f" Num Epochs = {args.num_train_epochs}")
886
+ logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
887
+ logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
888
+ logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
889
+ logger.info(f" Total optimization steps = {args.max_train_steps}")
890
+ global_step = 0
891
+ first_epoch = 0
892
+
893
+ # Potentially load in the weights and states from a previous save
894
+ if args.resume_from_checkpoint:
895
+ if args.resume_from_checkpoint != "latest":
896
+ path = os.path.basename(args.resume_from_checkpoint)
897
+ else:
898
+ # Get the mos recent checkpoint
899
+ dirs = os.listdir(args.output_dir)
900
+ dirs = [d for d in dirs if d.startswith("checkpoint")]
901
+ dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
902
+ path = dirs[-1]
903
+ accelerator.print(f"Resuming from checkpoint {path}")
904
+ accelerator.load_state(os.path.join(args.output_dir, path))
905
+ global_step = int(path.split("-")[1])
906
+
907
+ resume_global_step = global_step * args.gradient_accumulation_steps
908
+ first_epoch = resume_global_step // num_update_steps_per_epoch
909
+ resume_step = resume_global_step % num_update_steps_per_epoch
910
+
911
+ # Only show the progress bar once on each machine.
912
+ progress_bar = tqdm(range(global_step, args.max_train_steps), disable=not accelerator.is_local_main_process)
913
+ progress_bar.set_description("Steps")
914
+
915
+ for epoch in range(first_epoch, args.num_train_epochs):
916
+ unet.train()
917
+ if args.train_text_encoder:
918
+ text_encoder.train()
919
+ with TorchTracemalloc() if not args.no_tracemalloc else nullcontext() as tracemalloc:
920
+ for step, batch in enumerate(train_dataloader):
921
+ # Skip steps until we reach the resumed step
922
+ if args.resume_from_checkpoint and epoch == first_epoch and step < resume_step:
923
+ if step % args.gradient_accumulation_steps == 0:
924
+ progress_bar.update(1)
925
+ if args.report_to == "wandb":
926
+ accelerator.print(progress_bar)
927
+ continue
928
+
929
+ with accelerator.accumulate(unet):
930
+ # Convert images to latent space
931
+ latents = vae.encode(batch["pixel_values"].to(dtype=weight_dtype)).latent_dist.sample()
932
+ latents = latents * 0.18215
933
+
934
+ # Sample noise that we'll add to the latents
935
+ noise = torch.randn_like(latents)
936
+ bsz = latents.shape[0]
937
+ # Sample a random timestep for each image
938
+ timesteps = torch.randint(
939
+ 0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device
940
+ )
941
+ timesteps = timesteps.long()
942
+
943
+ # Add noise to the latents according to the noise magnitude at each timestep
944
+ # (this is the forward diffusion process)
945
+ noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
946
+
947
+ # Get the text embedding for conditioning
948
+ encoder_hidden_states = text_encoder(batch["input_ids"])[0]
949
+
950
+ # Predict the noise residual
951
+ model_pred = unet(noisy_latents, timesteps, encoder_hidden_states).sample
952
+
953
+ # Get the target for loss depending on the prediction type
954
+ if noise_scheduler.config.prediction_type == "epsilon":
955
+ target = noise
956
+ elif noise_scheduler.config.prediction_type == "v_prediction":
957
+ target = noise_scheduler.get_velocity(latents, noise, timesteps)
958
+ else:
959
+ raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
960
+
961
+ if args.with_prior_preservation:
962
+ # Chunk the noise and model_pred into two parts and compute the loss on each part separately.
963
+ model_pred, model_pred_prior = torch.chunk(model_pred, 2, dim=0)
964
+ target, target_prior = torch.chunk(target, 2, dim=0)
965
+
966
+ # Compute instance loss
967
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
968
+
969
+ # Compute prior loss
970
+ prior_loss = F.mse_loss(model_pred_prior.float(), target_prior.float(), reduction="mean")
971
+
972
+ # Add the prior loss to the instance loss.
973
+ loss = loss + args.prior_loss_weight * prior_loss
974
+ else:
975
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
976
+
977
+ accelerator.backward(loss)
978
+ if accelerator.sync_gradients:
979
+ params_to_clip = (
980
+ itertools.chain(unet.parameters(), text_encoder.parameters())
981
+ if args.train_text_encoder
982
+ else unet.parameters()
983
+ )
984
+ accelerator.clip_grad_norm_(params_to_clip, args.max_grad_norm)
985
+ optimizer.step()
986
+ lr_scheduler.step()
987
+ optimizer.zero_grad()
988
+
989
+ # Checks if the accelerator has performed an optimization step behind the scenes
990
+ if accelerator.sync_gradients:
991
+ progress_bar.update(1)
992
+ if args.report_to == "wandb":
993
+ accelerator.print(progress_bar)
994
+ global_step += 1
995
+
996
+ logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
997
+ progress_bar.set_postfix(**logs)
998
+ accelerator.log(logs, step=global_step)
999
+
1000
+ if (
1001
+ args.validation_prompt is not None
1002
+ and (step + num_update_steps_per_epoch * epoch) % args.validation_steps == 0
1003
+ ):
1004
+ logger.info(
1005
+ f"Running validation... \n Generating {args.num_validation_images} images with prompt:"
1006
+ f" {args.validation_prompt}."
1007
+ )
1008
+ # create pipeline
1009
+ pipeline = DiffusionPipeline.from_pretrained(
1010
+ args.pretrained_model_name_or_path,
1011
+ safety_checker=None,
1012
+ revision=args.revision,
1013
+ )
1014
+ # set `keep_fp32_wrapper` to True because we do not want to remove
1015
+ # mixed precision hooks while we are still training
1016
+ pipeline.unet = accelerator.unwrap_model(unet, keep_fp32_wrapper=True)
1017
+ pipeline.text_encoder = accelerator.unwrap_model(text_encoder, keep_fp32_wrapper=True)
1018
+ pipeline.scheduler = DPMSolverMultistepScheduler.from_config(pipeline.scheduler.config)
1019
+ pipeline = pipeline.to(accelerator.device)
1020
+ pipeline.set_progress_bar_config(disable=True)
1021
+
1022
+ # run inference
1023
+ if args.seed is not None:
1024
+ generator = torch.Generator(device=accelerator.device).manual_seed(args.seed)
1025
+ else:
1026
+ generator = None
1027
+ images = []
1028
+ for _ in range(args.num_validation_images):
1029
+ image = pipeline(args.validation_prompt, num_inference_steps=25, generator=generator).images[0]
1030
+ images.append(image)
1031
+
1032
+ for tracker in accelerator.trackers:
1033
+ if tracker.name == "tensorboard":
1034
+ np_images = np.stack([np.asarray(img) for img in images])
1035
+ tracker.writer.add_images("validation", np_images, epoch, dataformats="NHWC")
1036
+ if tracker.name == "wandb":
1037
+ import wandb
1038
+
1039
+ tracker.log(
1040
+ {
1041
+ "validation": [
1042
+ wandb.Image(image, caption=f"{i}: {args.validation_prompt}")
1043
+ for i, image in enumerate(images)
1044
+ ]
1045
+ }
1046
+ )
1047
+
1048
+ del pipeline
1049
+ if torch.cuda.is_available():
1050
+ torch.cuda.empty_cache()
1051
+ elif torch.xpu.is_available():
1052
+ torch.xpu.empty_cache()
1053
+
1054
+ if global_step >= args.max_train_steps:
1055
+ break
1056
+
1057
+ # Printing the accelerator memory usage details such as allocated memory, peak memory, and total memory usage
1058
+ if not args.no_tracemalloc:
1059
+ accelerator.print(
1060
+ f"{accelerator.device.type.upper()} Memory before entering the train : {b2mb(tracemalloc.begin)}"
1061
+ )
1062
+ accelerator.print(
1063
+ f"{accelerator.device.type.upper()} Memory consumed at the end of the train (end-begin): {tracemalloc.used}"
1064
+ )
1065
+ accelerator.print(
1066
+ f"{accelerator.device.type.upper()} Peak Memory consumed during the train (max-begin): {tracemalloc.peaked}"
1067
+ )
1068
+ accelerator.print(
1069
+ f"{accelerator.device.type.upper()} Total Peak Memory consumed during the train (max): {tracemalloc.peaked + b2mb(tracemalloc.begin)}"
1070
+ )
1071
+
1072
+ accelerator.print(f"CPU Memory before entering the train : {b2mb(tracemalloc.cpu_begin)}")
1073
+ accelerator.print(f"CPU Memory consumed at the end of the train (end-begin): {tracemalloc.cpu_used}")
1074
+ accelerator.print(f"CPU Peak Memory consumed during the train (max-begin): {tracemalloc.cpu_peaked}")
1075
+ accelerator.print(
1076
+ f"CPU Total Peak Memory consumed during the train (max): {tracemalloc.cpu_peaked + b2mb(tracemalloc.cpu_begin)}"
1077
+ )
1078
+
1079
+ # Create the pipeline using using the trained modules and save it.
1080
+ accelerator.wait_for_everyone()
1081
+ if accelerator.is_main_process:
1082
+ if args.use_oft:
1083
+ unwarpped_unet = accelerator.unwrap_model(unet)
1084
+ unwarpped_unet.save_pretrained(
1085
+ os.path.join(args.output_dir, "unet"), state_dict=accelerator.get_state_dict(unet)
1086
+ )
1087
+ if args.train_text_encoder:
1088
+ unwarpped_text_encoder = accelerator.unwrap_model(text_encoder)
1089
+ unwarpped_text_encoder.save_pretrained(
1090
+ os.path.join(args.output_dir, "text_encoder"),
1091
+ state_dict=accelerator.get_state_dict(text_encoder),
1092
+ )
1093
+ else:
1094
+ pipeline = DiffusionPipeline.from_pretrained(
1095
+ args.pretrained_model_name_or_path,
1096
+ unet=accelerator.unwrap_model(unet),
1097
+ text_encoder=accelerator.unwrap_model(text_encoder),
1098
+ revision=args.revision,
1099
+ )
1100
+ pipeline.save_pretrained(args.output_dir)
1101
+
1102
+ if args.push_to_hub:
1103
+ api.upload_folder(
1104
+ repo_id=repo_id,
1105
+ folder_path=args.output_dir,
1106
+ commit_message="End of training",
1107
+ run_as_future=True,
1108
+ )
1109
+
1110
+ accelerator.end_training()
1111
+
1112
+
1113
+ if __name__ == "__main__":
1114
+ args = parse_args()
1115
+ main(args)
tasks/tasksmith-c488fc138ba1/tests/source/examples/olora_finetuning/README.md ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # OLoRA: Orthonormal Low Rank Adaptation of Large Language Models
2
+
3
+ ## Introduction
4
+ [OLoRA](https://huggingface.co/papers/2406.01775) is a novel approach that leverages orthonormal low rank adaptation through QR decomposition. Unlike the default LoRA implementation, OLoRA decomposes original weights into their $\mathbf{Q}$ and $\mathbf{R}$ parts, and then uses the first `rank` rows of $\mathbf{R}$ and the first `rank` columns of $\mathbf{Q}$ to initialize $\mathbf{A}$ and $\mathbf{B}$, respectively. This results in significantly faster convergence, more stable training, and superior performance.
5
+
6
+ ## Quick start
7
+ ```python
8
+ import torch
9
+ from peft import LoraConfig, get_peft_model
10
+ from transformers import AutoTokenizer, AutoModelForCausalLM
11
+ from trl import SFTConfig, SFTTrainer
12
+ from datasets import load_dataset
13
+
14
+ model = AutoModelForCausalLM.from_pretrained("facebook/opt-350m", dtype=torch.bfloat16, device_map="auto")
15
+ tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m")
16
+ dataset = load_dataset("imdb", split="train[:1%]")
17
+ lora_config = LoraConfig(
18
+ init_lora_weights="olora"
19
+ )
20
+ peft_model = get_peft_model(model, lora_config)
21
+ training_args = SFTConfig(dataset_text_field="text", max_length=128)
22
+ trainer = SFTTrainer(
23
+ model=peft_model,
24
+ train_dataset=dataset,
25
+ processing_class=tokenizer,
26
+ )
27
+ trainer.train()
28
+ peft_model.save_pretrained("olora-opt-350m")
29
+ ```
30
+
31
+ There is no additional change needed to your standard LoRA procedure, except for specifying `init_lora_weights = "olora"` option in your lora configuration.
32
+
33
+ Additionally you can refer to olora finetuning script.
34
+ Run the script simply by running:
35
+ ```bash
36
+ python3 examples/olora_finetuning/olora_finetuning.py --base_model facebook/opt-350m
37
+ ```
38
+ OLoRA also supports quantization. To use 4-bit quantization try:
39
+ ```bash
40
+ python3 examples/olora_finetuning/olora_finetuning.py --base_model facebook/opt-350m --quantize
41
+ ```
42
+ or you can just pass a quantized model without the quantize flag.
43
+
44
+ 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:
45
+ ```bash
46
+ accelerate launch examples/olora_finetuning/olora_finetuning.py --base_model facebook/opt-350m
47
+ ```
48
+ please add `--device_map cpu` if you want to run finetune on CPU.
49
+
50
+ If you want to train a quantized model like AWQ and GPTQ which do not support olora init method, please pass `--init_lora_weights gaussian`. For example:
51
+ ```bash
52
+ python3 examples/olora_finetuning/olora_finetuning.py --base_model hugging-quants/Meta-Llama-3.1-8B-Instruct-AWQ-INT4 --init_lora_weights gaussian
53
+
54
+ ```
55
+
56
+
57
+ ## Use the model
58
+ You can load and use the model as any other 🤗 PEFT model
59
+ ```python
60
+ from peft import PeftModel
61
+ model = AutoModelForCausalLM.from_pretrained("facebook/opt-350m")
62
+ tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m")
63
+ olora_model = PeftModel.from_pretrained(model, "olora-opt-350m")
64
+ ```
65
+
66
+ ## OLoRA and LoRA
67
+ OLoRA differs from LoRA in that it mutates the original weights. To utilize multiple adapters simultaneously, you can leverage the `path_initial_model_for_weight_conversion` option. Below is a simple template illustrating how to convert OLoRA to conventional LoRA:
68
+ ```python
69
+ base_model = AutoModel.from_pretrained("facebook/opt-350m")
70
+ olora_config = LoraConfig(
71
+ ...
72
+ init_lora_weights = "olora" # Initialize the model with OLoRA
73
+ )
74
+ olora_model = get_peft_model(base_model, olora_config)
75
+ init_path = <path-to-untrained-olora-model>
76
+ olora_model.save_pretrained(init_path) # Save the model *before* performing any training
77
+
78
+ # Train the model
79
+ train(olora_model) # Your training loop
80
+
81
+ #Save the model after training
82
+ olora_model.save_pretrained(output_dir, path_initial_model_for_weight_conversion=init_path)
83
+ ```
84
+ After completing training, you can save and convert your OLoRA model to a conventional LoRA model by setting `path_initial_model_for_weight_conversion` to `init_path`, that is the path of your untrained OLoRA model. This conversion enables you to use multiple adapters with your LoRA model. Note that this conversion is not supported if `rslora` is used in combination with `rank_pattern` or `alpha_pattern`.
85
+
86
+ ## Citation
87
+ ```
88
+ @misc{büyükakyüz2024olora,
89
+ title={OLoRA: Orthonormal Low-Rank Adaptation of Large Language Models},
90
+ author={Kerim Büyükakyüz},
91
+ year={2024},
92
+ eprint={2406.01775},
93
+ archivePrefix={arXiv},
94
+ primaryClass={cs.CL}
95
+ }
96
+ ```
tasks/tasksmith-c488fc138ba1/tests/source/examples/olora_finetuning/olora_finetuning.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ 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, BitsAndBytesConfig, set_seed
23
+
24
+ from peft import (
25
+ LoraConfig,
26
+ get_peft_model,
27
+ )
28
+
29
+
30
+ def train(
31
+ base_model: str = "path/to/model",
32
+ data_path: str = "yahma/alpaca-cleaned",
33
+ output_dir: str = "olora",
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
+ quantize: bool = False,
40
+ eval_step: int = 100,
41
+ save_step: int = 100,
42
+ device_map: str = "auto",
43
+ lora_r: int = 32,
44
+ lora_alpha: int = 16,
45
+ lora_dropout: float = 0.05,
46
+ lora_target_modules: Optional[list[str]] = None,
47
+ dtype: str = "float16",
48
+ init_lora_weights="olora",
49
+ seed: Optional[int] = None,
50
+ ):
51
+ # Set device_map to the right place when enabling DDP.
52
+ world_size = int(os.environ.get("WORLD_SIZE", "0")) or int(os.environ.get("PMI_SIZE", "0"))
53
+ if world_size > 1 and device_map != "cpu":
54
+ from accelerate import Accelerator
55
+
56
+ device_map = {"": Accelerator().process_index}
57
+ # Set seed
58
+ if seed is not None:
59
+ set_seed(seed)
60
+ model_kwargs = {"dtype": getattr(torch, dtype), "device_map": device_map}
61
+ if quantize:
62
+ model_kwargs["quantization_config"] = BitsAndBytesConfig(
63
+ load_in_4bit=True,
64
+ bnb_4bit_compute_dtype=torch.bfloat16,
65
+ bnb_4bit_use_double_quant=True,
66
+ bnb_4bit_quant_type="nf4",
67
+ )
68
+ model = AutoModelForCausalLM.from_pretrained(base_model, **model_kwargs)
69
+
70
+ tokenizer = AutoTokenizer.from_pretrained(base_model, trust_remote_code=True)
71
+ # For some tokenizer with no pad token like llama
72
+ if tokenizer.pad_token is None:
73
+ tokenizer.pad_token = tokenizer.eos_token
74
+
75
+ def tokenize(prompt, add_eos_token=True):
76
+ result = tokenizer(
77
+ prompt,
78
+ truncation=True,
79
+ max_length=cutoff_len,
80
+ padding=False,
81
+ return_tensors=None,
82
+ )
83
+ if (
84
+ result["input_ids"][-1] != tokenizer.eos_token_id
85
+ and len(result["input_ids"]) < cutoff_len
86
+ and add_eos_token
87
+ ):
88
+ result["input_ids"].append(tokenizer.eos_token_id)
89
+ result["attention_mask"].append(1)
90
+
91
+ result["labels"] = result["input_ids"].copy()
92
+
93
+ return result
94
+
95
+ def generate_and_tokenize_prompt(example):
96
+ full_prompt = generate_prompt(example)
97
+ tokenized_full_prompt = tokenize(full_prompt)
98
+ return tokenized_full_prompt
99
+
100
+ config = LoraConfig(
101
+ r=lora_r,
102
+ lora_alpha=lora_alpha,
103
+ target_modules=lora_target_modules,
104
+ lora_dropout=lora_dropout,
105
+ bias="none",
106
+ task_type="CAUSAL_LM",
107
+ init_lora_weights=init_lora_weights,
108
+ )
109
+ model = get_peft_model(model, config)
110
+
111
+ data = load_dataset(data_path)
112
+
113
+ train_val = data["train"].train_test_split(test_size=val_set_size, shuffle=True, seed=42)
114
+ train_data = train_val["train"].shuffle().map(generate_and_tokenize_prompt)
115
+ val_data = train_val["test"].shuffle().map(generate_and_tokenize_prompt)
116
+
117
+ trainer = transformers.Trainer(
118
+ model=model,
119
+ train_dataset=train_data,
120
+ eval_dataset=val_data,
121
+ args=transformers.TrainingArguments(
122
+ per_device_train_batch_size=batch_size,
123
+ warmup_steps=100,
124
+ num_train_epochs=num_epochs,
125
+ learning_rate=learning_rate,
126
+ logging_steps=100,
127
+ optim="adamw_torch",
128
+ eval_strategy="steps",
129
+ save_strategy="steps",
130
+ eval_steps=eval_step,
131
+ save_steps=save_step,
132
+ output_dir=output_dir,
133
+ save_total_limit=3,
134
+ load_best_model_at_end=True,
135
+ ddp_find_unused_parameters=False if world_size > 1 else None,
136
+ ),
137
+ data_collator=transformers.DataCollatorForSeq2Seq(
138
+ tokenizer, pad_to_multiple_of=8, return_tensors="pt", padding=True
139
+ ),
140
+ )
141
+ trainer.train()
142
+ model.save_pretrained(output_dir)
143
+
144
+
145
+ def generate_prompt(example):
146
+ return f"""Below is an instruction that describes a task. Write a response that appropriately completes the request.
147
+ ### Instruction:
148
+ {example["instruction"]}
149
+ ### Response:
150
+ {example["output"]}"""
151
+
152
+
153
+ if __name__ == "__main__":
154
+ import argparse
155
+
156
+ parser = argparse.ArgumentParser()
157
+ parser.add_argument("--base_model", type=str, default="path/to/model")
158
+ parser.add_argument("--data_path", type=str, default="yahma/alpaca-cleaned")
159
+ parser.add_argument("--output_dir", type=str, default="olora")
160
+ parser.add_argument("--batch_size", type=int, default=16)
161
+ parser.add_argument("--num_epochs", type=int, default=1)
162
+ parser.add_argument("--learning_rate", type=float, default=3e-4)
163
+ parser.add_argument("--cutoff_len", type=int, default=256)
164
+ parser.add_argument("--val_set_size", type=int, default=16)
165
+ parser.add_argument("--quantize", action="store_true")
166
+ parser.add_argument("--eval_step", type=int, default=100)
167
+ parser.add_argument("--save_step", type=int, default=100)
168
+ parser.add_argument("--device_map", type=str, default="auto")
169
+ parser.add_argument("--lora_r", type=int, default=32)
170
+ parser.add_argument("--lora_alpha", type=int, default=16)
171
+ parser.add_argument("--lora_dropout", type=float, default=0.05)
172
+ parser.add_argument("--lora_target_modules", type=str, default=None)
173
+ parser.add_argument("--dtype", type=str, default="float16")
174
+ parser.add_argument("--init_lora_weights", type=str, default="olora")
175
+ parser.add_argument("--seed", type=int, default=None)
176
+
177
+ args = parser.parse_args()
178
+
179
+ train(
180
+ base_model=args.base_model,
181
+ data_path=args.data_path,
182
+ output_dir=args.output_dir,
183
+ batch_size=args.batch_size,
184
+ num_epochs=args.num_epochs,
185
+ learning_rate=args.learning_rate,
186
+ cutoff_len=args.cutoff_len,
187
+ val_set_size=args.val_set_size,
188
+ quantize=args.quantize,
189
+ eval_step=args.eval_step,
190
+ save_step=args.save_step,
191
+ device_map=args.device_map,
192
+ lora_r=args.lora_r,
193
+ lora_alpha=args.lora_alpha,
194
+ lora_dropout=args.lora_dropout,
195
+ lora_target_modules=args.lora_target_modules,
196
+ dtype=args.dtype,
197
+ init_lora_weights=args.init_lora_weights,
198
+ seed=args.seed,
199
+ )
tasks/tasksmith-c488fc138ba1/tests/source/examples/orthogonal_subspace_learning/README.md ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Orthogonal Subspace Fine-tuning (OSF) - Continual Learning Example
2
+
3
+ This example demonstrates OSF's ability to learn multiple tasks sequentially while preventing catastrophic forgetting, a key challenge in continual learning.
4
+
5
+ ## Introduction
6
+
7
+ **Orthogonal Subspace Fine-tuning (OSF)** is a parameter-efficient fine-tuning method designed specifically for continual learning scenarios. Unlike traditional fine-tuning which suffers from catastrophic forgetting when learning new tasks, OSF constrains parameter updates to be orthogonal to previously important directions, effectively preserving knowledge from earlier tasks.
8
+
9
+ ### Key Features
10
+
11
+ - **Prevents Catastrophic Forgetting**: Maintains performance on previous tasks while learning new ones
12
+ - **Full Model Capacity**: Unlike LoRA-based methods, OSF allows full-rank updates within the trainable subspace
13
+ - **Progressive Budget Allocation**: Gradually allocates more capacity to preserve previous knowledge
14
+ - **No Additional Parameters**: Modifies weights in-place without adding extra parameters per task
15
+
16
+ ## Quick Start
17
+
18
+ ### Installation
19
+
20
+ ```bash
21
+ pip install -e ".[dev]"
22
+ ```
23
+
24
+ ### Basic Usage
25
+
26
+ Run the continual learning example with OSF:
27
+
28
+ ```bash
29
+ python osf_continual_learning.py \
30
+ --model_name meta-llama/Llama-3.1-8B-Instruct \
31
+ --num_train 1000 \
32
+ --num_eval 200 \
33
+ --num_epochs 2 \
34
+ --output_dir ./outputs
35
+ ```
36
+
37
+ To compare with full fine-tuning baseline:
38
+
39
+ ```bash
40
+ python osf_continual_learning.py \
41
+ --model_name meta-llama/Llama-3.1-8B-Instruct \
42
+ --run_baseline \
43
+ --output_dir ./outputs
44
+ ```
45
+
46
+ ## Continual Learning Scenario
47
+
48
+ This example trains a model on three different tasks sequentially:
49
+
50
+ 1. **ScienceQA** - Science question answering across natural, language, and social sciences
51
+ 2. **NumGLUE** - Mathematical reasoning and numerical understanding
52
+ 3. **FOMC** - Financial sentiment classification (Dovish/Hawkish/Neutral)
53
+
54
+ ### Progressive Capacity Allocation
55
+
56
+ OSF uses a progressive budget allocation strategy where each task gets decreasing trainable capacity while preserving more knowledge from previous tasks:
57
+
58
+ | Task | Effective Rank | Preserved | Trainable | Description |
59
+ |------|----------------|-----------|-----------|-------------|
60
+ | Task 1 (ScienceQA) | 0.3 | 30% | 70% | Maximum capacity for first task |
61
+ | Task 2 (NumGLUE) | 0.5 | 50% | 50% | Balanced capacity allocation |
62
+ | Task 3 (FOMC) | 0.7 | 70% | 30% | Minimal capacity, maximum preservation |
63
+
64
+ This allocation ensures:
65
+ - Early tasks get sufficient capacity to learn effectively
66
+ - Later tasks can still learn new patterns
67
+ - Previous knowledge is progressively protected from interference
68
+
69
+ ## How OSF Works
70
+
71
+ OSF decomposes each weight matrix using SVD into high-rank (preserved) and low-rank (trainable) components:
72
+
73
+ ```
74
+ W = U_high @ S_high @ V_high^T + U_low @ S_low @ V_low^T
75
+ └─────────┬─────────┘ └──────┬──────┘
76
+ frozen trainable
77
+ (previous tasks) (current task)
78
+ ```
79
+
80
+ During training:
81
+ 1. **Initialization**: Perform SVD on each weight matrix
82
+ 2. **Partitioning**: Split singular values based on `effective_rank`
83
+ 3. **Freezing**: Freeze top-k singular directions (high-rank subspace)
84
+ 4. **Training**: Update remaining directions (low-rank subspace)
85
+ 5. **Gradient Projection**: Ensure updates are orthogonal to frozen subspace
86
+
87
+ Between tasks:
88
+ 1. **Unload**: Merge OSF components back into base model
89
+ 2. **Re-initialize**: Perform fresh SVD with increased `effective_rank`
90
+ 3. **Continue**: Train on next task with larger frozen subspace
91
+
92
+ ## Command Line Arguments
93
+
94
+ ```
95
+ --model_name Model to use (default: meta-llama/Llama-3.1-8B-Instruct)
96
+ --num_train Number of training samples per task (default: 1000)
97
+ --num_eval Number of evaluation samples per task (default: 200)
98
+ --output_dir Directory for outputs (default: ./osf_continual_learning_outputs)
99
+ --num_epochs Training epochs per task (default: 2)
100
+ --learning_rate Learning rate (default: 5e-6)
101
+ --batch_size Batch size per device (default: 32)
102
+ --gradient_accumulation_steps Gradient accumulation (default: 1)
103
+ --max_length Maximum sequence length (default: 512)
104
+ --seed Random seed (default: 42)
105
+ --run_baseline Also run full fine-tuning baseline for comparison
106
+ ```
107
+
108
+ ## Expected Results
109
+
110
+ ### OSF Performance
111
+
112
+ When using OSF (with 2 epochs per task), you should observe:
113
+ - **Reduced catastrophic forgetting**: Performance on earlier tasks degrades less compared to full fine-tuning
114
+ - **Continued learning**: Model successfully learns each new task
115
+ - **Better retention**: OSF maintains higher average accuracy across all tasks
116
+
117
+ ### Full Fine-tuning Baseline
118
+
119
+ Standard full fine-tuning typically shows:
120
+ - **Catastrophic forgetting**: Significant performance degradation on earlier tasks
121
+ - **Last task bias**: Model performs well only on the most recent task
122
+ - **Task interference**: New task learning overwrites previous knowledge
123
+
124
+ ## Understanding the Results
125
+
126
+ ### Forgetting Analysis
127
+
128
+ The script prints a forgetting analysis showing how much earlier task performance changes.
129
+
130
+ **Example results from training with 2 epochs per task:**
131
+
132
+ ```
133
+ SUMMARY METRICS
134
+ ================================================================================
135
+
136
+ 1. Average Accuracy Across All 3 Tasks (After Final Task):
137
+ OSF: 53.42%
138
+ Full FT: 46.26%
139
+ Difference: +7.17% (OSF better)
140
+
141
+ 2. Average Forgetting (Task 1 & 2):
142
+ Forgetting = Final Accuracy - Initial Accuracy (negative is worse)
143
+
144
+ ScienceQA:
145
+ OSF: +30.50% (initial: 55.00% → final: 85.50%)
146
+ Full FT: -13.00% (initial: 84.50% → final: 71.50%)
147
+ Difference: +43.50% (OSF better)
148
+
149
+ NumGLUE:
150
+ OSF: +30.00% (initial: 16.00% → final: 46.00%)
151
+ Full FT: +1.00% (initial: 37.50% → final: 38.50%)
152
+ Difference: +29.00% (OSF better)
153
+
154
+ Average Forgetting:
155
+ OSF: +30.25%
156
+ Full FT: -6.00%
157
+ Difference: +36.25% (OSF better)
158
+ ```
159
+
160
+ **Interpreting Forgetting Metrics:**
161
+ - **Negative values** = Forgetting occurred (performance decreased)
162
+ - **Positive values** = Backward transfer occurred (performance improved)
163
+ - **Values closer to 0** = Better retention
164
+
165
+ In this example, OSF shows significant positive backward transfer (+30.25% average), while Full FT shows slight forgetting (-6.00% average). This demonstrates OSF's ability to not only prevent catastrophic forgetting but also enable beneficial knowledge transfer across tasks.
166
+
167
+ ## Advanced Usage
168
+
169
+ ### Custom Task Configuration
170
+
171
+ You can modify the tasks and capacity allocation in the script:
172
+
173
+ ```python
174
+ tasks = [
175
+ {
176
+ "name": "Task1",
177
+ "train": task1_train,
178
+ "eval": task1_eval,
179
+ "effective_rank": 0.2, # Freeze 20%, train 80%
180
+ },
181
+ {
182
+ "name": "Task2",
183
+ "train": task2_train,
184
+ "eval": task2_eval,
185
+ "effective_rank": 0.6, # Freeze 60%, train 40%
186
+ },
187
+ ]
188
+ ```
189
+
190
+ ### Using Different Models
191
+
192
+ OSF works with any transformer-based model:
193
+
194
+ ```bash
195
+ # Smaller model for faster experimentation
196
+ python osf_continual_learning.py --model_name gpt2
197
+
198
+ # Different LLaMA variant
199
+ python osf_continual_learning.py --model_name meta-llama/Llama-2-7b-hf
200
+ ```
201
+
202
+ ### Adjusting Target Modules
203
+
204
+ In the script, you can modify which modules to apply OSF to:
205
+
206
+ ```python
207
+ config = OSFConfig(
208
+ target_modules=["q_proj", "k_proj", "v_proj", "o_proj"], # Attention only
209
+ effective_rank=task["effective_rank"],
210
+ )
211
+ ```
212
+
213
+ Common configurations:
214
+ - **Attention only**: `["q_proj", "k_proj", "v_proj", "o_proj"]`
215
+ - **Attention + MLP**: `["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]`
216
+ - **All linear**: `target_modules="all-linear"`
217
+
218
+ ## Customization
219
+
220
+ ### Adding Your Own Tasks
221
+
222
+ To add custom tasks, create data loading and formatting functions in `utils.py`:
223
+
224
+ ```python
225
+ def load_my_task(num_train=1000, num_eval=200, seed=42):
226
+ """Load your custom dataset."""
227
+ dataset = load_dataset("your/dataset")
228
+ # ... split and return
229
+ return train_dataset, eval_dataset
230
+
231
+ def format_my_task_for_llama(examples, tokenizer, max_length=512):
232
+ """Format your task for instruction following."""
233
+ prompts = []
234
+ labels_text = []
235
+
236
+ for i in range(len(examples)):
237
+ prompt = f"Your instruction template: {examples['input'][i]}"
238
+ label = examples['output'][i]
239
+
240
+ prompts.append(prompt)
241
+ labels_text.append(label)
242
+
243
+ # ... tokenization logic
244
+ return formatted_examples
245
+ ```
246
+
247
+ Then add to the tasks list in `osf_continual_learning.py`.
248
+
249
+ ## Performance Tips
250
+
251
+ ### Memory Optimization
252
+
253
+ For large models, consider:
254
+ - Reducing `batch_size` and increasing `gradient_accumulation_steps`
255
+ - Using smaller `max_length`
256
+ - Enabling gradient checkpointing (add to model before OSF):
257
+ ```python
258
+ model.gradient_checkpointing_enable()
259
+ ```
260
+
261
+ ### Training Speed
262
+
263
+ To speed up training:
264
+ - Reduce `num_train` and `num_eval` for initial testing
265
+ - Use smaller models (e.g., `gpt2` or `Llama-2-7b`)
266
+ - Reduce `max_length` for shorter sequences
267
+
268
+ ### Better Results
269
+
270
+ For improved continual learning performance:
271
+ - Play around with `num_epochs` per task (try 2-3 epochs)
272
+ - Adjust `learning_rate`
273
+ - Experiment with different capacity allocation strategies
274
+
275
+ ## Citation
276
+
277
+ If you use OSF in your research, please cite:
278
+
279
+ ```bibtex
280
+ @misc{nayak2025sculptingsubspacesconstrainedfinetuning,
281
+ title={Sculpting Subspaces: Constrained Full Fine-Tuning in LLMs for Continual Learning},
282
+ author={Nikhil Shivakumar Nayak and Krishnateja Killamsetty and Ligong Han and Abhishek Bhandwaldar and Prateek Chanda and Kai Xu and Hao Wang and Aldo Pareja and Oleg Silkin and Mustafa Eyceoz and Akash Srivastava},
283
+ year={2025},
284
+ eprint={2504.07097},
285
+ archivePrefix={arXiv},
286
+ primaryClass={cs.LG},
287
+ url={https://arxiv.org/abs/2504.07097},
288
+ }
289
+ ```
290
+
291
+ ## Additional Resources
292
+
293
+ - [OSF Documentation](../../docs/source/package_reference/osf.md)
294
+ - [PEFT Documentation](https://huggingface.co/docs/peft)
295
+ - [Original Paper](https://huggingface.co/papers/2504.07097)
296
+
297
+ ## License
298
+
299
+ This example is licensed under Apache 2.0. See the PEFT repository for full license details.
tasks/tasksmith-c488fc138ba1/tests/source/examples/orthogonal_subspace_learning/osf_continual_learning.py ADDED
@@ -0,0 +1,693 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ OSF Continual Learning Example
17
+
18
+ This script demonstrates OSF's ability to learn multiple tasks sequentially while preventing
19
+ catastrophic forgetting, compared to standard full fine-tuning.
20
+
21
+ Tasks:
22
+ 1. ScienceQA - Science question answering
23
+ 2. NumGLUE - Mathematical reasoning
24
+ 3. FOMC - Financial sentiment classification
25
+
26
+ OSF Configuration:
27
+ - Task 1: effective_rank=0.3 (train 70%, freeze 30%)
28
+ - Task 2: effective_rank=0.5 (train 50%, freeze 50%)
29
+ - Task 3: effective_rank=0.7 (train 30%, freeze 70%)
30
+ """
31
+
32
+ import argparse
33
+ import os
34
+ import re
35
+
36
+ import torch
37
+ from transformers import AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments
38
+ from utils import (
39
+ DataCollatorForCompletionOnly,
40
+ format_fomc_for_llama,
41
+ format_numglue_for_llama,
42
+ format_scienceqa_for_llama,
43
+ load_fomc,
44
+ load_numglue,
45
+ load_scienceqa,
46
+ )
47
+
48
+ from peft import OSFConfig, get_peft_model
49
+
50
+
51
+ def compute_accuracy_scienceqa(model, eval_dataset, tokenizer, data_collator):
52
+ """Compute accuracy for ScienceQA (extract predicted letter)."""
53
+ model.eval()
54
+ correct = 0
55
+ total = 0
56
+
57
+ # Create a simple dataloader
58
+ from torch.utils.data import DataLoader
59
+
60
+ dataloader = DataLoader(eval_dataset, batch_size=8, collate_fn=data_collator)
61
+
62
+ with torch.no_grad():
63
+ for batch in dataloader:
64
+ input_ids = batch["input_ids"].to(model.device)
65
+ attention_mask = batch["attention_mask"].to(model.device)
66
+ labels = batch["labels"]
67
+
68
+ # Generate predictions
69
+ outputs = model.generate(
70
+ input_ids=input_ids,
71
+ attention_mask=attention_mask,
72
+ max_new_tokens=5,
73
+ pad_token_id=tokenizer.pad_token_id,
74
+ do_sample=False,
75
+ )
76
+
77
+ # Extract predictions and ground truth
78
+ for i in range(len(outputs)):
79
+ # Decode the generated text
80
+ generated_text = tokenizer.decode(outputs[i], skip_special_tokens=True)
81
+
82
+ # Extract the answer (last letter in the generated text)
83
+ # Look for single capital letters A, B, C, D
84
+ matches = re.findall(r"\b([A-D])\b", generated_text)
85
+ pred = matches[-1] if matches else "X"
86
+
87
+ # Get ground truth (find the label that's not -100)
88
+ label_ids = labels[i][labels[i] != -100]
89
+ if len(label_ids) > 0:
90
+ gt = tokenizer.decode(label_ids, skip_special_tokens=True).strip()
91
+ if pred == gt:
92
+ correct += 1
93
+ total += 1
94
+
95
+ accuracy = correct / total if total > 0 else 0.0
96
+ return accuracy
97
+
98
+
99
+ def compute_accuracy_numglue(model, eval_dataset, tokenizer, data_collator):
100
+ """Compute accuracy for NumGLUE (extract predicted number)."""
101
+ model.eval()
102
+ correct = 0
103
+ total = 0
104
+
105
+ from torch.utils.data import DataLoader
106
+
107
+ dataloader = DataLoader(eval_dataset, batch_size=8, collate_fn=data_collator)
108
+
109
+ with torch.no_grad():
110
+ for batch in dataloader:
111
+ input_ids = batch["input_ids"].to(model.device)
112
+ attention_mask = batch["attention_mask"].to(model.device)
113
+ labels = batch["labels"]
114
+
115
+ outputs = model.generate(
116
+ input_ids=input_ids,
117
+ attention_mask=attention_mask,
118
+ max_new_tokens=20,
119
+ pad_token_id=tokenizer.pad_token_id,
120
+ do_sample=False,
121
+ )
122
+
123
+ for i in range(len(outputs)):
124
+ generated_text = tokenizer.decode(outputs[i], skip_special_tokens=True)
125
+
126
+ # Extract number from generated text
127
+ numbers = re.findall(r"-?\d+\.?\d*", generated_text)
128
+ pred = numbers[-1] if numbers else "-999"
129
+
130
+ # Get ground truth
131
+ label_ids = labels[i][labels[i] != -100]
132
+ if len(label_ids) > 0:
133
+ gt = tokenizer.decode(label_ids, skip_special_tokens=True).strip()
134
+ if pred == gt:
135
+ correct += 1
136
+ total += 1
137
+
138
+ accuracy = correct / total if total > 0 else 0.0
139
+ return accuracy
140
+
141
+
142
+ def compute_accuracy_fomc(model, eval_dataset, tokenizer, data_collator):
143
+ """Compute accuracy for FOMC (extract predicted sentiment)."""
144
+ model.eval()
145
+ correct = 0
146
+ total = 0
147
+
148
+ from torch.utils.data import DataLoader
149
+
150
+ dataloader = DataLoader(eval_dataset, batch_size=8, collate_fn=data_collator)
151
+
152
+ valid_labels = ["Dovish", "Hawkish", "Neutral"]
153
+
154
+ with torch.no_grad():
155
+ for batch in dataloader:
156
+ input_ids = batch["input_ids"].to(model.device)
157
+ attention_mask = batch["attention_mask"].to(model.device)
158
+ labels = batch["labels"]
159
+
160
+ outputs = model.generate(
161
+ input_ids=input_ids,
162
+ attention_mask=attention_mask,
163
+ max_new_tokens=10,
164
+ pad_token_id=tokenizer.pad_token_id,
165
+ do_sample=False,
166
+ )
167
+
168
+ for i in range(len(outputs)):
169
+ generated_text = tokenizer.decode(outputs[i], skip_special_tokens=True)
170
+
171
+ # Extract sentiment label
172
+ pred = None
173
+ for label in valid_labels:
174
+ if label in generated_text:
175
+ pred = label
176
+ break
177
+
178
+ # Get ground truth
179
+ label_ids = labels[i][labels[i] != -100]
180
+ if len(label_ids) > 0:
181
+ gt = tokenizer.decode(label_ids, skip_special_tokens=True).strip()
182
+ if pred == gt:
183
+ correct += 1
184
+ total += 1
185
+
186
+ accuracy = correct / total if total > 0 else 0.0
187
+ return accuracy
188
+
189
+
190
+ def evaluate_model(model, eval_dataset, data_collator, tokenizer, task_name, task_type):
191
+ """Evaluate model on a dataset and return loss and accuracy."""
192
+ # Compute loss
193
+ trainer = Trainer(
194
+ model=model,
195
+ data_collator=data_collator,
196
+ eval_dataset=eval_dataset,
197
+ args=TrainingArguments(
198
+ label_names=["labels"],
199
+ ),
200
+ )
201
+ results = trainer.evaluate()
202
+ loss = results["eval_loss"]
203
+
204
+ # Compute accuracy based on task type
205
+ if task_type == "scienceqa":
206
+ accuracy = compute_accuracy_scienceqa(model, eval_dataset, tokenizer, data_collator)
207
+ elif task_type == "numglue":
208
+ accuracy = compute_accuracy_numglue(model, eval_dataset, tokenizer, data_collator)
209
+ elif task_type == "fomc":
210
+ accuracy = compute_accuracy_fomc(model, eval_dataset, tokenizer, data_collator)
211
+ else:
212
+ accuracy = 0.0
213
+
214
+ print(f" {task_name}: Loss = {loss:.4f}, Accuracy = {accuracy * 100:.2f}%")
215
+ return loss, accuracy
216
+
217
+
218
+ def train_with_osf(
219
+ model_name,
220
+ num_train,
221
+ num_eval,
222
+ output_dir,
223
+ num_epochs,
224
+ learning_rate,
225
+ batch_size,
226
+ gradient_accumulation_steps,
227
+ max_length,
228
+ seed,
229
+ ):
230
+ """Train using OSF with progressive rank allocation."""
231
+ print("\n" + "=" * 80)
232
+ print("TRAINING WITH OSF (Orthogonal Subspace Fine-tuning)")
233
+ print("=" * 80)
234
+
235
+ # Load tokenizer and base model
236
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
237
+ tokenizer.pad_token = tokenizer.eos_token
238
+
239
+ base_model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.bfloat16, device_map="auto")
240
+
241
+ # Load all datasets with task-specific sizes
242
+ # FOMC only has 496 samples total, so we use 350 train + 146 eval for it
243
+ print("\nLoading datasets...")
244
+ scienceqa_train, scienceqa_eval = load_scienceqa(1000, 200, seed)
245
+ numglue_train, numglue_eval = load_numglue(1000, 200, seed)
246
+ fomc_train, fomc_eval = load_fomc(350, 146, seed)
247
+
248
+ # Store original eval datasets for later
249
+ scienceqa_eval_original = scienceqa_eval
250
+ numglue_eval_original = numglue_eval
251
+ fomc_eval_original = fomc_eval
252
+
253
+ # Format datasets
254
+ scienceqa_train = scienceqa_train.map(
255
+ lambda x: format_scienceqa_for_llama(x, tokenizer, max_length),
256
+ batched=True,
257
+ remove_columns=scienceqa_train.column_names,
258
+ )
259
+ scienceqa_eval = scienceqa_eval.map(
260
+ lambda x: format_scienceqa_for_llama(x, tokenizer, max_length),
261
+ batched=True,
262
+ remove_columns=scienceqa_eval.column_names,
263
+ )
264
+
265
+ numglue_train = numglue_train.map(
266
+ lambda x: format_numglue_for_llama(x, tokenizer, max_length),
267
+ batched=True,
268
+ remove_columns=numglue_train.column_names,
269
+ )
270
+ numglue_eval = numglue_eval.map(
271
+ lambda x: format_numglue_for_llama(x, tokenizer, max_length),
272
+ batched=True,
273
+ remove_columns=numglue_eval.column_names,
274
+ )
275
+
276
+ fomc_train = fomc_train.map(
277
+ lambda x: format_fomc_for_llama(x, tokenizer, max_length), batched=True, remove_columns=fomc_train.column_names
278
+ )
279
+ fomc_eval = fomc_eval.map(
280
+ lambda x: format_fomc_for_llama(x, tokenizer, max_length), batched=True, remove_columns=fomc_eval.column_names
281
+ )
282
+
283
+ data_collator = DataCollatorForCompletionOnly(tokenizer, max_length)
284
+
285
+ # Task configurations
286
+ tasks = [
287
+ {
288
+ "name": "ScienceQA",
289
+ "train": scienceqa_train,
290
+ "eval": scienceqa_eval,
291
+ "eval_original": scienceqa_eval_original,
292
+ "effective_rank": 0.3, # Freeze 30%, train 70%
293
+ "type": "scienceqa",
294
+ },
295
+ {
296
+ "name": "NumGLUE",
297
+ "train": numglue_train,
298
+ "eval": numglue_eval,
299
+ "eval_original": numglue_eval_original,
300
+ "effective_rank": 0.5, # Freeze 50%, train 50%
301
+ "type": "numglue",
302
+ },
303
+ {
304
+ "name": "FOMC",
305
+ "train": fomc_train,
306
+ "eval": fomc_eval,
307
+ "eval_original": fomc_eval_original,
308
+ "effective_rank": 0.7, # Freeze 70%, train 30%
309
+ "type": "fomc",
310
+ },
311
+ ]
312
+
313
+ # Store evaluation history: {task_name: [(loss, accuracy), ...]}
314
+ eval_history = {
315
+ "ScienceQA": [],
316
+ "NumGLUE": [],
317
+ "FOMC": [],
318
+ }
319
+
320
+ # Sequential task training
321
+ model = base_model
322
+ for task_idx, task in enumerate(tasks):
323
+ print(f"\n{'=' * 80}")
324
+ print(f"TASK {task_idx + 1}: {task['name']}")
325
+ print(f"Effective Rank: {task['effective_rank']} (preserving {task['effective_rank'] * 100:.0f}%)")
326
+ print(f"{'=' * 80}")
327
+
328
+ # Configure OSF for this task
329
+ config = OSFConfig(
330
+ target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
331
+ effective_rank=task["effective_rank"],
332
+ )
333
+
334
+ # Apply OSF to the model
335
+ model = get_peft_model(model, config)
336
+
337
+ # Training arguments
338
+ training_args = TrainingArguments(
339
+ output_dir=f"{output_dir}/osf_{task['name'].lower()}",
340
+ num_train_epochs=num_epochs,
341
+ per_device_train_batch_size=batch_size,
342
+ gradient_accumulation_steps=gradient_accumulation_steps,
343
+ learning_rate=learning_rate,
344
+ logging_steps=10,
345
+ save_strategy="no",
346
+ bf16=True,
347
+ remove_unused_columns=False,
348
+ )
349
+
350
+ # Train on current task
351
+ trainer = Trainer(
352
+ model=model,
353
+ args=training_args,
354
+ train_dataset=task["train"],
355
+ data_collator=data_collator,
356
+ )
357
+
358
+ print(f"\nTraining on {task['name']}...")
359
+ trainer.train()
360
+
361
+ # Evaluate on all tasks seen so far
362
+ print(f"\nEvaluating on all tasks after training on {task['name']}:")
363
+ for eval_task_idx in range(task_idx + 1):
364
+ eval_task = tasks[eval_task_idx]
365
+ loss, accuracy = evaluate_model(
366
+ model, eval_task["eval"], data_collator, tokenizer, eval_task["name"], eval_task["type"]
367
+ )
368
+ eval_history[eval_task["name"]].append((loss, accuracy))
369
+
370
+ # Unload OSF to get the updated base model for next task (if not last task)
371
+ if task_idx < len(tasks) - 1:
372
+ print("\nUnloading OSF adapter to prepare for next task...")
373
+ model = model.unload()
374
+
375
+ # Save final model
376
+ final_model_path = f"{output_dir}/osf_final"
377
+ model.save_pretrained(final_model_path)
378
+ print(f"\nFinal OSF model saved to {final_model_path}")
379
+
380
+ return eval_history
381
+
382
+
383
+ def train_full_finetuning(
384
+ model_name,
385
+ num_train,
386
+ num_eval,
387
+ output_dir,
388
+ num_epochs,
389
+ learning_rate,
390
+ batch_size,
391
+ gradient_accumulation_steps,
392
+ max_length,
393
+ seed,
394
+ ):
395
+ """Train using standard full fine-tuning (baseline for comparison)."""
396
+ print("\n" + "=" * 80)
397
+ print("TRAINING WITH FULL FINE-TUNING (Baseline)")
398
+ print("=" * 80)
399
+
400
+ # Load tokenizer
401
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
402
+ tokenizer.pad_token = tokenizer.eos_token
403
+
404
+ # Load all datasets with task-specific sizes
405
+ # FOMC only has 496 samples total, so we use 350 train + 146 eval for it
406
+ print("\nLoading datasets...")
407
+ scienceqa_train, scienceqa_eval = load_scienceqa(1000, 200, seed)
408
+ numglue_train, numglue_eval = load_numglue(1000, 200, seed)
409
+ fomc_train, fomc_eval = load_fomc(350, 146, seed)
410
+
411
+ # Store original eval datasets
412
+ scienceqa_eval_original = scienceqa_eval
413
+ numglue_eval_original = numglue_eval
414
+ fomc_eval_original = fomc_eval
415
+
416
+ # Format datasets
417
+ scienceqa_train = scienceqa_train.map(
418
+ lambda x: format_scienceqa_for_llama(x, tokenizer, max_length),
419
+ batched=True,
420
+ remove_columns=scienceqa_train.column_names,
421
+ )
422
+ scienceqa_eval = scienceqa_eval.map(
423
+ lambda x: format_scienceqa_for_llama(x, tokenizer, max_length),
424
+ batched=True,
425
+ remove_columns=scienceqa_eval.column_names,
426
+ )
427
+
428
+ numglue_train = numglue_train.map(
429
+ lambda x: format_numglue_for_llama(x, tokenizer, max_length),
430
+ batched=True,
431
+ remove_columns=numglue_train.column_names,
432
+ )
433
+ numglue_eval = numglue_eval.map(
434
+ lambda x: format_numglue_for_llama(x, tokenizer, max_length),
435
+ batched=True,
436
+ remove_columns=numglue_eval.column_names,
437
+ )
438
+
439
+ fomc_train = fomc_train.map(
440
+ lambda x: format_fomc_for_llama(x, tokenizer, max_length), batched=True, remove_columns=fomc_train.column_names
441
+ )
442
+ fomc_eval = fomc_eval.map(
443
+ lambda x: format_fomc_for_llama(x, tokenizer, max_length), batched=True, remove_columns=fomc_eval.column_names
444
+ )
445
+
446
+ data_collator = DataCollatorForCompletionOnly(tokenizer, max_length)
447
+
448
+ tasks = [
449
+ {"name": "ScienceQA", "train": scienceqa_train, "eval": scienceqa_eval, "type": "scienceqa"},
450
+ {"name": "NumGLUE", "train": numglue_train, "eval": numglue_eval, "type": "numglue"},
451
+ {"name": "FOMC", "train": fomc_train, "eval": fomc_eval, "type": "fomc"},
452
+ ]
453
+
454
+ # Store evaluation history
455
+ eval_history = {
456
+ "ScienceQA": [],
457
+ "NumGLUE": [],
458
+ "FOMC": [],
459
+ }
460
+
461
+ # Load base model once
462
+ model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.bfloat16, device_map="auto")
463
+
464
+ # Sequential task training
465
+ for task_idx, task in enumerate(tasks):
466
+ print(f"\n{'=' * 80}")
467
+ print(f"TASK {task_idx + 1}: {task['name']}")
468
+ print(f"{'=' * 80}")
469
+
470
+ # Training arguments
471
+ training_args = TrainingArguments(
472
+ output_dir=f"{output_dir}/full_{task['name'].lower()}",
473
+ num_train_epochs=num_epochs,
474
+ per_device_train_batch_size=batch_size,
475
+ gradient_accumulation_steps=gradient_accumulation_steps,
476
+ learning_rate=learning_rate,
477
+ logging_steps=10,
478
+ save_strategy="no",
479
+ bf16=True,
480
+ remove_unused_columns=False,
481
+ )
482
+
483
+ # Train on current task
484
+ trainer = Trainer(
485
+ model=model,
486
+ args=training_args,
487
+ train_dataset=task["train"],
488
+ data_collator=data_collator,
489
+ )
490
+
491
+ print(f"\nTraining on {task['name']}...")
492
+ trainer.train()
493
+
494
+ # Evaluate on all tasks seen so far
495
+ print(f"\nEvaluating on all tasks after training on {task['name']}:")
496
+ for eval_task_idx in range(task_idx + 1):
497
+ eval_task = tasks[eval_task_idx]
498
+ loss, accuracy = evaluate_model(
499
+ model, eval_task["eval"], data_collator, tokenizer, eval_task["name"], eval_task["type"]
500
+ )
501
+ eval_history[eval_task["name"]].append((loss, accuracy))
502
+
503
+ # Save final model
504
+ final_model_path = f"{output_dir}/full_final"
505
+ model.save_pretrained(final_model_path)
506
+ print(f"\nFinal full fine-tuning model saved to {final_model_path}")
507
+
508
+ return eval_history
509
+
510
+
511
+ def print_results_comparison(osf_history, full_history):
512
+ """Print comparison table of OSF vs Full Fine-tuning."""
513
+ print("\n" + "=" * 80)
514
+ print("RESULTS COMPARISON: OSF vs Full Fine-tuning")
515
+ print("=" * 80)
516
+
517
+ tasks = ["ScienceQA", "NumGLUE", "FOMC"]
518
+
519
+ # Print detailed results
520
+ print("\n" + "-" * 80)
521
+ print("DETAILED RESULTS (Accuracy %)")
522
+ print("-" * 80)
523
+ print(f"{'Task':<15} {'After Task':<15} {'OSF Acc %':<15} {'Full FT Acc %':<15} {'Difference':<15}")
524
+ print("-" * 80)
525
+
526
+ for task_idx, task in enumerate(tasks):
527
+ for eval_after_idx in range(task_idx, len(tasks)):
528
+ eval_after = tasks[eval_after_idx]
529
+ osf_acc = osf_history[task][eval_after_idx - task_idx][1] * 100
530
+ full_acc = full_history[task][eval_after_idx - task_idx][1] * 100
531
+ diff = osf_acc - full_acc
532
+
533
+ print(
534
+ f"{task:<15} {eval_after:<15} {osf_acc:<15.2f} {full_acc:<15.2f} {diff:+15.2f}{' (OSF better)' if diff > 0 else ''}"
535
+ )
536
+
537
+ # Summary statistics
538
+ print("\n" + "=" * 80)
539
+ print("SUMMARY METRICS")
540
+ print("=" * 80)
541
+
542
+ # Final average accuracy across all 3 tasks
543
+ osf_final_accs = [osf_history[task][-1][1] * 100 for task in tasks]
544
+ full_final_accs = [full_history[task][-1][1] * 100 for task in tasks]
545
+
546
+ osf_avg_final = sum(osf_final_accs) / len(osf_final_accs)
547
+ full_avg_final = sum(full_final_accs) / len(full_final_accs)
548
+
549
+ print("\n1. Average Accuracy Across All 3 Tasks (After Final Task):")
550
+ print(f" OSF: {osf_avg_final:.2f}%")
551
+ print(f" Full FT: {full_avg_final:.2f}%")
552
+ print(
553
+ f" Difference: {osf_avg_final - full_avg_final:+.2f}% {'(OSF better)' if osf_avg_final > full_avg_final else '(Full FT better)'}"
554
+ )
555
+
556
+ # Average forgetting (for tasks 1 and 2 only, since task 3 is the final task)
557
+ print("\n2. Average Forgetting (Task 1 & 2):")
558
+ print(" Forgetting = Final Accuracy - Initial Accuracy (negative is worse)\n")
559
+
560
+ osf_forgetting_vals = []
561
+ full_forgetting_vals = []
562
+
563
+ for task_idx, task in enumerate(tasks[:-1]): # Exclude last task
564
+ osf_initial_acc = osf_history[task][0][1] * 100 # Right after learning task
565
+ osf_final_acc = osf_history[task][-1][1] * 100 # After learning all tasks
566
+ osf_forgetting = osf_final_acc - osf_initial_acc
567
+
568
+ full_initial_acc = full_history[task][0][1] * 100
569
+ full_final_acc = full_history[task][-1][1] * 100
570
+ full_forgetting = full_final_acc - full_initial_acc
571
+
572
+ osf_forgetting_vals.append(osf_forgetting)
573
+ full_forgetting_vals.append(full_forgetting)
574
+
575
+ print(f" {task}:")
576
+ print(f" OSF: {osf_forgetting:+.2f}% (initial: {osf_initial_acc:.2f}% → final: {osf_final_acc:.2f}%)")
577
+ print(
578
+ f" Full FT: {full_forgetting:+.2f}% (initial: {full_initial_acc:.2f}% → final: {full_final_acc:.2f}%)"
579
+ )
580
+ print(
581
+ f" Difference: {osf_forgetting - full_forgetting:+.2f}% {'(OSF better)' if osf_forgetting > full_forgetting else '(Full FT better)'}\n"
582
+ )
583
+
584
+ osf_avg_forgetting = sum(osf_forgetting_vals) / len(osf_forgetting_vals)
585
+ full_avg_forgetting = sum(full_forgetting_vals) / len(full_forgetting_vals)
586
+
587
+ print(" Average Forgetting:")
588
+ print(f" OSF: {osf_avg_forgetting:+.2f}%")
589
+ print(f" Full FT: {full_avg_forgetting:+.2f}%")
590
+ print(
591
+ f" Difference: {osf_avg_forgetting - full_avg_forgetting:+.2f}% {'(OSF better)' if osf_avg_forgetting > full_avg_forgetting else '(Full FT better)'}"
592
+ )
593
+
594
+ print("\n" + "=" * 80)
595
+
596
+
597
+ def main():
598
+ parser = argparse.ArgumentParser(description="OSF Continual Learning Example")
599
+ parser.add_argument(
600
+ "--model_name",
601
+ type=str,
602
+ default="meta-llama/Llama-3.1-8B-Instruct",
603
+ help="Model name or path",
604
+ )
605
+ parser.add_argument("--num_train", type=int, default=1000, help="Number of training samples per task")
606
+ parser.add_argument("--num_eval", type=int, default=200, help="Number of evaluation samples per task")
607
+ parser.add_argument("--output_dir", type=str, default="./osf_continual_learning_outputs", help="Output directory")
608
+ parser.add_argument("--num_epochs", type=int, default=2, help="Number of training epochs per task")
609
+ parser.add_argument("--learning_rate", type=float, default=5e-6, help="Learning rate")
610
+ parser.add_argument("--batch_size", type=int, default=32, help="Batch size per device")
611
+ parser.add_argument("--gradient_accumulation_steps", type=int, default=1, help="Gradient accumulation steps")
612
+ parser.add_argument("--max_length", type=int, default=512, help="Maximum sequence length")
613
+ parser.add_argument("--seed", type=int, default=42, help="Random seed")
614
+ parser.add_argument(
615
+ "--run_baseline",
616
+ action="store_true",
617
+ help="Also run full fine-tuning baseline for comparison",
618
+ )
619
+
620
+ args = parser.parse_args()
621
+
622
+ # Create output directory
623
+ os.makedirs(args.output_dir, exist_ok=True)
624
+
625
+ # Train with OSF
626
+ osf_history = train_with_osf(
627
+ args.model_name,
628
+ args.num_train,
629
+ args.num_eval,
630
+ args.output_dir,
631
+ args.num_epochs,
632
+ args.learning_rate,
633
+ args.batch_size,
634
+ args.gradient_accumulation_steps,
635
+ args.max_length,
636
+ args.seed,
637
+ )
638
+
639
+ # Optionally train with full fine-tuning baseline
640
+ if args.run_baseline:
641
+ full_history = train_full_finetuning(
642
+ args.model_name,
643
+ args.num_train,
644
+ args.num_eval,
645
+ args.output_dir,
646
+ args.num_epochs,
647
+ args.learning_rate,
648
+ args.batch_size,
649
+ args.gradient_accumulation_steps,
650
+ args.max_length,
651
+ args.seed,
652
+ )
653
+
654
+ # Print comparison
655
+ print_results_comparison(osf_history, full_history)
656
+ else:
657
+ print("\n" + "=" * 80)
658
+ print("OSF TRAINING COMPLETE")
659
+ print("=" * 80)
660
+ print("\nTo compare with full fine-tuning baseline, run with --run_baseline flag")
661
+
662
+ # Print OSF-only summary
663
+ tasks = ["ScienceQA", "NumGLUE", "FOMC"]
664
+ print("\n" + "=" * 80)
665
+ print("OSF SUMMARY METRICS")
666
+ print("=" * 80)
667
+
668
+ # Final average accuracy
669
+ osf_final_accs = [osf_history[task][-1][1] * 100 for task in tasks]
670
+ osf_avg_final = sum(osf_final_accs) / len(osf_final_accs)
671
+
672
+ print(f"\n1. Average Accuracy Across All 3 Tasks (After Final Task): {osf_avg_final:.2f}%")
673
+ for task, acc in zip(tasks, osf_final_accs):
674
+ print(f" {task}: {acc:.2f}%")
675
+
676
+ # Average forgetting
677
+ print("\n2. Average Forgetting (Task 1 & 2):")
678
+ osf_forgetting_vals = []
679
+ for task_idx, task in enumerate(tasks[:-1]):
680
+ osf_initial_acc = osf_history[task][0][1] * 100
681
+ osf_final_acc = osf_history[task][-1][1] * 100
682
+ osf_forgetting = osf_initial_acc - osf_final_acc
683
+ osf_forgetting_vals.append(osf_forgetting)
684
+
685
+ print(f" {task}: {osf_forgetting:+.2f}% (initial: {osf_initial_acc:.2f}% → final: {osf_final_acc:.2f}%)")
686
+
687
+ osf_avg_forgetting = sum(osf_forgetting_vals) / len(osf_forgetting_vals)
688
+ print(f" Average: {osf_avg_forgetting:+.2f}%")
689
+ print("\n" + "=" * 80)
690
+
691
+
692
+ if __name__ == "__main__":
693
+ main()
tasks/tasksmith-c488fc138ba1/tests/source/examples/orthogonal_subspace_learning/utils.py ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 torch
17
+ from datasets import load_dataset
18
+
19
+
20
+ def load_scienceqa(num_train=1000, num_eval=200, seed=42):
21
+ """
22
+ Load ScienceQA dataset for science question answering.
23
+
24
+ Args:
25
+ num_train: Number of training samples
26
+ num_eval: Number of evaluation samples
27
+ seed: Random seed for reproducibility
28
+
29
+ Returns:
30
+ train_dataset, eval_dataset
31
+ """
32
+ dataset = load_dataset("derek-thomas/ScienceQA", split="train")
33
+
34
+ # Shuffle and split
35
+ dataset = dataset.shuffle(seed=seed)
36
+ train_dataset = dataset.select(range(num_train))
37
+ eval_dataset = dataset.select(range(num_train, num_train + num_eval))
38
+
39
+ return train_dataset, eval_dataset
40
+
41
+
42
+ def load_numglue(num_train=1000, num_eval=200, seed=42):
43
+ """
44
+ Load NumGLUE dataset for mathematical reasoning.
45
+
46
+ Args:
47
+ num_train: Number of training samples
48
+ num_eval: Number of evaluation samples
49
+ seed: Random seed for reproducibility
50
+
51
+ Returns:
52
+ train_dataset, eval_dataset
53
+ """
54
+ import json
55
+
56
+ from datasets import Dataset
57
+ from huggingface_hub import hf_hub_download
58
+
59
+ # Download the NumGLUE JSON file manually
60
+ json_path = hf_hub_download(repo_id="metaeval/num-glue", filename="NumGLUE_train.json", repo_type="dataset")
61
+
62
+ # Read and process the JSON file line by line
63
+ data = []
64
+ with open(json_path) as f:
65
+ for line in f:
66
+ if line.strip(): # Skip empty lines
67
+ item = json.loads(line)
68
+ # Extract the number from the answer JSON structure
69
+ answer = item.get("answer", "")
70
+ if isinstance(answer, dict):
71
+ # NumGLUE answers are JSON with 'number' and 'date' fields
72
+ # Extract just the number field
73
+ answer_str = answer.get("number", "")
74
+ else:
75
+ answer_str = str(answer)
76
+
77
+ data.append({"question": item.get("question", ""), "answer": answer_str})
78
+
79
+ # Create dataset from processed data
80
+ dataset = Dataset.from_list(data)
81
+
82
+ # Shuffle and split
83
+ dataset = dataset.shuffle(seed=seed)
84
+ train_dataset = dataset.select(range(min(num_train, len(dataset))))
85
+
86
+ # If not enough samples, use what's available
87
+ eval_start = min(num_train, len(dataset))
88
+ eval_end = min(num_train + num_eval, len(dataset))
89
+ eval_dataset = dataset.select(range(eval_start, eval_end))
90
+
91
+ return train_dataset, eval_dataset
92
+
93
+
94
+ def load_fomc(num_train=1000, num_eval=200, seed=42):
95
+ """
96
+ Load FOMC dataset for financial sentiment classification.
97
+
98
+ Args:
99
+ num_train: Number of training samples
100
+ num_eval: Number of evaluation samples
101
+ seed: Random seed for reproducibility
102
+
103
+ Returns:
104
+ train_dataset, eval_dataset
105
+ """
106
+ dataset = load_dataset("TheFinAI/finben-fomc", split="test")
107
+
108
+ # Shuffle and split
109
+ dataset = dataset.shuffle(seed=seed)
110
+ train_dataset = dataset.select(range(min(num_train, len(dataset))))
111
+
112
+ eval_start = min(num_train, len(dataset))
113
+ eval_end = min(num_train + num_eval, len(dataset))
114
+ eval_dataset = dataset.select(range(eval_start, eval_end))
115
+
116
+ return train_dataset, eval_dataset
117
+
118
+
119
+ def format_scienceqa_for_llama(examples, tokenizer, max_length=512):
120
+ """Format ScienceQA examples for Llama instruction following."""
121
+ prompts = []
122
+ labels_text = []
123
+
124
+ for i in range(len(examples["question"])):
125
+ # Build the question with choices
126
+ question = examples["question"][i]
127
+ choices = examples["choices"][i]
128
+
129
+ # Format choices
130
+ choices_text = "\n".join([f"{chr(65 + j)}. {choice}" for j, choice in enumerate(choices)])
131
+
132
+ prompt = f"""Answer the following science question by selecting the correct option.
133
+ Question: {question}
134
+
135
+ Choices:
136
+ {choices_text}
137
+
138
+ Answer (just the letter):"""
139
+
140
+ # Get the answer (convert index to letter)
141
+ answer_idx = examples["answer"][i]
142
+ answer = chr(65 + answer_idx)
143
+
144
+ prompts.append(prompt)
145
+ labels_text.append(answer)
146
+
147
+ # Tokenize
148
+ model_inputs = tokenizer(prompts, max_length=max_length, truncation=True, padding=False)
149
+
150
+ # Tokenize labels
151
+ labels = tokenizer(labels_text, max_length=10, truncation=True, padding=False)
152
+
153
+ # Combine input and label for training
154
+ combined_input_ids = []
155
+ combined_attention_mask = []
156
+ combined_labels = []
157
+
158
+ for i in range(len(model_inputs["input_ids"])):
159
+ input_ids = model_inputs["input_ids"][i]
160
+ label_ids = labels["input_ids"][i]
161
+
162
+ # Combine input and label
163
+ combined = input_ids + label_ids + [tokenizer.eos_token_id]
164
+ combined_input_ids.append(combined)
165
+
166
+ # Attention mask
167
+ combined_attention_mask.append([1] * len(combined))
168
+
169
+ # Labels (mask the prompt part, only train on answer)
170
+ label_masked = [-100] * len(input_ids) + label_ids + [tokenizer.eos_token_id]
171
+ combined_labels.append(label_masked)
172
+
173
+ return {
174
+ "input_ids": combined_input_ids,
175
+ "attention_mask": combined_attention_mask,
176
+ "labels": combined_labels,
177
+ }
178
+
179
+
180
+ def format_numglue_for_llama(examples, tokenizer, max_length=512):
181
+ """Format NumGLUE examples for Llama instruction following."""
182
+ prompts = []
183
+ labels_text = []
184
+
185
+ for i in range(len(examples["question"])):
186
+ question = examples["question"][i]
187
+ answer = str(examples["answer"][i])
188
+
189
+ prompt = f"""Solve the following math problem and provide just the numerical answer.
190
+
191
+ Question: {question}
192
+
193
+ Answer:"""
194
+
195
+ prompts.append(prompt)
196
+ labels_text.append(answer)
197
+
198
+ # Tokenize
199
+ model_inputs = tokenizer(prompts, max_length=max_length, truncation=True, padding=False)
200
+ labels = tokenizer(labels_text, max_length=20, truncation=True, padding=False)
201
+
202
+ combined_input_ids = []
203
+ combined_attention_mask = []
204
+ combined_labels = []
205
+
206
+ for i in range(len(model_inputs["input_ids"])):
207
+ input_ids = model_inputs["input_ids"][i]
208
+ label_ids = labels["input_ids"][i]
209
+
210
+ combined = input_ids + label_ids + [tokenizer.eos_token_id]
211
+ combined_input_ids.append(combined)
212
+ combined_attention_mask.append([1] * len(combined))
213
+
214
+ label_masked = [-100] * len(input_ids) + label_ids + [tokenizer.eos_token_id]
215
+ combined_labels.append(label_masked)
216
+
217
+ return {
218
+ "input_ids": combined_input_ids,
219
+ "attention_mask": combined_attention_mask,
220
+ "labels": combined_labels,
221
+ }
222
+
223
+
224
+ def format_fomc_for_llama(examples, tokenizer, max_length=512):
225
+ """Format FOMC examples for Llama instruction following."""
226
+ prompts = []
227
+ labels_text = []
228
+
229
+ for i in range(len(examples["text"])):
230
+ text = examples["text"][i]
231
+ # FOMC dataset has 'answer' column with values like 'dovish', 'hawkish', 'neutral'
232
+ label = examples["answer"][i].capitalize() # Capitalize first letter
233
+
234
+ prompt = f"""Classify the sentiment of the following Federal Reserve statement as Dovish, Hawkish, or Neutral.
235
+
236
+ Statement: {text}
237
+
238
+ Sentiment:"""
239
+
240
+ prompts.append(prompt)
241
+ labels_text.append(label)
242
+
243
+ # Tokenize
244
+ model_inputs = tokenizer(prompts, max_length=max_length, truncation=True, padding=False)
245
+ labels = tokenizer(labels_text, max_length=10, truncation=True, padding=False)
246
+
247
+ combined_input_ids = []
248
+ combined_attention_mask = []
249
+ combined_labels = []
250
+
251
+ for i in range(len(model_inputs["input_ids"])):
252
+ input_ids = model_inputs["input_ids"][i]
253
+ label_ids = labels["input_ids"][i]
254
+
255
+ combined = input_ids + label_ids + [tokenizer.eos_token_id]
256
+ combined_input_ids.append(combined)
257
+ combined_attention_mask.append([1] * len(combined))
258
+
259
+ label_masked = [-100] * len(input_ids) + label_ids + [tokenizer.eos_token_id]
260
+ combined_labels.append(label_masked)
261
+
262
+ return {
263
+ "input_ids": combined_input_ids,
264
+ "attention_mask": combined_attention_mask,
265
+ "labels": combined_labels,
266
+ }
267
+
268
+
269
+ class DataCollatorForCompletionOnly:
270
+ """Data collator that pads sequences for training."""
271
+
272
+ def __init__(self, tokenizer, max_length=512):
273
+ self.tokenizer = tokenizer
274
+ self.max_length = max_length
275
+
276
+ def __call__(self, features):
277
+ # Pad sequences
278
+ max_len = min(max(len(f["input_ids"]) for f in features), self.max_length)
279
+
280
+ input_ids = []
281
+ attention_mask = []
282
+ labels = []
283
+
284
+ for f in features:
285
+ # Truncate if needed
286
+ curr_input_ids = f["input_ids"][:max_len]
287
+ curr_attention_mask = f["attention_mask"][:max_len]
288
+ curr_labels = f["labels"][:max_len]
289
+
290
+ # Pad
291
+ padding_length = max_len - len(curr_input_ids)
292
+ curr_input_ids = curr_input_ids + [self.tokenizer.pad_token_id] * padding_length
293
+ curr_attention_mask = curr_attention_mask + [0] * padding_length
294
+ curr_labels = curr_labels + [-100] * padding_length
295
+
296
+ input_ids.append(curr_input_ids)
297
+ attention_mask.append(curr_attention_mask)
298
+ labels.append(curr_labels)
299
+
300
+ return {
301
+ "input_ids": torch.tensor(input_ids, dtype=torch.long),
302
+ "attention_mask": torch.tensor(attention_mask, dtype=torch.long),
303
+ "labels": torch.tensor(labels, dtype=torch.long),
304
+ }
tasks/tasksmith-c488fc138ba1/tests/source/examples/peanut_finetuning/README.md ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PEANuT: Parameter-Efficient Adaptation with Weight-aware Neural Tweakers
2
+
3
+ ## Introduction
4
+ [**PEANuT**](https://arxiv.org/abs/2410.01870) is a PEFT method that introduces a **weight-aware neural tweaker** to generate adapter updates from the base weight itself. Instead of directly learning a low-rank decomposition `Delta W = A @ B` as in LoRA, PEANuT transforms the target layer weight through a small neural network (the neural tweaker) to produce `Delta W`.
5
+
6
+ PEANuT is built on three key ideas:
7
+
8
+ - **Weight-aware adaptation**: `Delta W` is produced by transforming the base weight using `A`, `B`, and optional intermediate layers. Because PEANuT applies `A` on the output dimension of the base weight, `A` has shape `(out_features, r)` instead of LoRA's typical `(in_features, r)`. When `in_features > out_features`, PEANuT can use fewer parameters than LoRA at the same rank.
9
+ - **Non-linearity inside the tweaker**: PEANuT inserts activation functions in the neural tweaker (default: `relu`) to increase expressiveness.
10
+ - **Depth capacity increase**: Besides mandatory `A` and `B`, PEANuT can insert intermediate `r x r` layers in residual encoder/decoder pairs. Here, `depth` counts the number of residual pairs, so `depth=0` means only `A` and `B`.
11
+
12
+ ## Quick start
13
+
14
+ With respect to your standard PEFT training procedure with LoRA, simply swap your `LoraConfig` for a `PeanutConfig`.
15
+
16
+ ```python
17
+ import torch
18
+ from datasets import load_dataset
19
+ from transformers import AutoModelForCausalLM, AutoTokenizer
20
+ from trl import SFTConfig, SFTTrainer
21
+
22
+ from peft import PeanutConfig
23
+
24
+ model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.2-3B", dtype=torch.bfloat16, device_map="auto")
25
+ tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.2-3B")
26
+ dataset = load_dataset("timdettmers/openassistant-guanaco", split="train")
27
+ peanut_config = PeanutConfig()
28
+
29
+ trainer = SFTTrainer(
30
+ model=model,
31
+ train_dataset=dataset,
32
+ processing_class=tokenizer,
33
+ peft_config=peanut_config,
34
+ args=SFTConfig(
35
+ max_length=2048,
36
+ dataset_text_field="text",
37
+ per_device_train_batch_size=2,
38
+ ),
39
+ )
40
+ trainer.train()
41
+ trainer.model.save_pretrained("peanut-llama-3.2-3b")
42
+ ```
43
+
44
+ Run the finetuning script simply by running:
45
+ ```sh
46
+ python examples/peanut_finetuning/peanut_finetuning.py --base_model meta-llama/Llama-3.2-3B --data_path timdettmers/openassistant-guanaco
47
+ ```
48
+
49
+ ## Use the model on Hugging Face
50
+ You can load and use the model as any other Hugging Face model.
51
+
52
+ ```python
53
+ import torch
54
+ from peft import PeftModel
55
+ from transformers import AutoModelForCausalLM
56
+
57
+ model = AutoModelForCausalLM.from_pretrained(
58
+ "meta-llama/Llama-3.2-3B", dtype=torch.bfloat16, device_map="auto"
59
+ )
60
+ peft_model = PeftModel.from_pretrained(model, "peanut-llama-3.2-3b")
61
+ ```
62
+
63
+ ## Additional Notes
64
+
65
+ - `r` controls the hidden rank of the neural tweaker. Larger `r` increases capacity and trainable parameters.
66
+ - `depth` controls the number of intermediate encoder/decoder residual pairs. It must be a non-negative integer.
67
+ - `depth=0` means only `A` and `B`.
68
+ - `depth=1` adds one encoder/decoder residual pair between `A` and `B`.
69
+ - Larger depths add more `r x r` residual pairs.
70
+ - `act_fn` controls the non-linearity inside PEANuT and defaults to `relu`.
71
+ - `scaling` is a direct scalar multiplier on the adapter output before it is added to the frozen base layer output.
72
+ - PEANuT can perform better than LoRA across a range of tasks. We also find it strong in very low-parameter regimes (for example around `0.2M` trainable parameters).
73
+ - Compared with LoRA, PEANuT typically uses more GPU memory and runs slower because it explicitly constructs `Delta W` during forward passes. Adding intermediate layers (higher `depth`) increases this overhead further.
74
+
75
+ ## Citation
76
+ ```bibtex
77
+ @misc{zhong2025peanutparameterefficientadaptationweightaware,
78
+ title={PEANuT: Parameter-Efficient Adaptation with Weight-aware Neural Tweakers},
79
+ author={Yibo Zhong and Haoxiang Jiang and Lincan Li and Ryumei Nakada and Tianci Liu and Linjun Zhang and Huaxiu Yao and Haoyu Wang},
80
+ year={2025},
81
+ eprint={2410.01870},
82
+ archivePrefix={arXiv},
83
+ primaryClass={cs.LG},
84
+ url={https://arxiv.org/abs/2410.01870},
85
+ }
86
+ ```
tasks/tasksmith-c488fc138ba1/tests/source/examples/peanut_finetuning/peanut_finetuning.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This script is based on examples/lily_finetuning/lily_finetuning.py
2
+ import os
3
+
4
+ import torch
5
+ from datasets import load_dataset
6
+ from transformers import (
7
+ AutoModelForCausalLM,
8
+ AutoTokenizer,
9
+ DataCollatorForLanguageModeling,
10
+ Trainer,
11
+ TrainingArguments,
12
+ )
13
+
14
+ from peft import PeanutConfig, get_peft_model
15
+
16
+
17
+ def train_model(
18
+ base_model: str,
19
+ data_path: str,
20
+ output_dir: str,
21
+ batch_size: int,
22
+ num_epochs: int,
23
+ learning_rate: float,
24
+ cutoff_len: int,
25
+ val_set_size: int,
26
+ eval_step: int,
27
+ save_step: int,
28
+ device: str,
29
+ peanut_r: int,
30
+ peanut_depth: int,
31
+ peanut_scaling: float,
32
+ peanut_act_fn: str,
33
+ peanut_target_modules: str,
34
+ peanut_init_weights: bool,
35
+ hub_model_id: str,
36
+ push_to_hub: bool,
37
+ ):
38
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
39
+ hf_token = os.getenv("HF_TOKEN")
40
+
41
+ # Setup device
42
+ if device == "auto":
43
+ device = torch.accelerator.current_accelerator().type if hasattr(torch, "accelerator") else "cuda"
44
+ else:
45
+ device = torch.device(device)
46
+ print(f"Using device: {device}")
47
+
48
+ # load tokenizer
49
+ tokenizer = AutoTokenizer.from_pretrained(base_model, token=hf_token)
50
+
51
+ model = AutoModelForCausalLM.from_pretrained(base_model, token=hf_token)
52
+
53
+ # PEANuT config for the PEFT model
54
+ peanut_config = PeanutConfig(
55
+ r=peanut_r,
56
+ depth=peanut_depth,
57
+ scaling=peanut_scaling,
58
+ act_fn=peanut_act_fn,
59
+ init_weights=peanut_init_weights,
60
+ target_modules=(
61
+ peanut_target_modules.split(",")
62
+ if peanut_target_modules
63
+ else ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
64
+ ),
65
+ )
66
+
67
+ # get the peft model with PEANuT config
68
+ model = get_peft_model(model, peanut_config)
69
+ model.print_trainable_parameters()
70
+
71
+ model.to(device)
72
+ tokenizer.pad_token = tokenizer.eos_token
73
+
74
+ # Load the dataset
75
+ dataset = load_dataset(data_path)
76
+
77
+ def tokenize_function(examples):
78
+ inputs = tokenizer(examples["text"], padding="max_length", truncation=True, max_length=cutoff_len)
79
+ inputs["labels"] = inputs["input_ids"].copy() # setting labels for a language modeling task
80
+ return inputs
81
+
82
+ # Tokenize the dataset and prepare for training
83
+ tokenized_datasets = dataset.map(tokenize_function, batched=True, remove_columns=dataset["train"].column_names)
84
+
85
+ # Data collator to dynamically pad the batched examples
86
+ data_collator = DataCollatorForLanguageModeling(tokenizer, mlm=False)
87
+
88
+ # Define training arguments
89
+ training_args = TrainingArguments(
90
+ output_dir=output_dir,
91
+ num_train_epochs=num_epochs,
92
+ per_device_train_batch_size=batch_size,
93
+ per_device_eval_batch_size=batch_size,
94
+ warmup_steps=100,
95
+ weight_decay=0.01,
96
+ logging_steps=eval_step,
97
+ save_steps=save_step,
98
+ save_total_limit=2,
99
+ push_to_hub=push_to_hub,
100
+ hub_model_id=hub_model_id,
101
+ gradient_accumulation_steps=16,
102
+ fp16=True,
103
+ learning_rate=learning_rate,
104
+ hub_token=hf_token,
105
+ )
106
+
107
+ # Clear device cache to free memory
108
+ if torch.cuda.is_available():
109
+ torch.cuda.empty_cache()
110
+ elif torch.xpu.is_available():
111
+ torch.xpu.empty_cache()
112
+
113
+ # Initialize the Trainer
114
+ trainer = Trainer(
115
+ model=model,
116
+ args=training_args,
117
+ train_dataset=tokenized_datasets["train"],
118
+ eval_dataset=tokenized_datasets["test"],
119
+ data_collator=data_collator,
120
+ )
121
+
122
+ # Start model training
123
+ trainer.train()
124
+
125
+ # Save and push the trained model and tokenizer
126
+ if push_to_hub:
127
+ trainer.push_to_hub(commit_message="Fine-tuned model with PEANuT")
128
+
129
+ # Save the model and tokenizer locally
130
+ model.save_pretrained(output_dir)
131
+ tokenizer.save_pretrained(output_dir)
132
+
133
+
134
+ if __name__ == "__main__":
135
+ import argparse
136
+
137
+ parser = argparse.ArgumentParser(description="Fine-tune LLaMA with PEANuT and PEFT")
138
+ parser.add_argument("--base_model", type=str, default="meta-llama/Llama-3.2-3B", help="Base model path or name")
139
+ parser.add_argument(
140
+ "--data_path", type=str, default="timdettmers/openassistant-guanaco", help="Dataset path or name"
141
+ )
142
+ parser.add_argument(
143
+ "--output_dir", type=str, default="path/to/output", help="Output directory for the fine-tuned model"
144
+ )
145
+ parser.add_argument("--batch_size", type=int, default=1, help="Batch size")
146
+ parser.add_argument("--num_epochs", type=int, default=1, help="Number of training epochs")
147
+ parser.add_argument("--learning_rate", type=float, default=1e-4, help="Learning rate")
148
+ parser.add_argument("--cutoff_len", type=int, default=512, help="Cutoff length for tokenization")
149
+ parser.add_argument("--val_set_size", type=int, default=500, help="Validation set size")
150
+ parser.add_argument("--eval_step", type=int, default=10, help="Evaluation step interval")
151
+ parser.add_argument("--save_step", type=int, default=100, help="Save step interval")
152
+ parser.add_argument("--device", type=str, default="auto", help="Device to use for training")
153
+ parser.add_argument("--peanut_r", type=int, default=32, help="PEANuT rank")
154
+ parser.add_argument(
155
+ "--peanut_depth",
156
+ type=int,
157
+ default=0,
158
+ help="Total number of PEANuT transforms including A and B (must be even and >= 2)",
159
+ )
160
+ parser.add_argument(
161
+ "--peanut_scaling", type=float, default=1.0, help="PEANuT scaling factor applied to adapter output"
162
+ )
163
+ parser.add_argument(
164
+ "--peanut_act_fn",
165
+ type=str,
166
+ default="relu",
167
+ help="Activation used inside PEANuT neural tweakers (must be a valid transformers ACT2FN key)",
168
+ )
169
+ parser.add_argument(
170
+ "--peanut_target_modules", type=str, default=None, help="Comma-separated list of target modules for PEANuT"
171
+ )
172
+ parser.add_argument(
173
+ "--peanut_init_weights",
174
+ action=argparse.BooleanOptionalAction,
175
+ default=True,
176
+ help="Use PEANuT default init: zero-init B and Kaiming-init the other layers",
177
+ )
178
+ parser.add_argument(
179
+ "--hub_model_id",
180
+ type=str,
181
+ default="path/to/repo",
182
+ help="Repository name to push the model on the Hugging Face Hub",
183
+ )
184
+ parser.add_argument("--push_to_hub", action="store_true", help="Whether to push the model to Hugging Face Hub")
185
+ args = parser.parse_args()
186
+
187
+ train_model(
188
+ base_model=args.base_model,
189
+ data_path=args.data_path,
190
+ output_dir=args.output_dir,
191
+ batch_size=args.batch_size,
192
+ num_epochs=args.num_epochs,
193
+ learning_rate=args.learning_rate,
194
+ cutoff_len=args.cutoff_len,
195
+ val_set_size=args.val_set_size,
196
+ eval_step=args.eval_step,
197
+ save_step=args.save_step,
198
+ device=args.device,
199
+ peanut_r=args.peanut_r,
200
+ peanut_depth=args.peanut_depth,
201
+ peanut_scaling=args.peanut_scaling,
202
+ peanut_act_fn=args.peanut_act_fn,
203
+ peanut_target_modules=args.peanut_target_modules,
204
+ peanut_init_weights=args.peanut_init_weights,
205
+ hub_model_id=args.hub_model_id,
206
+ push_to_hub=args.push_to_hub,
207
+ )
tasks/tasksmith-c488fc138ba1/tests/source/examples/pissa_finetuning/README.md ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PiSSA: Principal Singular values and Singular vectors Adaptation
2
+ ## Introduction ([Paper](https://huggingface.co/papers/2404.02948), [code](https://github.com/GraphPKU/PiSSA))
3
+ PiSSA represents a matrix $W\in\mathbb{R}^{m\times n}$ within the model by the product of two trainable matrices $A \in \mathbb{R}^{m\times r}$ and $B \in \mathbb{R}^{r\times n}$, where $r \ll \min(m, n)$, plus a residual matrix $W^{res}\in\mathbb{R}^{m\times n}$ for error correction. Singular value decomposition (SVD) is employed to factorize $W$, and the principal singular values and vectors of $W$ are utilized to initialize $A$ and $B$. The residual singular values and vectors initialize the residual matrix $W^{res}$, which keeps frozen during fine-tuning. This straightforward modification allows PiSSA to converge more rapidly than LoRA and ultimately attain superior performance. Moreover, PiSSA reduces the quantization error compared to QLoRA, leading to further enhancements.
4
+
5
+ ## Quick Start
6
+ ```python
7
+ import torch
8
+ from peft import LoraConfig, get_peft_model
9
+ from transformers import AutoTokenizer, AutoModelForCausalLM
10
+ from trl import SFTConfig, SFTTrainer
11
+ from datasets import load_dataset
12
+
13
+ model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf", dtype=torch.bfloat16, device_map="auto")
14
+ tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
15
+ tokenizer.pad_token_id = tokenizer.eos_token_id
16
+ lora_config = LoraConfig(
17
+ # init_lora_weights="pissa", # Configure the initialization method to "pissa", which may take several minutes to execute SVD on the pre-trained model.
18
+ init_lora_weights="pissa_niter_4", # Initialize the PiSSA with fast SVD, which completes in just a few seconds.
19
+ )
20
+ peft_model = get_peft_model(model, lora_config)
21
+
22
+ peft_model.print_trainable_parameters()
23
+
24
+ dataset = load_dataset("imdb", split="train[:1%]")
25
+
26
+ training_args = SFTConfig(dataset_text_field="text", max_length=128)
27
+ trainer = SFTTrainer(
28
+ model=peft_model,
29
+ args=training_args,
30
+ train_dataset=dataset,
31
+ processing_class=tokenizer,
32
+ )
33
+ trainer.train()
34
+ peft_model.save_pretrained("pissa-llama-2-7b")
35
+ ```
36
+ When utilizing fast SVD, reducing the rank and the number of iterations decreases the time required. However, this approach leads to higher errors in the computed matrices $A$ and $B$. To preserve the model's initial capabilities, we calculate the residual matrix by $W^{res} = W - BA$. Even with potential errors in $A$ and $B$, the sum of $W^{res}$ and $BA$ accurately equals $W$.
37
+
38
+
39
+ To utilize the fine-tuned PiSSA modules, simply run the following command:
40
+ ```python
41
+ import torch
42
+ from peft import PeftModel
43
+ from transformers import AutoModelForCausalLM
44
+
45
+ model = AutoModelForCausalLM.from_pretrained(
46
+ "meta-llama/Llama-2-7b-hf", dtype=torch.bfloat16, device_map="auto"
47
+ )
48
+ # Performs SVD again to initialize the residual model and loads the state_dict of the fine-tuned PiSSA modules.
49
+ peft_model = PeftModel.from_pretrained(model, "pissa-llama-2-7b")
50
+ ```
51
+
52
+ ## Advanced Usage
53
+
54
+ ### Access the preprocessed models
55
+ We recommend downloading decomposed models directly from the [Hugging Face Collections](https://huggingface.co/collections/fxmeng/pissa-661ce700721235e542a5d7a8) instead of performing SVD every time.
56
+ If the existing models do not meet your needs, apply PiSSA initialization to a pre-trained model and store the decomposed model locally:
57
+ ```bash
58
+ python preprocess.py \
59
+ --base_model_name_or_path meta-llama/Llama-2-7b-hf \
60
+ --init_lora_weights pissa \
61
+ --output_dir pissa-llama-2-7b-r32-alpha-32 \
62
+ --lora_r 32 \
63
+ --lora_alpha 32 \
64
+ --lora_dropout 0 \
65
+ --bits bf16
66
+ ```
67
+
68
+ ### Convert PiSSA to LoRA
69
+ The main advantage of PiSSA is concentrated during the training phase. For a trained PiSSA adapter, we recommend converting it equivalently to the LoRA adapter for using and sharing.
70
+ ```python
71
+ # The fine-tuned matrices $A$ and $B$ in PiSSA adapter is saved and should be combined with the residual model.
72
+ peft_model.save_pretrained(output_dir)
73
+ # Given the matrices $A_0$ and $B_0$, initialized by PiSSA and untrained, and the trained matrices $A$ and $B$,
74
+ # we can convert these to LoRA by setting $\Delta W = A \times B - A_0 \times B_0 = [A \mid A_0] \times [B \mid -B_0]^T = A'B'$.
75
+ peft_model.save_pretrained(output_dir, path_initial_model_for_weight_conversion="pissa_init")
76
+
77
+ ```
78
+ This conversion enables the loading of LoRA on top of a standard base model:
79
+
80
+ ```python
81
+ import torch
82
+ from peft import PeftModel
83
+ from transformers import AutoModelForCausalLM
84
+
85
+ model = AutoModelForCausalLM.from_pretrained(
86
+ "meta-llama/Llama-2-7b-hf", dtype=torch.bfloat16, device_map="auto"
87
+ )
88
+ # No SVD is performed during this step, and the base model remains unaltered.
89
+ peft_model = PeftModel.from_pretrained(model, "pissa-llama-2-7b-lora")
90
+ ```
91
+ Utilizing the converted LoRA does not require modifying the parameters of the base model. When multiple converted LoRAs are needed simultaneously, each adapter operates independently without interference, allowing for the adapters to be freely deleted or added.
92
+
93
+ Note that this conversion is not supported if `rslora` is used in combination with `rank_pattern` or `alpha_pattern`.
94
+
95
+ ### Fine-tune in 4-bit or 8-bit
96
+ If quantization fine-tuning is desired, it is necessary to first decompose the original model at full precision and then reload the residual model in either 4-bit or 8-bit configurations.
97
+ ```shell
98
+ python pissa_finetuning.py \
99
+ --residual_model_name_or_path fxmeng/pissa-llama-2-7b-r16-alpha-16 \
100
+ --output_dir output/pissa-llama-2-7b-r16-alpha-16-metamath-10k \
101
+ --bits nf4 \
102
+ --data_path meta-math/MetaMathQA \
103
+ --dataset_split train[:100000] \
104
+ --dataset_field query response \
105
+ --bf16 True \
106
+ --num_train_epochs 1 \
107
+ --per_device_train_batch_size 32 \
108
+ --gradient_accumulation_steps 4 \
109
+ --save_strategy "steps" \
110
+ --save_steps 1000 \
111
+ --save_total_limit 1 \
112
+ --logging_steps 1 \
113
+ --learning_rate 2e-5 \
114
+ --weight_decay 0. \
115
+ --warmup_steps 0.03 \
116
+ --tf32 True \
117
+ --report_to none \
118
+ --convert_pissa_to_lora
119
+ ```
120
+
121
+ This approach ensures the preservation of high-frequency, out-of-distribution parameters in the low-rank PiSSA modules, resulting in reduced quantization errors during the quantization of the residual model.
122
+
123
+ ## Citation
124
+ ```
125
+ @article{meng2024pissa,
126
+ title={PiSSA: Principal Singular Values and Singular Vectors Adaptation of Large Language Models},
127
+ author={Meng, Fanxu and Wang, Zhaohui and Zhang, Muhan},
128
+ journal={arXiv preprint arXiv:2404.02948},
129
+ year={2024}
130
+ }
131
+ ```
tasks/tasksmith-c488fc138ba1/tests/source/examples/pissa_finetuning/pissa_finetuning.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 os
16
+ from dataclasses import dataclass, field
17
+ from typing import Optional
18
+
19
+ import torch
20
+ from datasets import load_dataset
21
+ from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, HfArgumentParser
22
+ from trl import SFTConfig, SFTTrainer
23
+
24
+ from peft import LoraConfig, PeftModel, get_peft_model, prepare_model_for_kbit_training
25
+
26
+
27
+ @dataclass
28
+ class ScriptArguments(SFTConfig):
29
+ # model configs
30
+ base_model_name_or_path: Optional[str] = field(
31
+ default=None, metadata={"help": "The name or path of the fp32/16 base model."}
32
+ )
33
+ residual_model_name_or_path: Optional[str] = field(
34
+ default=None,
35
+ metadata={
36
+ "help": "The name or path of the fp32/16 residual model. (`['fxmeng/pissa-llama-2-7b-r16-alpha-16']`)"
37
+ },
38
+ )
39
+ bits: str = field(default="fp32", metadata={"help": "(`['fp4', 'nf4', 'int8', 'bf16', 'fp16', fp32]`)"})
40
+ init_lora_weights: str = field(default="pissa", metadata={"help": "(`['gaussian', 'pissa', 'pissa_niter_4']`)"})
41
+ lora_r: int = field(default=16)
42
+ lora_alpha: int = field(default=16)
43
+ lora_dropout: float = field(default=0)
44
+ convert_pissa_to_lora: bool = field(default=False)
45
+ merge_and_save: bool = field(default=False)
46
+ # dataset configs
47
+ data_path: str = field(default="imdb", metadata={"help": "Path to the training data."})
48
+ dataset_split: str = field(default="train[:1%]", metadata={"help": "(`['train', 'test', 'eval']`):"})
49
+ dataset_field: list[str] = field(default=None, metadata={"help": "Fields of dataset input and output."})
50
+
51
+
52
+ parser = HfArgumentParser(ScriptArguments)
53
+ script_args = parser.parse_args_into_dataclasses()[0]
54
+ print(script_args)
55
+
56
+ print(f"Load pre-processed residual model in {script_args.bits} bits.")
57
+ if script_args.bits in ["nf4", "fp4", "int8"]:
58
+ quantization_config = BitsAndBytesConfig(
59
+ load_in_4bit=(script_args.bits == "nf4" or script_args.bits == "fp4"),
60
+ load_in_8bit=script_args.bits == "int8",
61
+ bnb_4bit_quant_type=script_args.bits,
62
+ bnb_4bit_use_double_quant=True,
63
+ bnb_4bit_compute_dtype=torch.bfloat16,
64
+ )
65
+ res_model = AutoModelForCausalLM.from_pretrained(
66
+ script_args.residual_model_name_or_path, quantization_config=quantization_config, low_cpu_mem_usage=True
67
+ )
68
+ res_model = prepare_model_for_kbit_training(res_model)
69
+ print("Wrapping the residual model with PiSSA.")
70
+ peft_model = PeftModel.from_pretrained(
71
+ res_model, script_args.residual_model_name_or_path, subfolder="pissa_init", is_trainable=True
72
+ )
73
+ tokenizer = AutoTokenizer.from_pretrained(script_args.residual_model_name_or_path)
74
+
75
+ elif script_args.residual_model_name_or_path is not None:
76
+ res_model = AutoModelForCausalLM.from_pretrained(
77
+ script_args.residual_model_name_or_path,
78
+ dtype=(
79
+ torch.float16
80
+ if script_args.bits == "fp16"
81
+ else (torch.bfloat16 if script_args.bits == "bf16" else torch.float32)
82
+ ),
83
+ device_map="auto",
84
+ )
85
+ print("Wrapping the residual model with PiSSA.")
86
+ peft_model = PeftModel.from_pretrained(
87
+ res_model, script_args.residual_model_name_or_path, subfolder="pissa_init", is_trainable=True
88
+ )
89
+ tokenizer = AutoTokenizer.from_pretrained(script_args.residual_model_name_or_path)
90
+
91
+ elif script_args.base_model_name_or_path is not None:
92
+ print(
93
+ f"No available pre-processed model, manually initialize a PiSSA using {script_args.base_model_name_or_path}."
94
+ )
95
+ model = AutoModelForCausalLM.from_pretrained(
96
+ script_args.base_model_name_or_path,
97
+ dtype=(
98
+ torch.float16
99
+ if script_args.bits == "fp16"
100
+ else (torch.bfloat16 if script_args.bits == "bf16" else torch.float32)
101
+ ),
102
+ device_map="auto",
103
+ )
104
+ tokenizer = AutoTokenizer.from_pretrained(script_args.base_model_name_or_path)
105
+ tokenizer.pad_token_id = tokenizer.eos_token_id
106
+ lora_config = LoraConfig(
107
+ r=script_args.lora_r,
108
+ lora_alpha=script_args.lora_alpha,
109
+ init_lora_weights=script_args.init_lora_weights,
110
+ lora_dropout=script_args.lora_dropout,
111
+ target_modules=["q_proj", "o_proj", "k_proj", "v_proj", "gate_proj", "up_proj", "down_proj"],
112
+ bias="none",
113
+ task_type="CAUSAL_LM",
114
+ )
115
+ peft_model = get_peft_model(model, lora_config)
116
+
117
+ print(peft_model)
118
+ peft_model.print_trainable_parameters()
119
+
120
+ print(f"Training PiSSA with trl on the {script_args.data_path}[{script_args.dataset_split}] dataset.")
121
+ dataset = load_dataset(script_args.data_path, split=script_args.dataset_split)
122
+ dataset = dataset.map(
123
+ lambda example: {
124
+ "text": f"### USER: {example[script_args.dataset_field[0]]}\n### ASSISTANT: {example[script_args.dataset_field[1]]}"
125
+ }
126
+ )
127
+
128
+ trainer = SFTTrainer(
129
+ model=peft_model,
130
+ args=script_args,
131
+ train_dataset=dataset,
132
+ processing_class=tokenizer,
133
+ )
134
+ trainer.train()
135
+ trainer.save_state()
136
+ ############################## Upon training completion, convert and save PiSSA in LoRA format ##############################
137
+ if script_args.convert_pissa_to_lora:
138
+ peft_model.save_pretrained(
139
+ os.path.join(script_args.output_dir, "pissa_lora"),
140
+ path_initial_model_for_weight_conversion=os.path.join(script_args.residual_model_name_or_path, "pissa_init"),
141
+ )
142
+ else:
143
+ peft_model.save_pretrained(
144
+ os.path.join(script_args.output_dir, "pissa_ft"),
145
+ )
146
+
147
+ if script_args.merge_and_save:
148
+ model = peft_model.merge_and_unload()
149
+ model.save_pretrained(os.path.join(script_args.output_dir, "pissa_merged"))
150
+ tokenizer.save_pretrained(os.path.join(script_args.output_dir, "pissa_merged"))
tasks/tasksmith-c488fc138ba1/tests/source/examples/pissa_finetuning/preprocess.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 argparse
16
+ import os
17
+
18
+ import torch
19
+ from transformers import AutoModelForCausalLM, AutoTokenizer
20
+
21
+ from peft import LoraConfig, get_peft_model
22
+
23
+
24
+ parser = argparse.ArgumentParser(description="Merge Adapter to Base Model")
25
+ parser.add_argument(
26
+ "--base_model_name_or_path",
27
+ help="The name or path of the fp32/16 base model.",
28
+ )
29
+ parser.add_argument("--output_dir", type=str, help="The directory to save the PiSSA model.")
30
+ parser.add_argument("--bits", type=str, default="bf16", choices=["bf16", "fp16", "fp32"])
31
+ parser.add_argument(
32
+ "--init_lora_weights", type=str, default="pissa", help="(`['pissa', 'pissa_niter_[number of iters]']`)"
33
+ )
34
+ parser.add_argument("--lora_r", type=int, default=128)
35
+ parser.add_argument("--lora_alpha", type=int, default=128)
36
+ parser.add_argument("--lora_dropout", type=int, default=0)
37
+ script_args = parser.parse_args()
38
+ print(script_args)
39
+
40
+ model = AutoModelForCausalLM.from_pretrained(
41
+ script_args.base_model_name_or_path,
42
+ dtype=(
43
+ torch.float16
44
+ if script_args.bits == "fp16"
45
+ else (torch.bfloat16 if script_args.bits == "bf16" else torch.float32)
46
+ ),
47
+ device_map="auto",
48
+ )
49
+ tokenizer = AutoTokenizer.from_pretrained(script_args.base_model_name_or_path)
50
+ tokenizer.pad_token_id = tokenizer.eos_token_id
51
+ lora_config = LoraConfig(
52
+ r=script_args.lora_r,
53
+ lora_alpha=script_args.lora_alpha,
54
+ init_lora_weights=script_args.init_lora_weights,
55
+ lora_dropout=script_args.lora_dropout,
56
+ target_modules=["q_proj", "o_proj", "k_proj", "v_proj", "gate_proj", "up_proj", "down_proj"],
57
+ bias="none",
58
+ task_type="CAUSAL_LM",
59
+ )
60
+ peft_model = get_peft_model(model, lora_config)
61
+
62
+ # Save PiSSA modules:
63
+ peft_model.peft_config["default"].init_lora_weights = True
64
+ peft_model.save_pretrained(os.path.join(script_args.output_dir, "pissa_init"))
65
+ # Save residual model:
66
+ peft_model = peft_model.unload()
67
+ peft_model.save_pretrained(script_args.output_dir)
68
+ # Save the tokenizer:
69
+ tokenizer.save_pretrained(script_args.output_dir)
tasks/tasksmith-c488fc138ba1/tests/source/examples/poly/peft_poly_seq2seq_with_generate.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
tasks/tasksmith-c488fc138ba1/tests/source/examples/psoft_finetuning/README.md ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Efficient Orthogonal Fine-Tuning with Principal Subspace Adaptation (PSOFT)
2
+ ## Introduction ([Paper](https://huggingface.co/papers/2505.11235), [code](https://github.com/fei407/PSOFT))
3
+ PSOFT aims to preserve the geometric relationships among pre-trained weight column vectors—a core principle of OFT—while achieving a balanced trade-off across parameter, computation, and memory efficiency. Unlike existing OFT variants (e.g., OFTv2, BOFT, and GOFT) that rely on sparsity-based designs, PSOFT adopts a low-rank principal subspace perspective, bridging the gap between LoRA and OFT. PSOFT confines orthogonal fine-tuning to a principal subspace, offering theoretical guarantees via orthogonality constraints on the down-projection matrix, while enabling practical adaptability through two low-dimensional tunable vectors.
4
+
5
+
6
+ ## Quick Start
7
+ ```python
8
+ import torch
9
+ from peft import PsoftConfig, get_peft_model
10
+ from transformers import AutoTokenizer, AutoModelForCausalLM
11
+ from trl import SFTConfig, SFTTrainer
12
+ from datasets import load_dataset
13
+
14
+ model_name = "facebook/opt-125m"
15
+
16
+ model = AutoModelForCausalLM.from_pretrained(model_name)
17
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
18
+ tokenizer.pad_token_id = tokenizer.eos_token_id
19
+
20
+ psoft_config = PsoftConfig(
21
+ r=32,
22
+ psoft_alpha=32,
23
+ )
24
+
25
+ peft_model = get_peft_model(model, psoft_config)
26
+ peft_model.print_trainable_parameters()
27
+
28
+ dataset = load_dataset("imdb", split="train[:1%]")
29
+
30
+ training_args = SFTConfig(dataset_text_field="text", max_length=128)
31
+
32
+ trainer = SFTTrainer(
33
+ model=peft_model,
34
+ args=training_args,
35
+ train_dataset=dataset,
36
+ processing_class=tokenizer,
37
+ )
38
+
39
+ trainer.train()
40
+ peft_model.save_pretrained("psoft-opt-125m")
41
+ ```
42
+
43
+ ## Further examples on LLaMA-3.2-3B
44
+ ```shell
45
+ python psoft_finetuning.py \
46
+ --base_model_name_or_path meta-llama/Llama-3.2-3B \
47
+ --output_dir ./outputs/psoft-llama3.2-3b-imdb \
48
+ --data_path imdb \
49
+ --dataset_split "train[:1%]" \
50
+ --max_length 128 \
51
+ --num_train_epochs 1 \
52
+ --per_device_train_batch_size 1 \
53
+ --gradient_accumulation_steps 8 \
54
+ --learning_rate 5e-4 \
55
+ --bits bf16 \
56
+ --r 128 \
57
+ --psoft_alpha 128 \
58
+ --target_modules q_proj v_proj
59
+ ```
60
+
61
+ ## Best Practices
62
+ 1. **Rank Choice**: Smaller ranks (e.g., `32–128`) are suitable for simpler tasks, while larger ranks (e.g., `64–256`) provide greater expressiveness for more complex tasks at the cost of increased parameters and computation.
63
+ 2. **Scaling Factor**: The scaling factor is typically set to $r$ in PSOFT.
64
+ 3. **Learning Rate**: Use standard learning rates (e.g., `1e-4` to `5e-3`) for stable training.
65
+ 4. **SVD Initialization**: The `lowrank` option is more memory- and compute-efficient than `full`, making it more suitable for large models.
66
+ 5. **Cayley–Neumann Approximation**: When the rank is large, enabling the Cayley–Neumann approximation can significantly improve computational efficiency, while the benefit is less pronounced for small ranks. In practice, a small number of Neumann series terms (typically `5`) usually provides a good balance between accuracy and efficiency.
67
+
68
+ ## Citation
69
+ ```
70
+ @inproceedings{wu2026efficient,
71
+ title={Efficient Orthogonal Fine-Tuning with Principal Subspace Adaptation},
72
+ author={Wu, Fei and Hu, Jia and Min, Geyong and Wang, Shiqiang},
73
+ booktitle={The Fourteenth International Conference on Learning Representations},
74
+ year={2026},
75
+ url={https://openreview.net/forum?id=FSHrinMArK}
76
+ }
77
+ ```
tasks/tasksmith-c488fc138ba1/tests/source/examples/psoft_finetuning/psoft_finetuning.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 os
16
+ from dataclasses import dataclass, field
17
+ from typing import Optional
18
+
19
+ import torch
20
+ from datasets import load_dataset
21
+ from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser
22
+ from trl import SFTConfig, SFTTrainer
23
+
24
+ from peft import PsoftConfig, get_peft_model
25
+
26
+
27
+ @dataclass
28
+ class ScriptArguments(SFTConfig):
29
+ # --- model ---
30
+ base_model_name_or_path: Optional[str] = field(
31
+ default=None, metadata={"help": "The name or path of the fp32/16 base model."}
32
+ )
33
+ bits: str = field(
34
+ default="fp32",
35
+ metadata={"help": "Precision to load the base model. Choices: ['bf16', 'fp16', 'fp32']."},
36
+ )
37
+
38
+ # --- PSOFT ---
39
+ r: int = field(default=32, metadata={"help": "Rank (r): dimension of trainable R."})
40
+ psoft_alpha: int = field(default=32, metadata={"help": "Scaling factor (typically set to r)."})
41
+ target_modules: list[str] = field(
42
+ default_factory=lambda: ["q_proj", "v_proj"],
43
+ metadata={"help": "Target module names, e.g. ['q_proj','k_proj','v_proj','o_proj', ...]."},
44
+ )
45
+
46
+ # SVD / init
47
+ ab_svd_init: str = field(
48
+ default="psoft_init",
49
+ metadata={"help": "Principal-subspace init identifier (e.g. 'psoft_init')."},
50
+ )
51
+ psoft_svd: str = field(
52
+ default="full",
53
+ metadata={"help": "SVD method. Typical choices: ['full', 'lowrank']."},
54
+ )
55
+ psoft_svd_lowrank_niter: Optional[int] = field(
56
+ default=None,
57
+ metadata={"help": "If psoft_svd='lowrank', number of iterations for lowrank SVD (optional)."},
58
+ )
59
+
60
+ # Orth / relaxation
61
+ psoft_orth: bool = field(default=True, metadata={"help": "Use orthogonal R (Cayley parameterization)."})
62
+ psoft_mag_a: bool = field(default=True, metadata={"help": "Enable tunable vector alpha (relaxed mode)."})
63
+ psoft_mag_b: bool = field(default=True, metadata={"help": "Enable tunable vector beta (relaxed mode)."})
64
+
65
+ # Cayley–Neumann approximation
66
+ use_cayley_neumann: bool = field(default=False, metadata={"help": "Enable Cayley-Neumann approximation."})
67
+ num_cayley_neumann_terms: int = field(default=5, metadata={"help": "Number of Neumann series terms."})
68
+ cayley_neumann_eps: Optional[float] = field(
69
+ default=None, metadata={"help": "Optional eps for numerical stability."}
70
+ )
71
+
72
+ # --- data ---
73
+ data_path: str = field(default="imdb", metadata={"help": "Dataset name/path for training."})
74
+ dataset_split: str = field(default="train[:1%]", metadata={"help": "Dataset split, e.g. 'train[:1%]'."})
75
+ dataset_field: Optional[list[str]] = field(
76
+ default=None,
77
+ metadata={
78
+ "help": (
79
+ "Fields used to build SFT text. "
80
+ "If provided, will build: '### USER: <field0>\\n### ASSISTANT: <field1>'. "
81
+ "If None, must already have a 'text' column."
82
+ )
83
+ },
84
+ )
85
+
86
+
87
+ def _dtype_from_bits(bits: str) -> torch.dtype:
88
+ bits = bits.lower()
89
+ if bits == "bf16":
90
+ return torch.bfloat16
91
+ if bits == "fp16":
92
+ return torch.float16
93
+ if bits == "fp32":
94
+ return torch.float32
95
+ raise ValueError(f"Unknown bits={bits}. Use one of: bf16, fp16, fp32.")
96
+
97
+
98
+ def main():
99
+ parser = HfArgumentParser(ScriptArguments)
100
+ script_args = parser.parse_args_into_dataclasses()[0]
101
+ print(script_args)
102
+
103
+ if script_args.base_model_name_or_path is None:
104
+ raise ValueError("--base_model_name_or_path is required.")
105
+
106
+ # PSOFT does NOT support quantized layers (nf4/int8/etc.).
107
+ # We only allow fp16/bf16/fp32 here to avoid accidental quantized loading.
108
+ if script_args.bits.lower() not in {"bf16", "fp16", "fp32"}:
109
+ raise ValueError("PSOFT example only supports bits in ['bf16','fp16','fp32'] (no quantization).")
110
+
111
+ torch_dtype = _dtype_from_bits(script_args.bits)
112
+
113
+ # Load base model
114
+ model = AutoModelForCausalLM.from_pretrained(
115
+ script_args.base_model_name_or_path,
116
+ dtype=torch_dtype,
117
+ device_map="auto",
118
+ )
119
+ tokenizer = AutoTokenizer.from_pretrained(script_args.base_model_name_or_path)
120
+ if tokenizer.pad_token_id is None:
121
+ tokenizer.pad_token_id = tokenizer.eos_token_id
122
+
123
+ # Build PSOFT config
124
+ psoft_kwargs = {
125
+ "r": script_args.r,
126
+ "psoft_alpha": script_args.psoft_alpha,
127
+ "target_modules": script_args.target_modules,
128
+ "ab_svd_init": script_args.ab_svd_init,
129
+ "psoft_svd": script_args.psoft_svd,
130
+ "psoft_orth": script_args.psoft_orth,
131
+ "psoft_mag_a": script_args.psoft_mag_a,
132
+ "psoft_mag_b": script_args.psoft_mag_b,
133
+ "use_cayley_neumann": script_args.use_cayley_neumann,
134
+ "num_cayley_neumann_terms": script_args.num_cayley_neumann_terms,
135
+ "cayley_neumann_eps": script_args.cayley_neumann_eps,
136
+ "task_type": "CAUSAL_LM",
137
+ }
138
+ # Only pass lowrank_niter when user sets it (and typically when psoft_svd='lowrank')
139
+ if script_args.psoft_svd_lowrank_niter is not None:
140
+ psoft_kwargs["psoft_svd_lowrank_niter"] = script_args.psoft_svd_lowrank_niter
141
+
142
+ peft_config = PsoftConfig(**psoft_kwargs)
143
+ model = get_peft_model(model, peft_config)
144
+
145
+ model.print_trainable_parameters()
146
+
147
+ # Load dataset
148
+ dataset = load_dataset(script_args.data_path, split=script_args.dataset_split)
149
+
150
+ # Ensure a "text" field for SFTTrainer
151
+ if script_args.dataset_field is not None:
152
+ if len(script_args.dataset_field) != 2:
153
+ raise ValueError("dataset_field must be a list of exactly 2 field names: [input_field, output_field].")
154
+
155
+ in_f, out_f = script_args.dataset_field[0], script_args.dataset_field[1]
156
+
157
+ def to_sft_text(example):
158
+ return {"text": f"### USER: {example[in_f]}\n### ASSISTANT: {example[out_f]}"}
159
+
160
+ dataset = dataset.map(to_sft_text)
161
+ else:
162
+ if "text" not in dataset.column_names:
163
+ raise ValueError("dataset_field is None but dataset has no 'text' column. Provide dataset_field.")
164
+
165
+ # Train
166
+ trainer = SFTTrainer(
167
+ model=model,
168
+ args=script_args,
169
+ train_dataset=dataset,
170
+ processing_class=tokenizer,
171
+ )
172
+ trainer.train()
173
+ trainer.save_state()
174
+
175
+ # Save adapter (PSOFT)
176
+ os.makedirs(script_args.output_dir, exist_ok=True)
177
+ model.save_pretrained(os.path.join(script_args.output_dir, "psoft_ft"))
178
+ tokenizer.save_pretrained(os.path.join(script_args.output_dir, "psoft_ft"))
179
+
180
+
181
+ if __name__ == "__main__":
182
+ main()